heal-cli 0.3.1

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
//! `heal status` — render `.heal/findings/latest.json` and, when needed,
//! produce it.
//!
//! Default flow reads the cached `FindingsRecord` from `latest.json` if
//! one exists. Only when the cache is missing — or `--refresh` is
//! passed — does this command run every observer, lift the reports
//! through `crate::core::finding::IntoFindings`, decorate each Finding
//! with Severity (via `Calibration`) and the per-file hotspot flag
//! (via `HotspotCalibration`), and write a fresh `FindingsRecord`. This
//! is still the single writer of `.heal/findings/`.
//!
//! The renderer groups findings by `(Severity, hotspot)` and labels the
//! sections by Severity (🔴 Critical 🔥 → 🔴 Critical → 🟠 High 🔥 → …).
//! Each section header carries a `[T0 Must drain]` / `[T1 Should drain]`
//! / `[Advisory]` suffix derived from `[policy.drain]` so the link to
//! `/heal-code-patch` stays explicit. Default policy:
//! `must = ["critical:hotspot"]`, `should = ["critical", "high:hotspot"]`.
//! Sections below `🟠 High 🔥` (plain High, Medium, Ok) are hidden unless
//! `--all` is passed; the footer surfaces a "next steps" line pointing
//! at `claude /heal-code-patch` for the Must-drain queue.
//!
//! `--json` emits the `FindingsRecord` in the exact shape of `latest.json`
//! so skills and CI scripts have one stable contract.

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

use anyhow::{Context, Result};

use crate::cli::{FindingMetric, SeverityFilter, StatusArgs};
use crate::core::accepted::read_accepted;
use crate::core::calibration::{FLOOR_CCN, FLOOR_COGNITIVE, FLOOR_OK_CCN, FLOOR_OK_COGNITIVE};
use crate::core::config::{load_from_project, Config, DrainTier, PolicyDrainConfig};
use crate::core::finding::Finding;
use crate::core::findings_cache::{
    config_hash_from_paths, read_latest, reconcile_fixed, write_record, FindingsRecord,
    RegressedEntry,
};
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::git;
use crate::observers::build_record;

pub fn run(project: &Path, args: &StatusArgs) -> Result<()> {
    let paths = HealPaths::new(project);
    paths.ensure().with_context(|| {
        format!(
            "creating {} (heal-cli needs a writable .heal/ directory)",
            paths.root().display(),
        )
    })?;

    let filters = Filters::from_args(args);

    // Cache reuse hinges on `(head_sha, config_hash, worktree_clean)` —
    // the same triple that drives `FindingsRecord.id` — so a stale
    // `latest.json` from a different commit, a different config, or a
    // dirty scan is auto-rescanned even without `--refresh`. The
    // freshness gate also matters because `latest.json` is git-tracked:
    // a teammate fetching the file at a different HEAD would otherwise
    // see the previous owner's state until they remembered to refresh.
    let head_sha = git::head_sha(project);
    let worktree_clean = git::worktree_clean(project).unwrap_or(false);
    let cfg_hash = config_hash_from_paths(&paths.config(), &paths.calibration());
    let cached = if args.refresh {
        None
    } else {
        read_latest(&paths.findings_latest())
            .ok()
            .flatten()
            .filter(|r| r.is_fresh_against(head_sha.as_deref(), &cfg_hash, worktree_clean))
    };
    let must_scan = cached.is_none();

    // Load config only when it's actually needed: a fresh scan needs
    // it for `build_record`, and the textual renderer needs it for
    // `policy.drain` + override notes. The JSON path with a cache hit
    // pays neither cost.
    let need_cfg = must_scan || !args.json;
    let cfg = if need_cfg {
        Some(load_from_project(project).with_context(|| {
            format!(
                "loading {} (run `heal init` first?)",
                paths.config().display(),
            )
        })?)
    } else {
        None
    };

    let (mut record, regressed) = if must_scan {
        let cfg = cfg.as_ref().expect("cfg loaded above when must_scan");
        let record = build_record(project, &paths, cfg, head_sha, worktree_clean);
        write_record(&paths.findings_latest(), &record)?;
        let regs = reconcile_fixed(
            &paths.findings_fixed(),
            &paths.findings_regressed_log(),
            &record,
        )?;
        (record, regs)
    } else {
        // Cache hit: skip the scan entirely. Reconciliation already
        // happened on the run that produced this record.
        (
            cached.expect("cache present per must_scan branch"),
            Vec::new(),
        )
    };

    // `latest.json` stores raw observer truth; the accepted-finding
    // overlay (Population minus accepted, drain queue skipping
    // accepted, `Accepted:` header) is derived just-in-time so
    // `heal mark accept` takes effect without a rescan.
    let accepted_map = read_accepted(&paths.findings_accepted())?;
    record.apply_accepted(&accepted_map);

    if args.json {
        match filters.workspace.as_deref() {
            None => super::emit_json(&record),
            Some(ws) => super::emit_json(&record.project_to_workspace(ws)),
        }
        return Ok(());
    }
    let cfg = cfg.expect("cfg loaded above when not args.json");
    write_through_pager(args.no_pager, |out, colorize| {
        render(&record, &regressed, &filters, &cfg, colorize, out)
    })
}

/// Resolved filters for the renderer.
#[derive(Debug, Clone, Default)]
pub(super) struct Filters {
    pub(super) metric: Option<FindingMetric>,
    pub(super) feature: Option<String>,
    pub(super) workspace: Option<String>,
    pub(super) severity: Option<Severity>,
    pub(super) all: bool,
    pub(super) top: Option<usize>,
}

impl Filters {
    fn from_args(args: &StatusArgs) -> Self {
        Self {
            metric: args.metric,
            feature: args.feature.clone(),
            workspace: args.workspace.clone(),
            severity: args.severity.map(SeverityFilter::into_severity),
            all: args.all,
            top: args.top,
        }
    }

    fn passes(&self, finding: &Finding) -> bool {
        if let Some(m) = self.metric {
            if !m.matches(&finding.metric) {
                return false;
            }
        }
        if let Some(ws) = self.workspace.as_deref() {
            if finding.workspace.as_deref() != Some(ws) {
                return false;
            }
        }
        if let Some(prefix) = self.feature.as_ref() {
            if !finding
                .location
                .file
                .to_string_lossy()
                .starts_with(prefix.as_str())
            {
                return false;
            }
        }
        true
    }
}

/// Render the record to `out`. Pure function — no IO besides writing
/// `out`. Tests pin the prefixes for the section headers; the precise
/// row formatting can evolve without breaking the contract.
#[allow(clippy::too_many_lines)] // tier-by-tier pour; splitting hurts readability
pub(super) fn render(
    record: &FindingsRecord,
    regressed: &[RegressedEntry],
    filters: &Filters,
    cfg: &Config,
    colorize: bool,
    out: &mut (impl Write + ?Sized),
) -> Result<()> {
    let drain = &cfg.policy.drain;
    writeln!(
        out,
        "  HEAD {}  ({} findings)",
        record.head_sha.as_deref().unwrap_or(""),
        record.findings.len(),
    )?;
    let summary = drain_summary(&record.findings, drain);
    writeln!(
        out,
        "  Drain queue: {}  ·  {}",
        ansi_wrap(
            ANSI_RED,
            &format!(
                "T0 {} findings ({} files)",
                summary.t0_count, summary.t0_files
            ),
            colorize,
        ),
        ansi_wrap(
            ANSI_YELLOW,
            &format!(
                "T1 {} findings ({} files)",
                summary.t1_count, summary.t1_files
            ),
            colorize,
        ),
    )?;
    writeln!(
        out,
        "  Population:  {}",
        record.severity_counts.render_inline(colorize),
    )?;
    let accepted = accepted_summary(&record.findings);
    if accepted.count > 0 {
        writeln!(
            out,
            "  {}    {} findings ({} files)",
            ansi_wrap(ANSI_CYAN, "Accepted:", colorize),
            accepted.count,
            accepted.files,
        )?;
    }
    if !record.worktree_clean {
        writeln!(
            out,
            "  {} worktree dirty — uncommitted changes are reflected here.",
            ansi_wrap(ANSI_YELLOW, "note:", colorize),
        )?;
    }
    if let Some(ws) = filters.workspace.as_deref() {
        writeln!(out, "  workspace: {ws}")?;
    }
    for line in override_notes(cfg) {
        writeln!(
            out,
            "  {} {line}",
            ansi_wrap(ANSI_CYAN, "override:", colorize)
        )?;
    }
    writeln!(out)?;

    if !regressed.is_empty() {
        writeln!(
            out,
            "  {} {} previously-fixed finding(s) re-detected. See `.heal/findings/regressed.jsonl`.",
            ansi_wrap(ANSI_YELLOW, "regression:", colorize),
            regressed.len(),
        )?;
        writeln!(out)?;
    }

    let show_low = filters.all || matches!(filters.severity, Some(Severity::Medium | Severity::Ok));

    // Bucket by (severity, hotspot). Sections are labelled by Severity so
    // the header counts (`[critical] N`) line up with the visible content;
    // the drain-tier (`[T0 Must drain]` etc.) is inferred from
    // `[policy.drain]` and shown as a per-section suffix so the link to
    // `/heal-code-patch` stays explicit without overriding the labels.
    let mut buckets: BTreeMap<(Severity, bool), Vec<&Finding>> = BTreeMap::new();
    let mut accepted_items: Vec<&Finding> = Vec::new();
    for f in record.findings.iter().filter(|f| filters.passes(f)) {
        if let Some(min) = filters.severity {
            if f.severity < min {
                continue;
            }
        }
        if f.accepted {
            // Accepted findings are out of the drain queue by design.
            // Surfaced under `--all` in their own section so the
            // audit trail stays visible without cluttering the
            // default view.
            accepted_items.push(f);
            continue;
        }
        buckets.entry((f.severity, f.hotspot)).or_default().push(f);
    }

    // Default-visible sections cover the drain queue + should-drain rows
    // under the literature-anchored policy default. Everything below the
    // Should line is gated behind `--all` (or an explicit low `--severity`).
    let order: &[(Severity, bool, &str, &str, bool)] = &[
        (Severity::Critical, true, "🔴 Critical 🔥", ANSI_RED, true),
        (Severity::Critical, false, "🔴 Critical", ANSI_RED, true),
        (Severity::High, true, "🟠 High 🔥", ANSI_YELLOW, true),
        (Severity::High, false, "🟠 High", ANSI_YELLOW, show_low),
        (
            Severity::Medium,
            true,
            "🟡 Medium 🔥",
            ANSI_YELLOW,
            show_low,
        ),
        (Severity::Medium, false, "🟡 Medium", ANSI_YELLOW, show_low),
        (Severity::Ok, true, "✅ Ok 🔥", ANSI_CYAN, show_low),
        (Severity::Ok, false, "✅ Ok", ANSI_GREEN, show_low),
    ];

    let mut hidden_count = 0usize;
    for (sev, hot, label, color, visible) in order {
        let Some(items) = buckets.get(&(*sev, *hot)) else {
            continue;
        };
        if !*visible {
            hidden_count += items.len();
            continue;
        }
        let suffix = drain
            .tier_for(items[0])
            .map(|t| {
                let name = match t {
                    DrainTier::Must => "T0 Must drain",
                    DrainTier::Should => "T1 Should drain",
                    DrainTier::Advisory => "Advisory",
                };
                format!(" [{name}]")
            })
            .unwrap_or_default();
        let full_label = format!("{label}{suffix}");
        render_tier_section(&full_label, color, items, filters.top, colorize, out)?;
    }

    if !show_low && hidden_count > 0 {
        writeln!(
            out,
            "  Hidden: {hidden_count} findings  [pass --all to show]",
        )?;
    }

    if filters.all && !accepted_items.is_empty() {
        render_tier_section(
            "📌 Accepted",
            ANSI_CYAN,
            &accepted_items,
            filters.top,
            colorize,
            out,
        )?;
    }

    writeln!(out)?;
    writeln!(
        out,
        "  Next: `claude /heal-code-patch` drains the T0 queue one finding per commit",
    )?;
    Ok(())
}

/// Render a drain-tier section with internal Severity 🔥 sort.
fn render_tier_section(
    label: &str,
    color: &str,
    items: &[&Finding],
    top: Option<usize>,
    colorize: bool,
    out: &mut (impl Write + ?Sized),
) -> std::io::Result<()> {
    if items.is_empty() {
        return Ok(());
    }
    let mut sorted: Vec<&Finding> = items.to_vec();
    // Severity desc, then 🔥 first within same Severity, then by metric
    // / file for deterministic output.
    sorted.sort_by(|a, b| {
        b.severity
            .cmp(&a.severity)
            .then_with(|| b.hotspot.cmp(&a.hotspot))
            .then_with(|| a.metric.cmp(&b.metric))
            .then_with(|| a.location.file.cmp(&b.location.file))
    });
    let total = sorted.len();
    if let Some(n) = top {
        sorted.truncate(n);
    }
    writeln!(out, "{} ({})", ansi_wrap(color, label, colorize), total)?;
    let mut by_file: BTreeMap<&PathBuf, Vec<&Finding>> = BTreeMap::new();
    for f in &sorted {
        by_file.entry(&f.location.file).or_default().push(f);
    }
    for (file, fs) in &by_file {
        let summary = fs
            .iter()
            .map(|f| f.short_label())
            .collect::<Vec<_>>()
            .join("  ");
        writeln!(out, "  {}  {summary}", file.display())?;
    }
    Ok(())
}

/// Accepted-finding tally for the header line. `Accepted: N
/// findings (M files)` runs alongside `Drain queue:` and `Population:`
/// so the user sees how much the team has explicitly suppressed —
/// makes the population-vs-drain gap auditable instead of mysterious.
struct AcceptedSummary {
    count: usize,
    files: usize,
}

fn accepted_summary(findings: &[Finding]) -> AcceptedSummary {
    let mut count = 0;
    let mut files: HashSet<&PathBuf> = HashSet::new();
    for f in findings {
        if f.accepted {
            count += 1;
            files.insert(&f.location.file);
        }
    }
    AcceptedSummary {
        count,
        files: files.len(),
    }
}

/// Drain-queue counts surfaced in the header. Foregrounds the
/// actionable T0 / T1 sizes so the user sees "5 things to fix" before
/// the wider Severity distribution. File counts let a user judge
/// whether the queue concentrates in one hotspot or spreads thin.
struct DrainSummary {
    t0_count: usize,
    t0_files: usize,
    t1_count: usize,
    t1_files: usize,
}

fn drain_summary(findings: &[Finding], drain: &PolicyDrainConfig) -> DrainSummary {
    let mut t0_count = 0;
    let mut t1_count = 0;
    let mut t0_files: HashSet<&PathBuf> = HashSet::new();
    let mut t1_files: HashSet<&PathBuf> = HashSet::new();
    for f in findings {
        if f.accepted {
            continue;
        }
        match drain.tier_for(f) {
            Some(DrainTier::Must) => {
                t0_count += 1;
                t0_files.insert(&f.location.file);
            }
            Some(DrainTier::Should) => {
                t1_count += 1;
                t1_files.insert(&f.location.file);
            }
            _ => {}
        }
    }
    DrainSummary {
        t0_count,
        t0_files: t0_files.len(),
        t1_count,
        t1_files: t1_files.len(),
    }
}

/// One-line notes for any per-metric `floor_ok` / `floor_critical`
/// override active in the config. Surfaced near the header so users see
/// "policy moved" without digging through `.heal/config.toml`.
fn override_notes(cfg: &Config) -> Vec<String> {
    let ccn = &cfg.metrics.ccn;
    let cog = &cfg.metrics.cognitive;
    if ccn.floor_ok.is_none()
        && ccn.floor_critical.is_none()
        && cog.floor_ok.is_none()
        && cog.floor_critical.is_none()
    {
        return Vec::new();
    }
    let push =
        |notes: &mut Vec<String>, metric: &str, kind: &str, value: Option<f64>, baseline: f64| {
            if let Some(v) = value {
                if (v - baseline).abs() > f64::EPSILON {
                    notes.push(format!("{metric} {kind}={v} [override from {baseline}]"));
                }
            }
        };
    let mut notes = Vec::with_capacity(4);
    push(&mut notes, "ccn", "floor_ok", ccn.floor_ok, FLOOR_OK_CCN);
    push(
        &mut notes,
        "cognitive",
        "floor_ok",
        cog.floor_ok,
        FLOOR_OK_COGNITIVE,
    );
    push(
        &mut notes,
        "ccn",
        "floor_critical",
        ccn.floor_critical,
        FLOOR_CCN,
    );
    push(
        &mut notes,
        "cognitive",
        "floor_critical",
        cog.floor_critical,
        FLOOR_COGNITIVE,
    );
    notes
}

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

    fn finding(metric: &str, file: &str, severity: Severity, hotspot: bool) -> Finding {
        let mut f = Finding::new(
            metric,
            Location {
                file: PathBuf::from(file),
                line: Some(1),
                symbol: Some("fn_name".into()),
            },
            format!(
                "{} 42 fn_name (rust)",
                if metric == "ccn" {
                    "CCN="
                } else if metric == "cognitive" {
                    "Cognitive="
                } else {
                    metric
                }
            ),
            metric,
        );
        f.severity = severity;
        f.hotspot = hotspot;
        f
    }

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

    fn render_to_string(record: &FindingsRecord, filters: &Filters) -> String {
        let mut buf = Vec::new();
        let cfg = Config::default();
        render(record, &[], filters, &cfg, false, &mut buf).unwrap();
        String::from_utf8(buf).unwrap()
    }

    fn default_filters() -> Filters {
        Filters {
            metric: None,
            feature: None,
            workspace: None,
            severity: None,
            all: false,
            top: None,
        }
    }

    #[test]
    fn critical_hotspot_renders_before_plain_critical() {
        // Critical 🔥 (T0 Must drain) must print before plain Critical
        // (T1 Should drain) so the operator sees must-fix items first.
        let rec = record(vec![
            finding("ccn", "src/cool.ts", Severity::Critical, false),
            finding("ccn", "src/hot.ts", Severity::Critical, true),
        ]);
        let out = render_to_string(&rec, &default_filters());
        let hot_idx = out.find("Critical 🔥").expect("Critical 🔥 section");
        let plain_idx = {
            // "Critical 🔥" header contains "Critical"; find the second occurrence.
            let after_hot = &out[hot_idx + "Critical 🔥".len()..];
            after_hot
                .find("🔴 Critical ")
                .map(|i| hot_idx + "Critical 🔥".len() + i)
                .or_else(|| {
                    after_hot
                        .find("🔴 Critical")
                        .map(|i| hot_idx + "Critical 🔥".len() + i)
                })
                .expect("plain Critical section")
        };
        assert!(
            hot_idx < plain_idx,
            "Critical 🔥 must render before plain Critical:\n{out}",
        );
        assert!(out.contains("[T0 Must drain]"), "T0 tier suffix:\n{out}");
        assert!(out.contains("[T1 Should drain]"), "T1 tier suffix:\n{out}");
        assert!(out.contains("src/hot.ts"));
        assert!(out.contains("src/cool.ts"));
    }

    #[test]
    fn default_hides_medium_and_ok() {
        let rec = record(vec![
            finding("ccn", "src/hot.ts", Severity::Critical, true), // visible
            finding("ccn", "src/lukewarm.ts", Severity::Medium, false), // hidden
            finding("ccn", "src/cold.ts", Severity::Ok, false),     // hidden
        ]);
        let out = render_to_string(&rec, &default_filters());
        assert!(out.contains("🔴 Critical 🔥"), "Critical 🔥 must render");
        assert!(
            !out.contains("🟡 Medium"),
            "Medium must be hidden by default:\n{out}"
        );
        assert!(
            !out.contains("✅ Ok"),
            "Ok must be hidden by default:\n{out}"
        );
        assert!(
            out.contains("Hidden: 2 findings"),
            "Hidden summary must surface counts:\n{out}",
        );
    }

    #[test]
    fn all_flag_shows_medium_and_ok() {
        let rec = record(vec![
            finding("ccn", "src/lukewarm.ts", Severity::Medium, false),
            finding("ccn", "src/cold.ts", Severity::Ok, false),
        ]);
        let mut filters = default_filters();
        filters.all = true;
        let out = render_to_string(&rec, &filters);
        assert!(out.contains("🟡 Medium"), "Medium must render with --all");
        assert!(out.contains("✅ Ok"), "Ok section must render with --all");
    }

    #[test]
    fn metric_filter_drops_other_metrics() {
        let rec = record(vec![
            finding("ccn", "src/a.ts", Severity::Critical, false),
            finding("duplication", "src/b.ts", Severity::Critical, false),
        ]);
        let mut filters = default_filters();
        filters.metric = Some(FindingMetric::Ccn);
        let out = render_to_string(&rec, &filters);
        assert!(out.contains("src/a.ts"));
        assert!(!out.contains("src/b.ts"));
    }

    #[test]
    fn feature_filter_keeps_path_prefix_only() {
        let rec = record(vec![
            finding("ccn", "src/payments/engine.ts", Severity::Critical, false),
            finding("ccn", "src/billing/cart.ts", Severity::Critical, false),
        ]);
        let mut filters = default_filters();
        filters.feature = Some("src/payments".to_owned());
        let out = render_to_string(&rec, &filters);
        assert!(out.contains("src/payments/engine.ts"));
        assert!(!out.contains("src/billing/cart.ts"));
    }

    #[test]
    fn severity_filter_drops_below_floor() {
        let rec = record(vec![
            finding("ccn", "src/hot.ts", Severity::Critical, false),
            finding("ccn", "src/warm.ts", Severity::High, false),
            finding("ccn", "src/lukewarm.ts", Severity::Medium, false),
        ]);
        let mut filters = default_filters();
        filters.severity = Some(Severity::High);
        filters.all = true; // make low-severity sections visible
        let out = render_to_string(&rec, &filters);
        assert!(out.contains("src/hot.ts"));
        assert!(out.contains("src/warm.ts"));
        assert!(
            !out.contains("src/lukewarm.ts"),
            "Medium must drop with --severity high:\n{out}"
        );
    }

    #[test]
    fn ok_hotspot_renders_after_drain_sections_under_all() {
        // Ok 🔥 — touched-a-lot but below floor. Must render below
        // Critical / High sections so the drain queue stays at the top.
        let rec = record(vec![
            finding("ccn", "src/hot.ts", Severity::Critical, true),
            finding("hotspot", "src/touch_a_lot.ts", Severity::Ok, true),
        ]);
        let mut filters = default_filters();
        filters.all = true;
        let out = render_to_string(&rec, &filters);
        let critical_idx = out.find("🔴 Critical 🔥").expect("Critical 🔥 section");
        let ok_hot_idx = out.find("✅ Ok 🔥").expect("Ok 🔥 section");
        assert!(
            critical_idx < ok_hot_idx,
            "Drain queue (Critical 🔥) must render above Ok 🔥:\n{out}",
        );
    }

    #[test]
    fn default_omits_low_severity_hotspot_section() {
        let rec = record(vec![finding(
            "hotspot",
            "src/touch_a_lot.ts",
            Severity::Ok,
            true,
        )]);
        let out = render_to_string(&rec, &default_filters());
        assert!(
            !out.contains("Ok 🔥"),
            "low-Severity hotspot section must stay hidden without --all:\n{out}",
        );
    }

    #[test]
    fn override_notes_surface_in_header() {
        let rec = record(Vec::new());
        let mut cfg = Config::default();
        cfg.metrics.ccn.floor_ok = Some(15.0);
        let mut buf = Vec::new();
        render(&rec, &[], &default_filters(), &cfg, false, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(
            out.contains("ccn floor_ok=15"),
            "override note must surface:\n{out}",
        );
        assert!(out.contains("override from 11"), "{out}");
    }

    #[test]
    fn override_notes_silent_when_at_default() {
        let rec = record(Vec::new());
        let mut cfg = Config::default();
        // Setting to literature default is not an override.
        cfg.metrics.ccn.floor_ok = Some(11.0);
        let mut buf = Vec::new();
        render(&rec, &[], &default_filters(), &cfg, false, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(
            !out.contains("override"),
            "no override note when value matches default:\n{out}"
        );
    }

    #[test]
    fn empty_record_renders_next_hint() {
        let rec = record(Vec::new());
        let out = render_to_string(&rec, &default_filters());
        assert!(out.contains("Next:"));
        assert!(out.contains("/heal-code-patch"));
        assert!(
            !out.contains("── HEAL status"),
            "leading divider should be removed:\n{out}",
        );
        assert!(
            !out.contains("Goal:"),
            "trailing Goal line should be removed:\n{out}",
        );
    }

    #[test]
    fn header_shows_drain_queue_and_population() {
        // Two T0 (Critical+hotspot, both in same file), one T1
        // (plain Critical), one Medium and one Ok in the noise floor.
        let rec = record(vec![
            finding("ccn", "src/hot.ts", Severity::Critical, true),
            finding("cognitive", "src/hot.ts", Severity::Critical, true),
            finding("ccn", "src/cool.ts", Severity::Critical, false),
            finding("ccn", "src/lukewarm.ts", Severity::Medium, false),
            finding("ccn", "src/cold.ts", Severity::Ok, false),
        ]);
        let out = render_to_string(&rec, &default_filters());
        assert!(
            out.contains("Drain queue: T0 2 findings (1 files)  ·  T1 1 findings (1 files)"),
            "header must surface T0 / T1 sizes with file counts:\n{out}",
        );
        // Population still shows the raw severity distribution.
        assert!(
            out.contains("Population:  [critical] 3"),
            "raw severity counts move to a 'Population:' line:\n{out}",
        );
    }

    #[test]
    fn header_drain_queue_zero_when_codebase_clean() {
        // No Critical / High findings → both T0 and T1 are zero, but
        // the header still renders both labels so the user sees
        // "drain queue: empty".
        let rec = record(vec![finding("ccn", "src/calm.ts", Severity::Medium, false)]);
        let out = render_to_string(&rec, &default_filters());
        assert!(
            out.contains("T0 0 findings (0 files)"),
            "empty T0 must still render explicitly:\n{out}",
        );
        assert!(
            out.contains("T1 0 findings (0 files)"),
            "empty T1 must still render explicitly:\n{out}",
        );
    }
}