basemind 0.30.0

Full AI context layer over MCP — tree-sitter code-map, document RAG (PDF/Office/HTML/email + OCR + reranker), shared agent memory, on-demand web crawl, git history + blame + per-symbol diff. 300+ languages, 10+ coding-agent harnesses, content-addressed Fjall + LanceDB.
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
//! Colored, colorblind-safe rendering for scan/watch reports.
//!
//! Every line carries a symbol AND a label so color is decoration, not the
//! information channel — users with color-vision differences read the same
//! signal as everyone else.
//!
//! Auto-disables ANSI on non-TTY stdout and when `NO_COLOR` is set.

use std::collections::BTreeMap;
use std::io::Write;
use std::path::Path;

use anstream::AutoStream;
use anstyle::{AnsiColor, Color, Reset, Style};

use crate::lang::BootstrapSummary;
use crate::scan_phase_peaks::PhasePeak;
use crate::scanner::{FileResult, FileStatus, ScanObserver, ScanStats};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verbosity {
    Quiet,
    Default,
    Verbose,
}

impl Verbosity {
    pub fn from_flags(quiet: bool, verbose: bool) -> Self {
        match (quiet, verbose) {
            (true, _) => Verbosity::Quiet,
            (_, true) => Verbosity::Verbose,
            _ => Verbosity::Default,
        }
    }
}

/// Stdout writer that auto-handles TTY detection + NO_COLOR.
/// `force_off=true` strips ANSI regardless of TTY state (for `--no-color`).
pub fn stdout(force_off: bool) -> AutoStream<std::io::Stdout> {
    if force_off {
        AutoStream::never(std::io::stdout())
    } else {
        AutoStream::auto(std::io::stdout())
    }
}

const COL_PATH: usize = 8;

/// Per-grammar tally of files that parsed with errors, so a grammar with gaps produces one summary
/// line instead of one `warn` line per file.
#[derive(Debug, Default)]
pub struct WarnTally {
    by_grammar: BTreeMap<&'static str, (usize, u64)>,
}

impl WarnTally {
    /// Fold in `res` when it is a partial-map warning. Returns true when it was absorbed.
    pub fn absorb(&mut self, res: &FileResult) -> bool {
        let FileStatus::Updated {
            had_errors: true,
            error_count,
            ..
        } = &res.status
        else {
            return false;
        };
        let grammar = crate::lang::detect(Path::new(&res.path)).unwrap_or("unknown");
        let entry = self.by_grammar.entry(grammar).or_default();
        entry.0 += 1;
        entry.1 += u64::from(*error_count);
        true
    }

    /// One line per grammar: `<grammar>: N files, M parse errors`.
    pub fn summary_lines(&self) -> Vec<String> {
        self.by_grammar
            .iter()
            .map(|(grammar, (files, errors))| {
                format!(
                    "{grammar}: {files} file{fs}, {errors} parse error{es}",
                    fs = if *files == 1 { "" } else { "s" },
                    es = if *errors == 1 { "" } else { "s" },
                )
            })
            .collect()
    }

    /// Print the summary lines (a no-op when nothing was absorbed) and reset the tally.
    pub fn flush(&mut self, w: &mut AutoStream<std::io::Stdout>) {
        let style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow))).render();
        let reset = Reset.render();
        let dim = Style::new().dimmed().render();
        for line in self.summary_lines() {
            let _ = writeln!(
                w,
                "{style}⚠ warn {reset} {line} {dim}(partial maps; -v lists each file){reset}"
            );
        }
        self.by_grammar.clear();
    }
}

/// Print one file's line, or fold a parse-error warning into `tally` unless `-v` asked for every line.
fn render_or_tally(w: &mut AutoStream<std::io::Stdout>, tally: &mut WarnTally, res: &FileResult, verbosity: Verbosity) {
    if verbosity == Verbosity::Default && tally.absorb(res) {
        return;
    }
    render_file(w, res, verbosity);
}

/// Print the per-file lines of an already-collected result set (no summary). Used by the watcher,
/// which renders a batch after the fact. Parse-error warnings collapse into one line per grammar
/// unless `-v`.
pub fn render_files(w: &mut AutoStream<std::io::Stdout>, results: &[FileResult], verbosity: Verbosity) {
    let mut tally = WarnTally::default();
    for r in results {
        render_or_tally(w, &mut tally, r, verbosity);
    }
    tally.flush(w);
}

/// A [`ScanObserver`] that prints each file's line the moment the scan absorbs it.
///
/// This is why the CLI no longer needs `ScanReport.results`: it owns its own stdout stream, so it
/// never has to be handed a `Vec` of every file in the repo just to print one line per file. The
/// summary is still rendered by the caller from `report.stats` once the scan returns. Parse-error
/// warnings are tallied per grammar and printed by [`finish`](Self::finish) unless `-v`.
pub struct ScanLineObserver {
    out: AutoStream<std::io::Stdout>,
    verbosity: Verbosity,
    tally: WarnTally,
}

impl ScanLineObserver {
    /// `force_off` mirrors [`stdout`]'s `--no-color` flag.
    pub fn new(force_off: bool, verbosity: Verbosity) -> Self {
        Self {
            out: stdout(force_off),
            verbosity,
            tally: WarnTally::default(),
        }
    }

    /// Print the per-grammar warning summary. Call once the scan has returned.
    pub fn finish(&mut self) {
        self.tally.flush(&mut self.out);
    }
}

impl ScanObserver for ScanLineObserver {
    fn on_file(&mut self, result: FileResult) {
        render_or_tally(&mut self.out, &mut self.tally, &result, self.verbosity);
    }
}

pub fn render_file(w: &mut AutoStream<std::io::Stdout>, res: &FileResult, verbosity: Verbosity) {
    let Some(line) = format_line(res, verbosity) else {
        return;
    };
    let _ = writeln!(w, "{line}");
}

pub fn render_summary(w: &mut AutoStream<std::io::Stdout>, stats: &ScanStats, verbosity: Verbosity) {
    if verbosity == Verbosity::Quiet
        && stats.read_failed == 0
        && stats.extract_failed == 0
        && stats.updated_with_warnings == 0
    {
        return;
    }
    let style_label = Style::new().dimmed();
    let style_zero = Style::new().dimmed();
    let style_ok = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green)));
    let style_warn = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)));
    let style_fail = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red)));

    let pair = |label: &str, n: usize, important: Style| -> String {
        let s = if n == 0 { style_zero } else { important };
        format!(
            "{label_style}{label}{label_off} {n_style}{n}{n_off}",
            label_style = style_label.render(),
            label_off = Reset.render(),
            label = label,
            n_style = s.render(),
            n_off = Reset.render(),
            n = n,
        )
    };

    let line = format!(
        "{scanned}  {updated}  {reused}  {warn}  {unchanged}  {failed}  {skipped}  {removed}",
        scanned = pair("scanned", stats.scanned, Style::new()),
        updated = pair("updated", stats.updated, style_ok),
        reused = pair("reused", stats.reused_extraction, Style::new()),
        warn = pair("warn", stats.updated_with_warnings, style_warn),
        unchanged = pair("unchanged", stats.skipped_unchanged, Style::new()),
        failed = pair("failed", stats.read_failed + stats.extract_failed, style_fail),
        skipped = pair(
            "skipped",
            stats.skipped_too_large + stats.skipped_non_utf8 + stats.skipped_no_lang,
            Style::new(),
        ),
        removed = pair("removed", stats.removed, style_warn),
    );
    let _ = writeln!(w, "{line}");
    if stats.docs_indexed > 0 {
        let docs_line = pair("docs_indexed", stats.docs_indexed, style_ok);
        let _ = writeln!(w, "{docs_line}");
    }
    if stats.docs_degraded > 0 || stats.doc_timeouts > 0 {
        let _ = writeln!(
            w,
            "{degraded}  {timeouts} (large text documents use linear chunking; see [documents] markdown_chunk_max_bytes)",
            degraded = pair("docs_degraded", stats.docs_degraded, style_warn),
            timeouts = pair("doc_timeouts", stats.doc_timeouts, style_fail),
        );
    }
    if stats.docs_text_fallback > 0 {
        let _ = writeln!(
            w,
            "{fallback} (of docs_degraded: structured extraction failed, so the file was read as plain text)",
            fallback = pair("docs_text_fallback", stats.docs_text_fallback, style_warn),
        );
    }
    if stats.docs_tombstoned > 0 || stats.docs_deferred > 0 || stats.abandoned_extractions > 0 {
        let _ = writeln!(
            w,
            "{tombstoned}  {deferred}  {abandoned} (see [documents] phase_budget_secs, max_abandoned_extractions)",
            tombstoned = pair("docs_tombstoned", stats.docs_tombstoned, style_warn),
            deferred = pair("docs_deferred", stats.docs_deferred, style_warn),
            abandoned = pair("abandoned_extractions", stats.abandoned_extractions, style_warn),
        );
    }
    if stats.tier_migrated > 0 || stats.refreshed_extraction > 0 {
        let _ = writeln!(
            w,
            "{migrated}  {refreshed}",
            migrated = pair("tier_migrated", stats.tier_migrated, style_warn),
            refreshed = pair("refreshed", stats.refreshed_extraction, style_warn),
        );
    }
    if stats.skipped_too_large > 0 {
        let too_large = pair("too_large", stats.skipped_too_large, style_warn);
        let _ = writeln!(
            w,
            "{too_large} (over [scan] max_file_bytes, or [documents] max_file_bytes for documents)"
        );
    }
}

/// Peak footprint per scan phase, one dimmed line (`peak memory  extract 512.0MB  resolve 5.5GB`).
/// Silent under `--quiet` and when the scan recorded none.
pub fn render_phase_peaks(w: &mut AutoStream<std::io::Stdout>, peaks: &[PhasePeak], verbosity: Verbosity) {
    let Some(line) = phase_peaks_line(peaks) else {
        return;
    };
    if verbosity == Verbosity::Quiet {
        return;
    }
    let dim = Style::new().dimmed().render();
    let _ = writeln!(w, "{dim}{line}{reset}", reset = Reset.render());
}

fn phase_peaks_line(peaks: &[PhasePeak]) -> Option<String> {
    if peaks.is_empty() {
        return None;
    }
    let cells: Vec<String> = peaks
        .iter()
        .map(|p| format!("{} {}", p.phase, human_bytes(p.peak_bytes)))
        .collect();
    Some(format!("peak memory  {}", cells.join("  ")))
}

/// Print what the post-scan blob cleanup reclaimed. Silent when nothing was orphaned.
pub fn render_cleanup(w: &mut AutoStream<std::io::Stdout>, report: &crate::store_gc::GcReport) {
    if report.removed == 0 {
        return;
    }
    let _ = writeln!(
        w,
        "cleanup: reclaimed {} orphaned blob(s), {} bytes",
        report.removed, report.bytes_freed
    );
}

/// Print a one-line summary of the grammar bootstrap.
///
/// Silent when all grammars were already cached (unless verbose). When a download did happen,
/// always emit at least one line so the user knows what basemind was doing during the pause.
pub fn render_grammar_bootstrap(w: &mut AutoStream<std::io::Stdout>, summary: &BootstrapSummary, verbosity: Verbosity) {
    if !summary.did_download() && verbosity != Verbosity::Verbose {
        return;
    }
    let dim = Style::new().dimmed();
    let ok = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green)));
    let info = Style::new().fg_color(Some(Color::Ansi(AnsiColor::BrightBlue)));

    if summary.did_download() {
        let names = summary.downloaded.join(", ");
        let _ = writeln!(
            w,
            "{s}▼ downloaded {n} grammar{plural}{r} {d}({names}){dr}",
            s = info.render(),
            r = Reset.render(),
            d = dim.render(),
            dr = Reset.render(),
            n = summary.downloaded.len(),
            plural = if summary.downloaded.len() == 1 { "" } else { "s" },
            names = names,
        );
    }
    if verbosity == Verbosity::Verbose {
        let cached_count = summary.already_cached.len();
        let _ = writeln!(
            w,
            "{s}✓ grammars ready{r} {d}({cached_count} cached, {dl} fresh){dr}",
            s = ok.render(),
            r = Reset.render(),
            d = dim.render(),
            dr = Reset.render(),
            cached_count = cached_count,
            dl = summary.downloaded.len(),
        );
        if let Some(dir) = &summary.cache_dir {
            let _ = writeln!(
                w,
                "  {d}cache: {dir}{dr}",
                d = dim.render(),
                dr = Reset.render(),
                dir = dir.display(),
            );
        }
    }
}

/// Tiny header used by non-working-tree scans (staged / rev). Working-tree scans don't get
/// one — they're the default and shouldn't grow noise on every run.
pub fn render_scan_header(w: &mut AutoStream<std::io::Stdout>, label: &str, verbosity: Verbosity) {
    if verbosity == Verbosity::Quiet {
        return;
    }
    let style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::BrightBlue)));
    let _ = writeln!(
        w,
        "{s}▶ scanning {label}{r}",
        s = style.render(),
        r = Reset.render(),
        label = label,
    );
}

pub fn render_batch_header(w: &mut AutoStream<std::io::Stdout>, paths: usize, verbosity: Verbosity) {
    if verbosity == Verbosity::Quiet {
        return;
    }
    let style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::BrightBlue)));
    let _ = writeln!(
        w,
        "{s}▶ batch — {paths} {label}{r}",
        s = style.render(),
        r = Reset.render(),
        paths = paths,
        label = if paths == 1 { "path" } else { "paths" },
    );
}

/// Sanitize a repo-relative path for single-line terminal output: collapse
/// newlines and strip the remaining control characters (including ANSI escape
/// introducers) so a crafted filename can't inject escape sequences or break the
/// one-line-per-file layout. Mirrors the newline-flattening done in
/// `cli::render::truncate`, but also drops control chars since paths are
/// rendered raw (not length-capped).
fn sanitize_path(path: &str) -> String {
    path.chars()
        .map(|c| if c == '\n' || c == '\r' { ' ' } else { c })
        .filter(|c| !c.is_control())
        .collect()
}

fn format_line(res: &FileResult, verbosity: Verbosity) -> Option<String> {
    let row = row_for(res, verbosity)?;
    let style = row.style.render();
    let reset = Reset.render();
    let symbol = row.symbol;
    let label = row.label;
    let path = sanitize_path(&res.path);
    let detail = row.detail;
    let detail_block = if detail.is_empty() {
        String::new()
    } else {
        let dim = Style::new().dimmed().render();
        format!(" {dim}{detail}{reset}")
    };
    Some(format!("{style}{symbol} {label:<5}{reset} {path}{detail_block}",))
}

struct Row<'a> {
    symbol: char,
    label: &'a str,
    style: Style,
    detail: String,
}

fn row_for(res: &FileResult, verbosity: Verbosity) -> Option<Row<'_>> {
    let v = verbosity;
    match &res.status {
        FileStatus::Updated { had_errors: false, .. } => {
            if v == Verbosity::Verbose {
                Some(Row {
                    symbol: '✓',
                    label: "ok",
                    style: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green))),
                    detail: String::new(),
                })
            } else {
                None
            }
        }
        FileStatus::Updated {
            had_errors: true,
            error_count,
            ..
        } => {
            if v == Verbosity::Quiet {
                None
            } else {
                Some(Row {
                    symbol: '⚠',
                    label: "warn",
                    style: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow))),
                    detail: format!(
                        "({n} parse error{s}, partial map)",
                        n = error_count,
                        s = if *error_count == 1 { "" } else { "s" }
                    ),
                })
            }
        }
        #[cfg(feature = "documents")]
        FileStatus::DocUnchanged => {
            if v == Verbosity::Verbose {
                Some(Row {
                    symbol: '·',
                    label: "same",
                    style: Style::new().dimmed(),
                    detail: String::new(),
                })
            } else {
                None
            }
        }
        FileStatus::Unchanged => {
            if v == Verbosity::Verbose {
                Some(Row {
                    symbol: '·',
                    label: "same",
                    style: Style::new().dimmed(),
                    detail: String::new(),
                })
            } else {
                None
            }
        }
        FileStatus::Removed => {
            if v == Verbosity::Quiet {
                None
            } else {
                Some(Row {
                    symbol: '×',
                    label: "gone",
                    style: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red))),
                    detail: String::new(),
                })
            }
        }
        FileStatus::SkippedTooLarge { size } => {
            if v == Verbosity::Verbose {
                Some(Row {
                    symbol: '·',
                    label: "skip",
                    style: Style::new().dimmed(),
                    detail: format!("({} too large)", human_bytes(*size)),
                })
            } else {
                None
            }
        }
        FileStatus::SkippedNonUtf8 => {
            if v == Verbosity::Verbose {
                Some(Row {
                    symbol: '·',
                    label: "skip",
                    style: Style::new().dimmed(),
                    detail: "(non-UTF8)".to_string(),
                })
            } else {
                None
            }
        }
        FileStatus::SkippedNoLang => {
            if v == Verbosity::Verbose {
                Some(Row {
                    symbol: '·',
                    label: "skip",
                    style: Style::new().dimmed(),
                    detail: "(no language)".to_string(),
                })
            } else {
                None
            }
        }
        FileStatus::SkippedBinary => {
            if v == Verbosity::Verbose {
                Some(Row {
                    symbol: '·',
                    label: "skip",
                    style: Style::new().dimmed(),
                    detail: "(binary)".to_string(),
                })
            } else {
                None
            }
        }
        FileStatus::ParseTimedOut => Some(Row {
            symbol: '✗',
            label: "fail",
            style: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red))),
            detail: "(parse timed out — file likely pathological)".to_string(),
        }),
        FileStatus::ReadFailed { msg, .. } => Some(Row {
            symbol: '✗',
            label: "fail",
            style: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red))),
            detail: format!("(read failed: {msg})"),
        }),
        #[cfg(feature = "documents")]
        FileStatus::DocTimedOut => Some(Row {
            symbol: '✗',
            label: "fail",
            style: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red))),
            detail: "(document extraction timed out; see [documents] extraction_timeout_secs)".to_string(),
        }),
        #[cfg(feature = "documents")]
        FileStatus::DocTombstoned => {
            if v == Verbosity::Verbose {
                Some(Row {
                    symbol: '·',
                    label: "skip",
                    style: Style::new().dimmed(),
                    detail: "(timed out before, unchanged; edit the file or raise [documents] extraction_timeout_secs to retry)".to_string(),
                })
            } else {
                None
            }
        }
        #[cfg(feature = "documents")]
        FileStatus::DocDeferred => Some(Row {
            symbol: '·',
            label: "defer",
            style: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow))),
            detail: "(document deferred to the next scan: phase budget spent or too many stuck extractions)"
                .to_string(),
        }),
        FileStatus::ExtractFailed { msg } => Some(Row {
            symbol: '✗',
            label: "fail",
            style: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red))),
            detail: format!("(extract failed: {msg})"),
        }),
        #[cfg(feature = "documents")]
        FileStatus::DocIndexed {
            chunk_count,
            embedding_dim,
            reused,
            degraded,
            text_fallback,
            elapsed_ms,
        } => {
            if v == Verbosity::Quiet {
                None
            } else {
                let cached = if *reused { ", cached" } else { "" };
                let cached = if *text_fallback {
                    format!("{cached}, read as plain text after a parse failure")
                } else if *degraded {
                    format!("{cached}, linear chunking")
                } else {
                    cached.to_string()
                };
                Some(Row {
                    symbol: '✓',
                    label: "doc",
                    style: Style::new().fg_color(Some(Color::Ansi(AnsiColor::BrightBlue))),
                    detail: format!(
                        "({chunk_count} chunks, dim={embedding_dim}{cached}, {})",
                        format_elapsed(*elapsed_ms)
                    ),
                })
            }
        }
    }
}

/// Compact per-document duration: `850ms` under a second, `1.2s` under a minute, `3m05s` beyond.
#[cfg(any(feature = "documents", test))]
fn format_elapsed(ms: u64) -> String {
    match ms {
        0..1000 => format!("{ms}ms"),
        1000..60_000 => format!("{:.1}s", ms as f64 / 1000.0),
        _ => format!("{}m{:02}s", ms / 60_000, ms / 1000 % 60),
    }
}

fn human_bytes(b: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = 1024 * KB;
    const GB: u64 = 1024 * MB;
    if b >= GB {
        format!("{:.1}GB", b as f64 / GB as f64)
    } else if b >= MB {
        format!("{:.1}MB", b as f64 / MB as f64)
    } else if b >= KB {
        format!("{:.1}KB", b as f64 / KB as f64)
    } else {
        format!("{b}B")
    }
}

const _: usize = COL_PATH;

#[cfg(test)]
mod tests {
    use super::{WarnTally, format_elapsed, phase_peaks_line, sanitize_path};
    use crate::scan_phase_peaks::PhasePeak;
    use crate::scanner::{FileResult, FileStatus};

    fn result(path: &str, status: FileStatus) -> FileResult {
        FileResult::bare(path.to_string(), status)
    }

    fn warned(path: &str, error_count: u32) -> FileResult {
        result(
            path,
            FileStatus::Updated {
                had_errors: true,
                error_count,
                reused: false,
            },
        )
    }

    #[test]
    fn warn_tally_aggregates_files_and_errors_per_grammar() {
        let mut tally = WarnTally::default();
        assert!(tally.absorb(&warned("a/one.scss", 3)));
        assert!(tally.absorb(&warned("a/two.scss", 2)));
        assert!(tally.absorb(&warned("db/x.sql", 1)));
        assert_eq!(
            tally.summary_lines(),
            vec!["scss: 2 files, 5 parse errors", "sql: 1 file, 1 parse error"]
        );
    }

    #[test]
    fn phase_peaks_line_lists_each_phase_and_is_absent_when_empty() {
        assert_eq!(phase_peaks_line(&[]), None);
        let peaks = [
            PhasePeak {
                phase: "extract",
                peak_bytes: 512 * 1024 * 1024,
            },
            PhasePeak {
                phase: "resolve",
                peak_bytes: 3 * 1024 * 1024 * 1024,
            },
        ];
        assert_eq!(
            phase_peaks_line(&peaks).as_deref(),
            Some("peak memory  extract 512.0MB  resolve 3.0GB")
        );
    }

    #[test]
    fn warn_tally_ignores_clean_and_unchanged_files() {
        let mut tally = WarnTally::default();
        let clean = result(
            "a.rs",
            FileStatus::Updated {
                had_errors: false,
                error_count: 0,
                reused: false,
            },
        );
        assert!(!tally.absorb(&clean));
        assert!(!tally.absorb(&result("b.rs", FileStatus::Unchanged)));
        assert!(tally.summary_lines().is_empty());
    }

    #[test]
    fn format_elapsed_scales_from_millis_to_minutes() {
        assert_eq!(format_elapsed(0), "0ms");
        assert_eq!(format_elapsed(850), "850ms");
        assert_eq!(format_elapsed(1_200), "1.2s");
        assert_eq!(format_elapsed(59_000), "59.0s");
        assert_eq!(format_elapsed(185_000), "3m05s");
    }

    #[test]
    fn sanitize_path_flattens_newlines_to_spaces() {
        assert_eq!(sanitize_path("src/a\nb.rs"), "src/a b.rs");
        assert_eq!(sanitize_path("src/a\r\nb.rs"), "src/a  b.rs");
    }

    #[test]
    fn sanitize_path_strips_ansi_and_control_chars() {
        let crafted = "src/\x1b[31mevil\x07\tname.rs";
        assert_eq!(sanitize_path(crafted), "src/[31mevilname.rs");
    }

    #[test]
    fn sanitize_path_leaves_plain_paths_unchanged() {
        assert_eq!(sanitize_path("src/render.rs"), "src/render.rs");
    }
}