face-core 0.1.0

Core grouping, clustering, and paging primitives for the face CLI.
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
//! `--format=human` rendering (§8.3).
//!
//! Tree-rendered, two-space indent per nesting level, optional ANSI
//! color, optional ASCII bars scaled to a fixed character budget,
//! width-aware: when the configured width would not leave comfortable
//! headroom, bars are dropped tree-wide first; if score ranges would
//! still overflow, they are dropped tree-wide too. Labels are never
//! truncated.

use crate::format::RenderOptions;
use crate::{Cluster, Envelope};

/// Width budget for the bar widget itself (12 cells); `BAR_GUTTER` is
/// the spacing in front of it. We reserve `BAR_BUDGET + BAR_GUTTER` as
/// the minimum slack needed to keep bars; below that, the rendering
/// drops bars tree-wide so columns stay aligned.
const BAR_BUDGET: usize = 12;
const BAR_GUTTER: usize = 2;

/// Render the envelope as a human-readable tree.
///
/// The header starts with `face: <total> items` and, when axes are
/// available, a compact grouping line. With `--verbose`, the CLI may
/// prepend its own provenance line above this. Keeping the library
/// output self-contained avoids leaking CLI-specific provenance text
/// into programmatic callers.
pub(super) fn render(envelope: &Envelope, opts: &RenderOptions) -> String {
    // Resolve width-driven decisions once so every line in the tree
    // makes the same call: drop bars / ranges either tree-wide or not
    // at all. Per-line decisions would produce ragged columns where
    // some lines have score ranges and others do not.
    let layout = decide_layout(envelope, opts);

    let mut out = String::new();
    write_header(&mut out, envelope, opts);

    if !envelope.clusters.is_empty() {
        out.push('\n');
        write_cluster_group(
            &mut out,
            &envelope.clusters,
            1,
            opts,
            &layout,
            envelope.result.detection.score_path.as_deref(),
        );
    }

    if !envelope.page.items.is_empty() {
        write_page(&mut out, envelope);
    }

    out
}

/// Layout decisions that apply to the whole tree.
#[derive(Debug, Clone, Copy)]
struct Layout {
    show_bars: bool,
    show_ranges: bool,
}

#[derive(Debug, Clone, Copy, Default)]
struct ColumnWidths {
    ordinal: usize,
    label: usize,
    count: usize,
    range: usize,
}

#[derive(Debug, Clone, Copy)]
struct LineParts<'a> {
    indent: &'a str,
    ordinal: Option<&'a str>,
    label: &'a str,
    count: &'a str,
    score_range: Option<&'a str>,
    bar: Option<&'a str>,
}

/// Decide whether to show bars and score ranges given the configured
/// width.
///
/// Rule: keep bars only when the longest with-bars line has at least
/// `BAR_BUDGET + BAR_GUTTER` of headroom. That captures the §8.3
/// "narrow terminals drop bars first" intent without a magic-number
/// threshold — narrow means "no comfortable room for a bar's worth of
/// drift".
///
/// After dropping bars, score ranges are dropped only when at least
/// one line still overflows. Both are tree-wide decisions so columns
/// stay aligned across siblings.
fn decide_layout(envelope: &Envelope, opts: &RenderOptions) -> Layout {
    let Some(width) = opts.width else {
        return Layout {
            show_bars: true,
            show_ranges: true,
        };
    };

    let longest_with_bars = max_line_width(envelope, /* bars */ true, /* ranges */ true);
    let longest_no_bars = max_line_width(envelope, false, true);
    let longest_no_extras = max_line_width(envelope, false, false);

    // Keep bars only when the widest with-bars line has ≥ a full bar
    // worth of slack. Reserving the bar's own footprint as headroom
    // matches the spec's "narrow terminals drop bars first" intent —
    // when the bar would be the only thing keeping a line on-budget,
    // we drop it.
    let show_bars = width.saturating_sub(longest_with_bars) >= BAR_BUDGET + BAR_GUTTER;

    let show_ranges = if show_bars {
        // Bars stay; ranges are part of the same line so the with-bars
        // line being on-budget already covers ranges.
        true
    } else if longest_no_bars > width {
        // After dropping bars some line still overflows: drop ranges.
        // Sanity: if even the no-extras line overflows we can't help
        // (labels are not truncated), but ranges still go.
        let _ = longest_no_extras;
        false
    } else {
        true
    };

    Layout {
        show_bars,
        show_ranges,
    }
}

/// Walk the tree and return the longest visible line width given the
/// inclusion flags. ANSI escapes are not relevant here because layout
/// decisions run before colorization and `assemble_no_color` is what
/// we measure.
fn max_line_width(envelope: &Envelope, with_bars: bool, with_ranges: bool) -> usize {
    let mut max = 0usize;
    walk_group_widths(
        &envelope.clusters,
        1,
        with_bars,
        with_ranges,
        envelope.result.detection.score_path.as_deref(),
        &mut max,
    );
    max
}

fn walk_group_widths(
    clusters: &[Cluster],
    depth: usize,
    with_bars: bool,
    with_ranges: bool,
    score_path: Option<&str>,
    max: &mut usize,
) {
    if clusters.is_empty() {
        return;
    }

    let show_ordinals = depth == 1;
    let widths = column_widths(clusters, with_ranges, score_path, show_ordinals);
    let sibling_max_total = clusters.iter().map(|c| c.total).max().unwrap_or(0);
    let indent = "  ".repeat(depth);

    for cluster in clusters {
        let bar = if with_bars {
            format_bar(cluster.total, sibling_max_total)
        } else {
            String::new()
        };
        let bar_opt = if bar.is_empty() {
            None
        } else {
            Some(bar.as_str())
        };

        let line_width = visible_width_of_assembled(&indent, &widths, bar_opt);
        if line_width > *max {
            *max = line_width;
        }

        if !cluster.clusters.is_empty() {
            walk_group_widths(
                &cluster.clusters,
                depth + 1,
                with_bars,
                with_ranges,
                score_path,
                max,
            );
        }
    }
}

fn write_header(out: &mut String, envelope: &Envelope, opts: &RenderOptions) {
    let total = envelope.result.input_total;
    let header = format!("face: {total} items");
    if opts.color {
        out.push_str(BOLD_ON);
        out.push_str(&header);
        out.push_str(BOLD_OFF);
    } else {
        out.push_str(&header);
    }
    out.push('\n');
    if let Some(grouping) = grouping_header(envelope) {
        out.push_str(&colorize(&grouping, DIM_ON, DIM_OFF, opts.color));
        out.push('\n');
    }
}

fn grouping_header(envelope: &Envelope) -> Option<String> {
    if envelope.result.axes.is_empty() {
        return None;
    }
    let axes = envelope
        .result
        .axes
        .iter()
        .map(|axis| format!("{} ({})", axis.field, axis.strategy.name()))
        .collect::<Vec<_>>()
        .join(" -> ");
    Some(format!("grouped by: {axes}"))
}

fn write_cluster_group(
    out: &mut String,
    clusters: &[Cluster],
    depth: usize,
    opts: &RenderOptions,
    layout: &Layout,
    score_path: Option<&str>,
) {
    if clusters.is_empty() {
        return;
    }

    let show_ordinals = depth == 1;
    let widths = column_widths(clusters, layout.show_ranges, score_path, show_ordinals);
    let sibling_max_total = clusters.iter().map(|c| c.total).max().unwrap_or(0);
    let indent = "  ".repeat(depth);

    for (index, cluster) in clusters.iter().enumerate() {
        let count = cluster.total.to_string();
        let score_range = if layout.show_ranges {
            cluster_score_range(cluster, score_path)
        } else {
            None
        };
        let ordinal = show_ordinals.then(|| format_ordinal(index));
        let bar = if layout.show_bars {
            format_bar(cluster.total, sibling_max_total)
        } else {
            String::new()
        };
        let bar_opt = if bar.is_empty() {
            None
        } else {
            Some(bar.as_str())
        };

        let line = assemble(
            LineParts {
                indent: &indent,
                ordinal: ordinal.as_deref(),
                label: &cluster.label,
                count: &count,
                score_range: score_range.as_deref(),
                bar: bar_opt,
            },
            opts,
            &widths,
        );
        out.push_str(&line);
        out.push('\n');

        if !cluster.clusters.is_empty() {
            write_cluster_group(out, &cluster.clusters, depth + 1, opts, layout, score_path);
        }
    }
}

fn column_widths(
    clusters: &[Cluster],
    with_ranges: bool,
    score_path: Option<&str>,
    show_ordinals: bool,
) -> ColumnWidths {
    let mut widths = ColumnWidths::default();
    for (index, cluster) in clusters.iter().enumerate() {
        if show_ordinals {
            widths.ordinal = widths.ordinal.max(format_ordinal(index).chars().count());
        }
        widths.label = widths.label.max(cluster.label.chars().count());
        widths.count = widths.count.max(cluster.total.to_string().chars().count());
        if with_ranges {
            let range = cluster_score_range(cluster, score_path);
            widths.range = widths.range.max(
                range
                    .as_deref()
                    .map(str::chars)
                    .map(Iterator::count)
                    .unwrap_or(0),
            );
        }
    }
    widths
}

fn format_ordinal(index: usize) -> String {
    format!("[{}]", index + 1)
}

fn cluster_score_range(cluster: &Cluster, score_path: Option<&str>) -> Option<String> {
    if score_path.is_some_and(|path| path_matches_axis(path, &cluster.axis)) {
        None
    } else {
        format_score_range(cluster.score_min, cluster.score_max)
    }
}

fn path_matches_axis(path: &str, axis: &str) -> bool {
    path.trim_start_matches('.') == axis.trim_start_matches('.')
}

/// Visible-width measurement counterpart of [`assemble`]: same column
/// layout, no color. Used by [`decide_layout`] before color is
/// applied. Keeping this aligned with `assemble`'s spacing rules
/// guarantees the layout-decision width matches what the renderer
/// actually emits.
fn visible_width_of_assembled(indent: &str, widths: &ColumnWidths, bar: Option<&str>) -> usize {
    let mut w = 0;
    w += indent.chars().count();
    if widths.ordinal > 0 {
        w += widths.ordinal;
        w += 2;
    }
    w += widths.label;
    w += 2; // gap to count
    w += widths.count;
    if widths.range > 0 {
        w += 2;
        w += widths.range;
    }
    if let Some(bar) = bar
        && !bar.is_empty()
    {
        w += 2;
        w += bar.chars().count();
    }
    w
}

fn assemble(parts: LineParts<'_>, opts: &RenderOptions, widths: &ColumnWidths) -> String {
    let mut s = String::new();
    s.push_str(parts.indent);
    if widths.ordinal > 0 {
        push_padded(
            &mut s,
            parts.ordinal.unwrap_or(""),
            widths.ordinal,
            Align::Right,
            None,
        );
        s.push_str("  ");
    }
    push_padded(
        &mut s,
        parts.label,
        widths.label,
        Align::Left,
        opts.color.then_some((BOLD_ON, BOLD_OFF)),
    );
    s.push_str("  ");
    push_padded(&mut s, parts.count, widths.count, Align::Right, None);
    if widths.range > 0 {
        s.push_str("  ");
        push_padded(
            &mut s,
            parts.score_range.unwrap_or(""),
            widths.range,
            Align::Left,
            opts.color.then_some((DIM_ON, DIM_OFF)),
        );
    }
    if let Some(bar) = parts.bar
        && !bar.is_empty()
    {
        s.push_str("  ");
        s.push_str(&colorize(bar, CYAN_ON, CYAN_OFF, opts.color));
    }
    s
}

#[derive(Debug, Clone, Copy)]
enum Align {
    Left,
    Right,
}

fn push_padded(
    out: &mut String,
    value: &str,
    width: usize,
    align: Align,
    color: Option<(&str, &str)>,
) {
    let value_width = value.chars().count();
    let pad = width.saturating_sub(value_width);
    if matches!(align, Align::Right) {
        out.push_str(&" ".repeat(pad));
    }
    if let Some((on, off)) = color {
        out.push_str(on);
        out.push_str(value);
        out.push_str(off);
    } else {
        out.push_str(value);
    }
    if matches!(align, Align::Left) {
        out.push_str(&" ".repeat(pad));
    }
}

/// Format a score range as `min–max` with U+2013 EN DASH and 2-decimal
/// precision (§8.3 example uses `0.85–1.00`). Returns `None` when both
/// ends are missing — i.e. no score path is in use for this cluster.
fn format_score_range(min: Option<f64>, max: Option<f64>) -> Option<String> {
    match (min, max) {
        (None, None) => None,
        (Some(lo), Some(hi)) => Some(format!("{lo:.2}\u{2013}{hi:.2}")),
        // Asymmetric pairs aren't expected from the clusterer, but
        // fall back to a half-open form rather than panicking.
        (Some(lo), None) => Some(format!("{lo:.2}\u{2013}")),
        (None, Some(hi)) => Some(format!("\u{2013}{hi:.2}")),
    }
}

/// Build an ASCII bar scaled to the largest sibling's count. Uses
/// U+2588 FULL BLOCK for whole units and the U+258F→U+2589 partial
/// blocks for the trailing eighth. Returns the empty string when the
/// sibling max is zero (no signal to scale against).
fn format_bar(total: u64, sibling_max_total: u64) -> String {
    if sibling_max_total == 0 || total == 0 {
        return String::new();
    }
    const EIGHTHS_PER_CELL: u64 = 8;
    let eighths_total = (BAR_BUDGET as u64) * EIGHTHS_PER_CELL;
    let eighths = (total * eighths_total) / sibling_max_total;
    let full = eighths / EIGHTHS_PER_CELL;
    let partial = eighths % EIGHTHS_PER_CELL;

    let mut bar = String::new();
    for _ in 0..full {
        bar.push('\u{2588}');
    }
    if partial > 0 {
        // U+258F (1/8) up to U+2589 (7/8). The Unicode block-shading
        // sequence is descending: U+2588 = full, U+2589 = 7/8, ...,
        // U+258F = 1/8.
        let ch = match partial {
            1 => '\u{258F}',
            2 => '\u{258E}',
            3 => '\u{258D}',
            4 => '\u{258C}',
            5 => '\u{258B}',
            6 => '\u{258A}',
            7 => '\u{2589}',
            _ => '\u{2588}',
        };
        bar.push(ch);
    }
    bar
}

fn write_page(out: &mut String, envelope: &Envelope) {
    let cluster_id_label = envelope
        .page
        .cluster_id
        .as_ref()
        .map(|id| id.to_string())
        .unwrap_or_else(|| "<root>".to_string());
    out.push('\n');
    out.push_str(&format!(
        "Page {cluster_id_label} (page {} of items {}):\n",
        envelope.page.page, envelope.page.total_items
    ));
    for item in &envelope.page.items {
        // Pretty JSON, one object per item. `to_string_pretty` on a
        // `serde_json::Value` cannot fail: the `Value` enum has no
        // non-string-keyed maps and no NaN floats, so serialization is
        // infallible.
        let line = serde_json::to_string_pretty(item)
            .expect("serializing serde_json::Value is infallible");
        out.push_str(&line);
        out.push('\n');
    }
}

fn colorize(s: &str, on: &str, off: &str, color: bool) -> String {
    if color {
        format!("{on}{s}{off}")
    } else {
        s.to_string()
    }
}

// ---------- ANSI escapes ----------
//
// Hand-rolled per the slice brief — no `colored` / `owo-colors` /
// `nu-ansi-term` dependency. The CSI codes here are the lowest common
// denominator supported by every terminal the CLI is expected to see.

const BOLD_ON: &str = "\x1b[1m";
const BOLD_OFF: &str = "\x1b[22m";
const DIM_ON: &str = "\x1b[2m";
const DIM_OFF: &str = "\x1b[22m";
const CYAN_ON: &str = "\x1b[36m";
const CYAN_OFF: &str = "\x1b[39m";

#[cfg(test)]
mod tests {
    use super::*;
    use crate::format::OutputFormat;
    use crate::{Cluster, ClusterId, ClusterIdSegment, Envelope};
    use serde_json::json;

    fn cluster(id_seg: (&str, &str), label: &str, total: u64, children: Vec<Cluster>) -> Cluster {
        let id = ClusterId::new(vec![ClusterIdSegment {
            axis: id_seg.0.into(),
            value: id_seg.1.into(),
        }]);
        Cluster {
            id,
            label: label.to_string(),
            axis: id_seg.0.to_string(),
            value: json!(id_seg.1),
            total,
            score_min: None,
            score_max: None,
            clusters: children,
        }
    }

    fn envelope_with(clusters: Vec<Cluster>, total: u64) -> Envelope {
        Envelope {
            result: crate::ResultBlock {
                input_total: total,
                ..crate::ResultBlock::default()
            },
            clusters,
            ..Envelope::default()
        }
    }

    #[test]
    fn renders_simple_two_cluster_tree() {
        let env = envelope_with(
            vec![
                cluster(("file", "src/cli.rs"), "src/cli.rs", 38, vec![]),
                cluster(("file", "src/core.rs"), "src/core.rs", 27, vec![]),
            ],
            65,
        );
        let out = super::render(&env, &RenderOptions::default());
        assert!(out.starts_with("face: 65 items\n"));
        assert!(out.contains("src/cli.rs"));
        assert!(out.contains("src/core.rs"));
        assert!(out.contains(" 38 "));
        assert!(out.contains(" 27 "));
        // Bar drawn for the 38-count cluster (largest).
        assert!(out.contains('\u{2588}'));
    }

    #[test]
    fn respects_width_drops_bars_first() {
        let env = envelope_with(
            vec![Cluster {
                score_min: Some(0.7),
                score_max: Some(0.85),
                ..cluster(("score", "strong"), "strong", 18, vec![])
            }],
            18,
        );

        // Wide: bar AND range present.
        let wide = super::render(
            &env,
            &RenderOptions {
                color: false,
                width: Some(120),
            },
        );
        assert!(wide.contains('\u{2588}'), "wide should keep bars");
        assert!(wide.contains("0.70\u{2013}0.85"), "wide should keep range");

        // Narrow enough to drop the bar but keep the range.
        let medium = super::render(
            &env,
            &RenderOptions {
                color: false,
                width: Some(28),
            },
        );
        assert!(
            !medium.contains('\u{2588}'),
            "narrow drops bars first: {medium:?}"
        );
        assert!(
            medium.contains("0.70\u{2013}0.85"),
            "narrow still has range: {medium:?}"
        );

        // Very narrow: range dropped too.
        let very_narrow = super::render(
            &env,
            &RenderOptions {
                color: false,
                width: Some(15),
            },
        );
        assert!(!very_narrow.contains('\u{2588}'));
        assert!(!very_narrow.contains('\u{2013}'));
        // Label survives even though width is exceeded.
        assert!(very_narrow.contains("strong"));
    }

    #[test]
    fn color_off_emits_no_ansi() {
        let env = envelope_with(
            vec![Cluster {
                score_min: Some(0.7),
                score_max: Some(0.85),
                ..cluster(("file", "src/cli.rs"), "src/cli.rs", 38, vec![])
            }],
            38,
        );
        let out = super::render(
            &env,
            &RenderOptions {
                color: false,
                width: None,
            },
        );
        assert!(!out.contains('\x1b'), "no ANSI when color=false: {out:?}");
    }

    #[test]
    fn color_on_emits_ansi() {
        let env = envelope_with(
            vec![cluster(("file", "src/cli.rs"), "src/cli.rs", 1, vec![])],
            1,
        );
        let out = super::render(
            &env,
            &RenderOptions {
                color: true,
                width: None,
            },
        );
        assert!(out.contains("\x1b["));
        assert!(out.contains(BOLD_ON));
    }

    #[test]
    fn nested_clusters_indent_two_per_level() {
        let inner = cluster(("score", "excellent"), "excellent", 12, vec![]);
        let outer = cluster(("file", "src/cli.rs"), "src/cli.rs", 38, vec![inner]);
        let env = envelope_with(vec![outer], 38);
        let out = super::render(&env, &RenderOptions::default());
        // Top-level has 2-space indent plus its drill ordinal; inner has 4.
        assert!(out.contains("\n  [1]  src/cli.rs"));
        assert!(out.contains("\n    excellent"));
    }

    #[test]
    fn dispatch_through_top_level_render() {
        // Sanity: the top-level `render` function reaches this module.
        use crate::format::render;
        let env = Envelope::default();
        let out = render(&env, OutputFormat::Human, &RenderOptions::default()).unwrap();
        assert!(out.starts_with("face: 0 items"));
    }
}