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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
//! `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::shared::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`, the textual renderer needs it for
    // `policy.drain` + override notes, and `--feature` needs it to
    // gate against the relevant `[features.<f>].enabled` switch. The
    // JSON path with a cache hit and no `--feature` filter pays
    // none of these costs.
    let need_cfg = must_scan || !args.json || args.feature.is_some();
    let cfg = if need_cfg {
        Some(load_from_project(project).with_context(|| {
            format!(
                "loading {} (run `heal init` first?)",
                paths.config().display(),
            )
        })?)
    } else {
        None
    };

    // Early-exit when `--feature <disabled>` would otherwise produce
    // empty output. Skills (`/heal-test-patch`, `/heal-doc-patch`,
    // …) shell out with `--feature <family>` and read the exit code:
    // a non-zero exit here is the contract for "this family is off
    // in `.heal/config.toml`, stop now".
    if let Some(family) = filters.family {
        let cfg_ref = cfg
            .as_ref()
            .expect("cfg loaded above when --feature is set");
        if !family.is_enabled(cfg_ref) {
            eprintln!(
                "heal status: --feature {0} requested but `[features.{0}].enabled = false`. \
                 Edit `.heal/config.toml` (or run `/heal-setup`) to enable the family before re-running.",
                family.name(),
            );
            std::process::exit(1);
        }
    }

    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 {
        // Workspace narrowing rebuilds the record (paths flipped
        // project-relative → workspace-relative), so the clone is
        // baked into `project_to_workspace`. The other filters
        // (`--feature` / `--metric` / `--path` / `--severity`) only
        // need to drop findings — borrow the record and clone only
        // when an actual narrowing is in flight, so the unfiltered
        // fast path serializes the original record directly.
        match (filters.workspace.as_deref(), filters.is_narrowing()) {
            (None, false) => super::emit_json(&record),
            (None, true) => {
                let mut emit = record.clone();
                emit.findings.retain(|f| filters.passes(f));
                super::emit_json(&emit);
            }
            (Some(ws), narrowing) => {
                let mut emit = record.project_to_workspace(ws);
                if narrowing {
                    emit.findings.retain(|f| filters.passes(f));
                }
                super::emit_json(&emit);
            }
        }
        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) family: Option<crate::feature::Family>,
    pub(super) path: 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,
            family: args.feature.map(crate::cli::FamilyFilter::as_family),
            path: args.path.clone(),
            workspace: args.workspace.clone(),
            severity: args.severity.map(SeverityFilter::into_severity),
            all: args.all,
            top: args.top,
        }
    }

    /// True when at least one finding-level filter is set. Lets the
    /// JSON emit path skip the `retain` clone allocation on the
    /// unfiltered fast path.
    fn is_narrowing(&self) -> bool {
        self.metric.is_some()
            || self.family.is_some()
            || self.path.is_some()
            || self.severity.is_some()
    }

    fn passes(&self, finding: &Finding) -> bool {
        if let Some(m) = self.metric {
            if !m.matches(&finding.metric) {
                return false;
            }
        }
        if let Some(f) = self.family {
            if finding.family() != f {
                return false;
            }
        }
        if let Some(ws) = self.workspace.as_deref() {
            if finding.workspace.as_deref() != Some(ws) {
                return false;
            }
        }
        if let Some(prefix) = self.path.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;
    let summary = drain_summary(&record.findings, drain);
    let accepted = accepted_summary(&record.findings);
    render_header(record, &summary, &accepted, cfg, filters, colorize, out)?;
    render_regressed_banner(regressed, colorize, out)?;

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

    // Partition by family first, then bucket each family's findings by
    // (severity, hotspot). Per-family rendering is the v0.4 contract:
    // each family's drain queue is independent (matching the per-family
    // patch skills and the per-family `HotspotIndex` decoration), so a
    // global Severity ordering would mix Test and Code Critical 🔥
    // rows that the user actually wants to triage separately.
    let mut by_family: BTreeMap<crate::feature::Family, 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_items.push(f);
            continue;
        }
        by_family.entry(f.family()).or_default().push(f);
    }

    let mut total_hidden = 0usize;
    // Render order = the canonical `Family` `Ord` order. Banner and
    // patch-skill labels live as methods on `Family` so renaming a
    // family in one place propagates everywhere.
    let family_order = [
        crate::feature::Family::Code,
        crate::feature::Family::Test,
        crate::feature::Family::Docs,
    ];
    for family in family_order {
        total_hidden += render_one_family(
            family,
            by_family.get(&family),
            drain,
            filters,
            cfg,
            show_low,
            colorize,
            out,
        )?;
    }

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

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

    Ok(())
}

/// Render the per-invocation header block — HEAD sha, drain queue
/// summary, population counts, accepted / worktree / workspace /
/// override notes, then a trailing blank line. Pure formatting; the
/// pre-computed `summary` and `accepted` are passed in so the caller
/// keeps single-pass arithmetic over `record.findings`.
fn render_header(
    record: &FindingsRecord,
    summary: &DrainSummary,
    accepted: &AcceptedSummary,
    cfg: &Config,
    filters: &Filters,
    colorize: bool,
    out: &mut (impl Write + ?Sized),
) -> Result<()> {
    writeln!(
        out,
        "  HEAD {}  ({} findings)",
        record.head_sha.as_deref().unwrap_or(""),
        record.findings.len(),
    )?;
    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),
    )?;
    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)?;
    Ok(())
}

/// Surface `regressed.jsonl` entries that re-appeared after a recorded
/// fix. No-op when `regressed` is empty so `render` itself stays free
/// of the conditional.
fn render_regressed_banner(
    regressed: &[RegressedEntry],
    colorize: bool,
    out: &mut (impl Write + ?Sized),
) -> Result<()> {
    if regressed.is_empty() {
        return Ok(());
    }
    writeln!(
        out,
        "  {} {} previously-fixed finding(s) re-detected. See `.heal/findings/regressed.jsonl`.",
        ansi_wrap(ANSI_YELLOW, "regression:", colorize),
        regressed.len(),
    )?;
    writeln!(out)?;
    Ok(())
}

/// Render one family's banner, findings, and patch-skill hint. Returns
/// the count of hidden lower-Severity findings the caller should
/// accumulate for the global `Hidden: …` footer. Disabled families and
/// `--feature X`-suppressed siblings produce zero output and zero hidden.
#[allow(clippy::too_many_arguments)] // each parameter is a distinct render input
fn render_one_family(
    family: crate::feature::Family,
    items: Option<&Vec<&Finding>>,
    drain: &PolicyDrainConfig,
    filters: &Filters,
    cfg: &Config,
    show_low: bool,
    colorize: bool,
    out: &mut (impl Write + ?Sized),
) -> Result<usize> {
    // Skip families whose feature is disabled so the user never sees
    // an empty banner for an opt-in family they haven't enabled.
    // Code is always on; Test / Docs follow their master switches.
    // The explicit `--feature <disabled>` case exits earlier in `run()`
    // so this branch only matters for the unfiltered render.
    if !family.is_enabled(cfg) {
        return Ok(0);
    }
    // `--feature X` narrows to one family — suppress the sibling
    // banners entirely even when they have findings (they were
    // already filtered out by `Filters::passes`). Without a family
    // filter, every enabled family prints its banner + Next hint so
    // the user always sees the path forward, even when a family is empty.
    if filters.family.is_some_and(|f| f != family) {
        return Ok(0);
    }
    writeln!(out, "{}", ansi_wrap(ANSI_CYAN, family.banner(), colorize))?;
    let hidden = if let Some(items) = items {
        render_family(items, drain, show_low, filters.top, colorize, out)?
    } else {
        writeln!(out, "  (no findings)")?;
        0
    };
    writeln!(
        out,
        "  Next: `claude {}` drains this family's T0 queue one finding per commit",
        family.patch_skill(),
    )?;
    writeln!(out)?;
    Ok(hidden)
}

/// Render one family's findings as the per-`(Severity, hotspot)`
/// bucket cascade. Returns the number of findings hidden behind the
/// `--all` gate so the caller can roll a single "Hidden: N across
/// families" footer instead of one per family.
fn render_family(
    items: &[&Finding],
    drain: &PolicyDrainConfig,
    show_low: bool,
    top: Option<usize>,
    colorize: bool,
    out: &mut (impl Write + ?Sized),
) -> Result<usize> {
    let mut buckets: BTreeMap<(Severity, bool), Vec<&Finding>> = BTreeMap::new();
    for f in items {
        buckets.entry((f.severity, f.hotspot)).or_default().push(*f);
    }
    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 = 0usize;
    for (sev, hot, label, color, visible) in order {
        let Some(items) = buckets.get(&(*sev, *hot)) else {
            continue;
        };
        if !*visible {
            hidden += 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, top, colorize, out)?;
    }
    Ok(hidden)
}

/// 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 = group_labels(fs.iter().map(|f| f.short_label())).join("  ");
        writeln!(out, "  {}  {summary}", file.display())?;
    }
    Ok(())
}

/// Run-length-encode adjacent identical labels into `label(N)` form so
/// the per-file summary stays readable when one metric fires many times
/// (e.g. 13× `doc_drift` on a heavy reference doc, 5× `coupled` on a
/// frequently-edited central file). Singletons stay bare. Adjacency is
/// the right granularity because `render_tier_section` already sorts
/// findings by metric before grouping by file.
fn group_labels<I: IntoIterator<Item = String>>(labels: I) -> Vec<String> {
    let mut out: Vec<(String, usize)> = Vec::new();
    for label in labels {
        match out.last_mut() {
            Some(last) if last.0 == label => last.1 += 1,
            _ => out.push((label, 1)),
        }
    }
    out.into_iter()
        .map(|(s, n)| if n > 1 { format!("{s}({n})") } else { s })
        .collect()
}

/// 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,
            family: None,
            path: 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 path_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.path = 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 family_filter_drops_other_families() {
        // CoveragePct is Family::Test; ccn is Family::Code. Filtering
        // to `--feature code` should keep ccn and drop coverage_pct.
        let rec = record(vec![
            finding("ccn", "src/hot.rs", Severity::Critical, false),
            finding("coverage_pct", "src/cold.rs", Severity::Critical, false),
        ]);
        let mut filters = default_filters();
        filters.family = Some(crate::feature::Family::Code);
        let out = render_to_string(&rec, &filters);
        assert!(out.contains("src/hot.rs"));
        assert!(!out.contains("src/cold.rs"));
    }

    #[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}",
        );
    }

    #[test]
    fn group_labels_collapses_adjacent_repeats() {
        // Heavy reference docs trigger many doc_drift findings on the
        // same file; without grouping the per-file line becomes
        // `doc_drift  doc_drift  doc_drift  …` which is unreadable.
        let labels = vec![
            "coupled".to_owned(),
            "coupled".to_owned(),
            "coupled".to_owned(),
            "duplication".to_owned(),
            "duplication".to_owned(),
            "LCOM=4".to_owned(),
        ];
        assert_eq!(
            super::group_labels(labels),
            vec![
                "coupled(3)".to_owned(),
                "duplication(2)".to_owned(),
                "LCOM=4".to_owned(),
            ],
        );
    }

    #[test]
    fn group_labels_keeps_singletons_bare() {
        let labels = vec![
            "CCN=36".to_owned(),
            "Cognitive=58".to_owned(),
            "duplication".to_owned(),
        ];
        assert_eq!(
            super::group_labels(labels),
            vec![
                "CCN=36".to_owned(),
                "Cognitive=58".to_owned(),
                "duplication".to_owned(),
            ],
        );
    }

    #[test]
    fn render_groups_repeated_metric_per_file() {
        // 13 same-metric findings on one file should print as
        // `duplication(13)`, not 13 space-separated copies. Mirrors the
        // motivating user report (where doc_drift was the offender —
        // same rendering path, but the Code family is always enabled
        // so the test doesn't need a tweaked Config).
        let findings: Vec<Finding> = (0..13)
            .map(|i| {
                let mut f = finding("duplication", "src/heavy.rs", Severity::Critical, false);
                f.id = format!("duplication:src/heavy.rs:{i}");
                f
            })
            .collect();
        let rec = record(findings);
        let out = render_to_string(&rec, &default_filters());
        assert!(
            out.contains("duplication(13)"),
            "expected grouped duplication(13) in output:\n{out}",
        );
        assert!(
            !out.contains("duplication  duplication"),
            "raw repeated labels must not appear after grouping:\n{out}",
        );
    }
}