heal-cli 0.4.0

Hook-driven Evaluation & Autonomous Loop — code-health harness CLI for AI coding agents
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
//! `heal diff [<git-ref>]` — bucket-style diff between the current
//! findings and the findings recomputed at an arbitrary git ref.
//! Default ref: the calibration baseline (`meta.calibrated_at_sha`,
//! recorded by `heal init` / `heal calibrate --force`), falling back to
//! `HEAD` when no baseline SHA is recorded — so "Progress: N% complete"
//! reads naturally as "drained since calibration".
//!
//! Two paths:
//!
//! 1. **Cache hit.** `latest.json.head_sha` matches the resolved ref
//!    → read the cached `FindingsRecord` directly. Fast.
//! 2. **Worktree fallback.** `git worktree add --detach <tempdir> <sha>`
//!    materialises the source at the ref, runs the observer pipeline
//!    against it (using the *current* `config.toml`/`calibration.toml`
//!    so the comparison is apples-to-apples), and removes the worktree
//!    on the way out. Gated by `[diff].max_loc_threshold` (default
//!    `200_000` LOC) — over the threshold the command exits with code 2
//!    and points at the manual two-branch flow instead of running an
//!    expensive scan.
//!
//! Output buckets — Resolved / Regressed / Improved / New / Unchanged —
//! plus a two-tier progress block: `Progress (T0 drain)` foregrounded
//! against the must-drain queue (Critical AND hotspot under the active
//! `[policy.drain]`), and a secondary `Population` line over the whole
//! baseline that includes Advisory churn. JSON shape is stable for
//! skills and CI; new fields (`t0_resolved`, `t0_total`,
//! `t0_progress_pct`, `DiffEntry.from_hotspot`) are additive.
//!
//! The human renderer hides entries whose `from` and `to` Severity
//! both sit below High by default — typical baselines drown the
//! actionable rows otherwise. `--all` bypasses the filter and also
//! surfaces the Improved / Unchanged buckets. JSON output is
//! unfiltered.
//!
//! Note this is **broader** than `heal status`'s default visibility
//! gate (Critical OR High+hotspot). The two views differ on purpose:
//! status surfaces today's drain queue, where hotspot is the
//! priority signal; diff surfaces *changes* between two refs, where
//! a plain-High regression is itself worth seeing even without the
//! hotspot decoration.

use std::collections::HashMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{anyhow, Context, Result};
use serde::Serialize;
use tempfile::TempDir;

use crate::core::accepted::read_accepted;
use crate::core::calibration::Calibration;
use crate::core::config::{load_from_project, Config, DrainTier, PolicyDrainConfig};
use crate::core::finding::Finding;
use crate::core::findings_cache::{read_latest, FindingsRecord};
use crate::core::severity::Severity;
use crate::core::term::{
    ansi_wrap, write_through_pager, ANSI_CYAN, ANSI_GREEN, ANSI_RED, ANSI_YELLOW,
};
use crate::core::HealPaths;
use crate::observer::code::loc::LocObserver;
use crate::observer::shared::git;
use crate::observers::build_record;

/// Exit status when `[diff].max_loc_threshold` is exceeded. Wraps the
/// human-readable guidance in a `process::exit` so scripts can branch on
/// the code without parsing stderr.
pub const DIFF_LOC_THRESHOLD_EXIT_CODE: i32 = 2;

pub fn run(
    project: &Path,
    revspec: Option<&str>,
    workspace: Option<&str>,
    show_all: bool,
    as_json: bool,
    no_pager: bool,
) -> Result<()> {
    let paths = HealPaths::new(project);
    let cfg = load_from_project(project).with_context(|| {
        format!(
            "loading {} (run `heal init` first?)",
            paths.config().display(),
        )
    })?;
    // No positional ref → diff against the calibration baseline so the
    // progress percentage reads as "drained since `heal init` /
    // `heal calibrate --force`". Falls back to `HEAD` if no baseline
    // SHA was recorded (e.g. calibration produced outside a git
    // worktree).
    let resolved_ref = match revspec {
        Some(r) => r.to_owned(),
        None => Calibration::load(&paths.calibration())
            .ok()
            .and_then(|c| c.meta.calibrated_at_sha)
            .unwrap_or_else(|| "HEAD".to_owned()),
    };
    let target_sha = git::resolve_ref(project, &resolved_ref).ok_or_else(|| {
        anyhow!(
            "could not resolve git ref `{resolved_ref}` in {} — is this a git repo?",
            project.display(),
        )
    })?;

    let mut from_record =
        load_or_recompute_from(project, &paths, &cfg, &resolved_ref, &target_sha)?;
    let to_head_sha = git::head_sha(project);
    let to_clean = git::worktree_clean(project).unwrap_or(false);
    let mut to_record = build_record(project, &paths, &cfg, to_head_sha, to_clean);

    // The baseline uses **today's** accepted-finding decisions —
    // apples-to-apples with the "to" view, same principle as
    // recomputing baseline findings under today's calibration.
    let accepted_map = read_accepted(&paths.findings_accepted())?;
    from_record.apply_accepted(&accepted_map);
    to_record.apply_accepted(&accepted_map);

    let diff = compute_diff(&from_record, &to_record, workspace, &cfg.policy.drain);
    if as_json {
        super::emit_json(&DiffReport {
            from_ref: &resolved_ref,
            from_sha: &target_sha,
            to_head_sha: to_record.head_sha.as_deref(),
            workspace,
            buckets: &diff,
        });
        return Ok(());
    }

    write_through_pager(no_pager, |out, colorize| {
        render_diff(
            &resolved_ref,
            &target_sha,
            workspace,
            &from_record,
            &to_record,
            &diff,
            show_all,
            colorize,
            out,
        )
    })
}

/// Build the "from" `FindingsRecord`. Prefers the cached `latest.json` when
/// its `head_sha` matches the target; otherwise materialises the source
/// at `<sha>` in a tempdir-backed `git worktree` and runs the observer
/// pipeline against it (after the LOC threshold check).
fn load_or_recompute_from(
    project: &Path,
    paths: &HealPaths,
    cfg: &Config,
    revspec: &str,
    target_sha: &str,
) -> Result<FindingsRecord> {
    if let Some(record) =
        read_latest(&paths.findings_latest())?.filter(|r| r.head_sha.as_deref() == Some(target_sha))
    {
        return Ok(record);
    }
    enforce_loc_threshold(project, cfg, revspec);
    recompute_at_ref(project, paths, cfg, target_sha)
}

/// Run a fast LOC count on the *current* worktree as a proxy for the
/// expected scan cost at `<sha>` (repos rarely change LOC by orders of
/// magnitude between commits). Returns when under the threshold or
/// exits the process with [`DIFF_LOC_THRESHOLD_EXIT_CODE`] otherwise.
fn enforce_loc_threshold(project: &Path, cfg: &Config, revspec: &str) {
    let report = LocObserver::from_config(cfg).scan(project);
    let total_loc = report.totals.code;
    let threshold = cfg.diff.max_loc_threshold;
    if u64::try_from(total_loc).unwrap_or(u64::MAX) <= threshold {
        return;
    }
    eprintln!("heal diff: project LOC {total_loc} exceeds [diff].max_loc_threshold ({threshold}).");
    eprintln!("Run two scans by hand instead:");
    eprintln!("  git worktree add --detach <tmp> {revspec}");
    eprintln!("  (cd <tmp> && heal status --refresh --json) > from.json");
    eprintln!("  heal status --refresh --json                > to.json");
    eprintln!("  # diff the two JSON payloads with your tool of choice");
    eprintln!("  git worktree remove <tmp>");
    eprintln!("Or raise the threshold in `.heal/config.toml` under `[diff]`.");
    std::process::exit(DIFF_LOC_THRESHOLD_EXIT_CODE);
}

/// Materialise `<sha>` in a fresh `git worktree`, run the observer
/// pipeline against it, and tear the worktree down. Uses the host
/// project's `.heal/calibration.toml` and `.heal/config.toml` so the
/// "from" record is comparable apples-to-apples with the live "to"
/// record under current rules.
fn recompute_at_ref(
    project: &Path,
    paths: &HealPaths,
    cfg: &Config,
    target_sha: &str,
) -> Result<FindingsRecord> {
    let tmp = TempDir::new().context("creating tempdir for `git worktree add`")?;
    let workdir = tmp.path().join("heal-diff");
    let _guard = WorktreeGuard::add(project, &workdir, target_sha)?;
    // A fresh `git worktree add --detach` is clean by construction.
    Ok(build_record(
        &workdir,
        paths,
        cfg,
        Some(target_sha.to_owned()),
        true,
    ))
}

/// RAII handle for a transient `git worktree`. `add` runs
/// `git worktree add --detach <path> <sha>` against the host project;
/// `Drop` runs `git worktree remove --force <path>` so a panic or `?`
/// short-circuit doesn't leave `.git/worktrees/` polluted.
struct WorktreeGuard {
    project: PathBuf,
    workdir: PathBuf,
}

impl WorktreeGuard {
    fn add(project: &Path, workdir: &Path, target_sha: &str) -> Result<Self> {
        if let Some(parent) = workdir.parent() {
            std::fs::create_dir_all(parent).ok();
        }
        let status = Command::new("git")
            .arg("-C")
            .arg(project)
            .args(["worktree", "add", "--detach", "--force"])
            .arg(workdir)
            .arg(target_sha)
            .status()
            .context("invoking `git worktree add`")?;
        if !status.success() {
            return Err(anyhow!(
                "`git worktree add` failed for {} at {target_sha}",
                workdir.display(),
            ));
        }
        Ok(Self {
            project: project.to_path_buf(),
            workdir: workdir.to_path_buf(),
        })
    }
}

impl Drop for WorktreeGuard {
    fn drop(&mut self) {
        let _ = Command::new("git")
            .arg("-C")
            .arg(&self.project)
            .args(["worktree", "remove", "--force"])
            .arg(&self.workdir)
            .status();
    }
}

#[derive(Debug, Serialize)]
struct DiffReport<'a> {
    /// User-supplied revspec ("HEAD", "main", "v0.2.1", "abc1234").
    from_ref: &'a str,
    /// Full 40-char SHA the revspec resolved to.
    from_sha: &'a str,
    to_head_sha: Option<&'a str>,
    /// Echo of the user-supplied `--workspace <path>` filter, when any.
    /// Skipped from JSON when omitted so the unfiltered shape stays
    /// terse.
    #[serde(skip_serializing_if = "Option::is_none")]
    workspace: Option<&'a str>,
    #[serde(flatten)]
    buckets: &'a Diff,
}

#[derive(Debug, Clone, Serialize, Default)]
pub(crate) struct Diff {
    pub resolved: Vec<DiffEntry>,
    pub regressed: Vec<DiffEntry>,
    pub improved: Vec<DiffEntry>,
    pub new_findings: Vec<DiffEntry>,
    pub unchanged: Vec<DiffEntry>,
    /// Population-side ratio: `resolved.len() / from.findings.len()`
    /// over the *whole* baseline, including Advisory churn. Kept as the
    /// stable JSON contract; new consumers should prefer
    /// `t0_progress_pct` for the actionable signal.
    pub progress_pct: f64,
    /// T0-baseline drain count (Critical AND hotspot, per the active
    /// `[policy.drain]`). Zero when the baseline had nothing in the
    /// must-drain tier.
    #[serde(default)]
    pub t0_total: usize,
    /// T0-baseline entries that no longer appear in `to`.
    #[serde(default)]
    pub t0_resolved: usize,
    /// `t0_resolved / t0_total` as a `[0.0, 1.0]` ratio. Zero when
    /// `t0_total` is zero — read alongside `t0_total` to disambiguate
    /// "no progress" from "no drain queue".
    #[serde(default)]
    pub t0_progress_pct: f64,
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct DiffEntry {
    pub finding_id: String,
    pub metric: String,
    pub file: String,
    pub from_severity: Option<Severity>,
    pub to_severity: Option<Severity>,
    /// Baseline-side hotspot flag. `false` for `new_findings` entries
    /// that have no `from`. Distinct from the curr-biased `hotspot`
    /// field below — needed so consumers can compute T0 / T1 counts of
    /// the *baseline* snapshot accurately.
    #[serde(default)]
    pub from_hotspot: bool,
    /// Curr-side hotspot when the finding still exists in `to`,
    /// otherwise the baseline-side hotspot. Kept for back-compat with
    /// existing skill consumers that read this single field; new
    /// callers should prefer `from_hotspot` for baseline classification.
    pub hotspot: bool,
    /// Baseline-side `accepted` flag. T0 progress excludes baseline-
    /// accepted entries — moving away from an accepted state isn't
    /// drain progress (the team already decided not to chase it).
    /// Skipped from JSON when false to keep the wire shape terse.
    #[serde(default, skip_serializing_if = "crate::core::finding::is_false")]
    pub from_accepted: bool,
}

impl DiffEntry {
    fn from_pair(prev: &Finding, curr: Option<&Finding>) -> Self {
        Self {
            finding_id: prev.id.clone(),
            metric: prev.metric.clone(),
            file: prev.location.file.display().to_string(),
            from_severity: Some(prev.severity),
            to_severity: curr.map(|c| c.severity),
            from_hotspot: prev.hotspot,
            hotspot: curr.map_or(prev.hotspot, |c| c.hotspot),
            from_accepted: prev.accepted,
        }
    }
    fn from_new(curr: &Finding) -> Self {
        Self {
            finding_id: curr.id.clone(),
            metric: curr.metric.clone(),
            file: curr.location.file.display().to_string(),
            from_severity: None,
            to_severity: Some(curr.severity),
            from_hotspot: false,
            hotspot: curr.hotspot,
            from_accepted: false,
        }
    }
}

pub(crate) fn compute_diff(
    from: &FindingsRecord,
    to: &FindingsRecord,
    workspace: Option<&str>,
    drain: &PolicyDrainConfig,
) -> Diff {
    let in_scope = |f: &Finding| -> bool {
        match workspace {
            None => true,
            Some(ws) => f.workspace.as_deref() == Some(ws),
        }
    };
    let from_by_id: HashMap<&str, &Finding> = from
        .findings
        .iter()
        .filter(|f| in_scope(f))
        .map(|f| (f.id.as_str(), f))
        .collect();
    let to_by_id: HashMap<&str, &Finding> = to
        .findings
        .iter()
        .filter(|f| in_scope(f))
        .map(|f| (f.id.as_str(), f))
        .collect();

    let mut diff = Diff::default();

    for (id, prev) in &from_by_id {
        match to_by_id.get(id) {
            None => diff.resolved.push(DiffEntry::from_pair(prev, None)),
            Some(curr) if curr.severity > prev.severity => {
                diff.regressed.push(DiffEntry::from_pair(prev, Some(curr)));
            }
            Some(curr) if curr.severity < prev.severity => {
                diff.improved.push(DiffEntry::from_pair(prev, Some(curr)));
            }
            Some(curr) => diff.unchanged.push(DiffEntry::from_pair(prev, Some(curr))),
        }
    }
    for (id, curr) in &to_by_id {
        if !from_by_id.contains_key(id) {
            diff.new_findings.push(DiffEntry::from_new(curr));
        }
    }

    let total = from_by_id.len();
    diff.progress_pct = if total == 0 {
        0.0
    } else {
        #[allow(clippy::cast_precision_loss)]
        let pct = diff.resolved.len() as f64 / total as f64;
        pct
    };

    let baseline_is_t0 = |e: &DiffEntry| {
        if e.from_accepted {
            return false;
        }
        e.from_severity
            .and_then(|sev| drain.tier_for_attrs(&e.metric, sev, e.from_hotspot))
            == Some(DrainTier::Must)
    };
    let t0_resolved = diff.resolved.iter().filter(|e| baseline_is_t0(e)).count();
    let t0_still_present = diff
        .regressed
        .iter()
        .chain(diff.improved.iter())
        .chain(diff.unchanged.iter())
        .filter(|e| baseline_is_t0(e))
        .count();
    diff.t0_resolved = t0_resolved;
    diff.t0_total = t0_resolved + t0_still_present;
    diff.t0_progress_pct = if diff.t0_total == 0 {
        0.0
    } else {
        #[allow(clippy::cast_precision_loss)]
        let pct = diff.t0_resolved as f64 / diff.t0_total as f64;
        pct
    };
    diff
}

#[allow(clippy::too_many_arguments)]
fn render_diff(
    revspec: &str,
    from_sha: &str,
    workspace: Option<&str>,
    from: &FindingsRecord,
    to: &FindingsRecord,
    diff: &Diff,
    show_all: bool,
    colorize: bool,
    out: &mut (impl Write + ?Sized),
) -> Result<()> {
    let short = &from_sha[..from_sha.len().min(8)];
    if let Some(ws) = workspace {
        writeln!(out, "  workspace: {ws}")?;
    }
    writeln!(
        out,
        "  from: {revspec} ({short})  ({} findings)",
        scoped_count(&from.findings, workspace),
    )?;
    writeln!(
        out,
        "  to:   live scan  HEAD={}  ({} findings)",
        to.head_sha.as_deref().unwrap_or(""),
        scoped_count(&to.findings, workspace),
    )?;
    writeln!(out)?;

    let mut hidden_low_severity = 0usize;
    let always_visible: [(&str, &str, &[DiffEntry]); 3] = [
        ("✅ Resolved", ANSI_GREEN, &diff.resolved),
        ("⚠️  Regressed", ANSI_RED, &diff.regressed),
        ("➕ New", ANSI_YELLOW, &diff.new_findings),
    ];
    for (label, color, items) in always_visible {
        render_bucket(
            label,
            color,
            items,
            show_all,
            &mut hidden_low_severity,
            colorize,
            out,
        )?;
    }
    if show_all {
        for (label, color, items) in [
            ("🟢 Improved", ANSI_GREEN, &diff.improved),
            ("▫️ Unchanged", ANSI_CYAN, &diff.unchanged),
        ] {
            render_bucket(
                label,
                color,
                items,
                true,
                &mut hidden_low_severity,
                colorize,
                out,
            )?;
        }
    } else {
        let hidden_buckets = diff.improved.len() + diff.unchanged.len();
        if hidden_buckets > 0 {
            writeln!(
                out,
                "  [Improved + Unchanged: {hidden_buckets} hidden — pass --all]"
            )?;
        }
        if hidden_low_severity > 0 {
            writeln!(
                out,
                "  [{hidden_low_severity} entries below High hidden — pass --all]"
            )?;
        }
    }
    writeln!(out)?;
    let resolved = diff.resolved.len();
    let total = scoped_count(&from.findings, workspace);
    if diff.t0_total == 0 {
        writeln!(out, "  Progress (T0 drain):  no T0 findings in baseline")?;
    } else {
        writeln!(
            out,
            "  Progress (T0 drain):  {} / {} resolved → {:.0}% complete",
            diff.t0_resolved,
            diff.t0_total,
            diff.t0_progress_pct * 100.0,
        )?;
    }
    if total == 0 {
        writeln!(
            out,
            "  Population:           n/a (prior run had no findings)"
        )?;
    } else {
        writeln!(
            out,
            "  Population:           {} / {} resolved ({:.0}%)",
            resolved,
            total,
            diff.progress_pct * 100.0,
        )?;
    }
    Ok(())
}

fn scoped_count(findings: &[Finding], workspace: Option<&str>) -> usize {
    match workspace {
        None => findings.len(),
        Some(ws) => findings
            .iter()
            .filter(|f| f.workspace.as_deref() == Some(ws))
            .count(),
    }
}

#[allow(clippy::too_many_arguments)]
fn render_bucket(
    label: &str,
    color: &str,
    items: &[DiffEntry],
    show_all: bool,
    hidden_low_severity: &mut usize,
    colorize: bool,
    out: &mut (impl Write + ?Sized),
) -> std::io::Result<()> {
    if show_all {
        return write_bucket(label, color, items.iter(), items.len(), colorize, out);
    }
    let visible: Vec<&DiffEntry> = items.iter().filter(|e| is_high_or_critical(e)).collect();
    *hidden_low_severity += items.len() - visible.len();
    write_bucket(
        label,
        color,
        visible.iter().copied(),
        visible.len(),
        colorize,
        out,
    )
}

fn write_bucket<'a>(
    label: &str,
    color: &str,
    entries: impl Iterator<Item = &'a DiffEntry>,
    count: usize,
    colorize: bool,
    out: &mut (impl Write + ?Sized),
) -> std::io::Result<()> {
    if count == 0 {
        return Ok(());
    }
    writeln!(out, "{} ({})", ansi_wrap(color, label, colorize), count)?;
    for e in entries {
        let arrow = match (e.from_severity, e.to_severity) {
            (Some(from), Some(to)) if from != to => format!("({from:?}{to:?})"),
            (Some(from), Some(_)) => format!("({from:?})"),
            (Some(from), None) => format!("({from:?} → ✓)"),
            (None, Some(to)) => format!("(new {to:?})"),
            (None, None) => String::new(),
        };
        let hot = if e.hotspot { " 🔥" } else { "" };
        writeln!(out, "  {} {} {arrow}{hot}", e.metric, e.file)?;
    }
    Ok(())
}

/// True when either side of the entry sits at High or above. The
/// human renderer uses this as the default-visibility gate so a noisy
/// baseline doesn't bury the actionable rows; `--all` bypasses it.
fn is_high_or_critical(e: &DiffEntry) -> bool {
    let hot = |sev: Option<Severity>| sev.is_some_and(|s| s >= Severity::High);
    hot(e.from_severity) || hot(e.to_severity)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::finding::{Finding, Location};
    use crate::core::findings_cache::FindingsRecord;
    use crate::core::severity::Severity;
    use std::path::PathBuf;

    fn finding(id_seed: &str, severity: Severity) -> Finding {
        let mut f = Finding::new(
            "ccn",
            Location {
                file: PathBuf::from(format!("src/{id_seed}.ts")),
                line: Some(1),
                symbol: Some(id_seed.to_owned()),
            },
            "CCN=10 fn (rust)".into(),
            id_seed,
        );
        f.severity = severity;
        f
    }

    fn record(findings: Vec<Finding>) -> FindingsRecord {
        FindingsRecord::new(Some("abc".into()), true, "h".into(), findings)
    }

    #[test]
    fn diff_buckets_resolved_regressed_new_unchanged() {
        let stay = finding("stay", Severity::High);
        let dropped = finding("dropped", Severity::Medium);
        let regressed_a = finding("hot", Severity::High);
        let regressed_b = {
            let mut f = finding("hot", Severity::Critical);
            f.severity = Severity::Critical;
            assert_eq!(f.id, regressed_a.id);
            f
        };
        let new_one = finding("new", Severity::High);

        let from = record(vec![dropped.clone(), regressed_a.clone(), stay.clone()]);
        let to = record(vec![regressed_b.clone(), stay.clone(), new_one.clone()]);

        let diff = compute_diff(&from, &to, None, &PolicyDrainConfig::default());

        assert_eq!(diff.resolved.len(), 1);
        assert_eq!(diff.resolved[0].file, "src/dropped.ts");
        assert_eq!(diff.regressed.len(), 1);
        assert_eq!(diff.regressed[0].file, "src/hot.ts");
        assert_eq!(diff.regressed[0].from_severity, Some(Severity::High));
        assert_eq!(diff.regressed[0].to_severity, Some(Severity::Critical));
        assert_eq!(diff.unchanged.len(), 1);
        assert_eq!(diff.unchanged[0].file, "src/stay.ts");
        assert_eq!(diff.new_findings.len(), 1);
        assert_eq!(diff.new_findings[0].file, "src/new.ts");
        assert!(diff.improved.is_empty());

        // 1 resolved out of 3 prior = 33%.
        assert!((diff.progress_pct - (1.0 / 3.0)).abs() < 1e-9);
    }

    #[test]
    fn diff_buckets_improved_when_severity_drops() {
        let mut prev = finding("calm", Severity::Critical);
        prev.severity = Severity::Critical;
        let mut curr = finding("calm", Severity::Medium);
        curr.severity = Severity::Medium;
        assert_eq!(prev.id, curr.id);
        let diff = compute_diff(
            &record(vec![prev]),
            &record(vec![curr]),
            None,
            &PolicyDrainConfig::default(),
        );
        assert_eq!(diff.improved.len(), 1);
        assert!(diff.regressed.is_empty());
        assert!((diff.progress_pct - 0.0).abs() < 1e-9);
    }

    #[test]
    fn diff_workspace_filter_scopes_buckets_and_total() {
        // Two findings per side, one in each workspace.
        let mut a_prev = finding("alpha", Severity::High);
        a_prev.workspace = Some("packages/web".into());
        let mut a_curr = finding("alpha", Severity::High);
        a_curr.workspace = Some("packages/web".into());
        let mut b_prev = finding("beta", Severity::High);
        b_prev.workspace = Some("packages/api".into());
        // beta resolved on the new side — but only counts when api scope active.
        let from = record(vec![a_prev, b_prev]);
        let to = record(vec![a_curr]);

        let web = compute_diff(
            &from,
            &to,
            Some("packages/web"),
            &PolicyDrainConfig::default(),
        );
        assert!(web.resolved.is_empty());
        assert_eq!(web.unchanged.len(), 1);
        // total = 1 (web only); 0 resolved → 0%.
        assert!((web.progress_pct - 0.0).abs() < 1e-9);

        let api = compute_diff(
            &from,
            &to,
            Some("packages/api"),
            &PolicyDrainConfig::default(),
        );
        assert_eq!(api.resolved.len(), 1);
        assert!(api.unchanged.is_empty());
        // total = 1 (api only); 1 resolved → 100%.
        assert!((api.progress_pct - 1.0).abs() < 1e-9);
    }

    #[test]
    fn t0_progress_counts_only_critical_hotspot_baseline() {
        // Two T0 in baseline (Critical AND hotspot); one resolved, one
        // still present. T1 entries (plain Critical, no hotspot) and
        // High+hotspot don't count toward t0_total.
        let drained = {
            let mut f = finding("t0_drained", Severity::Critical);
            f.hotspot = true;
            f
        };
        let stuck = {
            let mut f = finding("t0_stuck", Severity::Critical);
            f.hotspot = true;
            f
        };
        let plain_crit = finding("plain_crit", Severity::Critical);
        let high_hot = {
            let mut f = finding("high_hot", Severity::High);
            f.hotspot = true;
            f
        };

        let from = record(vec![
            drained.clone(),
            stuck.clone(),
            plain_crit.clone(),
            high_hot.clone(),
        ]);
        // `to` keeps `stuck` and `plain_crit`; `drained` and
        // `high_hot` resolved.
        let to = record(vec![stuck.clone(), plain_crit.clone()]);

        let diff = compute_diff(&from, &to, None, &PolicyDrainConfig::default());

        assert_eq!(diff.t0_total, 2, "two Critical+hotspot in baseline");
        assert_eq!(diff.t0_resolved, 1, "one of the two T0 resolved");
        assert!((diff.t0_progress_pct - 0.5).abs() < 1e-9);
        // Population: 4 baseline, 2 resolved (drained + high_hot).
        assert!((diff.progress_pct - 0.5).abs() < 1e-9);
    }

    #[test]
    fn diff_entry_from_hotspot_reflects_baseline_side() {
        // Improved: was Critical+hotspot in baseline, now Medium and
        // no longer hot. `from_hotspot` must reflect baseline state.
        let mut prev = finding("cool_off", Severity::Critical);
        prev.hotspot = true;
        let mut curr = finding("cool_off", Severity::Medium);
        curr.hotspot = false;
        assert_eq!(prev.id, curr.id);
        let diff = compute_diff(
            &record(vec![prev]),
            &record(vec![curr]),
            None,
            &PolicyDrainConfig::default(),
        );
        assert_eq!(diff.improved.len(), 1);
        assert!(
            diff.improved[0].from_hotspot,
            "baseline-side hotspot must persist"
        );
        assert!(
            !diff.improved[0].hotspot,
            "curr-side hotspot reflects to-side"
        );
    }

    #[test]
    fn diff_progress_zero_when_prior_empty() {
        let diff = compute_diff(
            &record(Vec::new()),
            &record(vec![finding("only", Severity::High)]),
            None,
            &PolicyDrainConfig::default(),
        );
        assert!((diff.progress_pct - 0.0).abs() < 1e-9);
        assert_eq!(diff.new_findings.len(), 1);
    }

    #[test]
    fn render_default_hides_below_high_entries_and_reports_hidden_count() {
        // One Resolved entry at Medium → hidden by default; one
        // Resolved at High → shown. Footer mentions the hidden count.
        let stay_high = finding("hi", Severity::High);
        let dropped_med = finding("med", Severity::Medium);
        let dropped_high = finding("dh", Severity::High);
        let from = record(vec![
            stay_high.clone(),
            dropped_med.clone(),
            dropped_high.clone(),
        ]);
        let to = record(vec![stay_high.clone()]);
        let diff = compute_diff(&from, &to, None, &PolicyDrainConfig::default());

        let mut buf: Vec<u8> = Vec::new();
        render_diff(
            "HEAD",
            "deadbeefdeadbeef",
            None,
            &from,
            &to,
            &diff,
            false,
            false,
            &mut buf,
        )
        .unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(out.contains("src/dh.ts"), "High entry must render: {out}");
        assert!(
            !out.contains("src/med.ts"),
            "Medium entry must be hidden: {out}",
        );
        assert!(
            out.contains("1 entries below High hidden"),
            "footer must report hidden count: {out}",
        );
    }

    #[test]
    fn render_all_surfaces_below_high_entries_and_drops_footer() {
        let dropped_med = finding("med", Severity::Medium);
        let from = record(vec![dropped_med.clone()]);
        let to = record(Vec::new());
        let diff = compute_diff(&from, &to, None, &PolicyDrainConfig::default());

        let mut buf: Vec<u8> = Vec::new();
        render_diff(
            "HEAD",
            "deadbeefdeadbeef",
            None,
            &from,
            &to,
            &diff,
            true,
            false,
            &mut buf,
        )
        .unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(
            out.contains("src/med.ts"),
            "--all must surface Medium entry: {out}",
        );
        assert!(
            !out.contains("entries below High hidden"),
            "--all must drop the hidden-count footer: {out}",
        );
    }

    #[test]
    fn recompute_at_ref_materialises_worktree_and_runs_observers() {
        use crate::core::config::Config;
        use crate::test_support::{commit, init_repo};
        use tempfile::TempDir;

        let dir = TempDir::new().unwrap();
        init_repo(dir.path());
        commit(
            dir.path(),
            "lib.rs",
            "fn ok() {}\n",
            "tester@example.com",
            "init",
        );
        let head_sha = git::head_sha(dir.path()).expect("head sha after first commit");
        let paths = HealPaths::new(dir.path());
        paths.ensure().unwrap();
        Config::default().save(&paths.config()).unwrap();

        let cfg = load_from_project(dir.path()).unwrap();
        let record = recompute_at_ref(dir.path(), &paths, &cfg, &head_sha).unwrap();
        assert_eq!(record.head_sha.as_deref(), Some(head_sha.as_str()));
        // Sanity: the worktree was torn down and didn't leak.
        let leftover = std::fs::read_dir(dir.path().join(".git/worktrees"))
            .ok()
            .map_or(0, std::iter::Iterator::count);
        assert_eq!(leftover, 0, "git worktree must be cleaned up after diff");
    }
}