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
//! Integration tests for `--format=human` (§8.3 of `docs/design.md`).
//!
//! Pins the human renderer's observable behavior:
//! - Two top-level clusters render in count-desc order with their counts.
//! - Top-level clusters carry 1-based ordinal labels for quick drilling.
//! - Score ranges use the en-dash `–` (U+2013).
//! - ANSI escapes only when `RenderOptions::color = true`.
//! - Width-aware: bars drop first, then score ranges.
//! - Nested clusters indent more than their parents.
//! - Page items appear after the cluster tree as pretty JSON.
//!
//! Assertions are substring / regex level — never byte-for-byte —
//! so the renderer can refactor whitespace without churning tests.

use face_core::{Envelope, OutputFormat, RenderOptions, render};
use serde_json::json;

/// Single-axis fixture per the slice-8 test brief: two top-level
/// clusters (`bug` total=20, `feat` total=18), score ranges populated.
fn fixture_envelope() -> Envelope {
    serde_json::from_value(json!({
        "result": {
            "input_total": 38,
            "skipped": 0,
            "axes": [{ "field": "kind", "strategy": "exact", "auto": false }],
            "detection": {
                "format": "json",
                "items_path": ".",
                "score_path": null,
                "preset": null,
                "fallback_reason": null
            }
        },
        "meta": {},
        "clusters": [
            {
                "id": "kind:bug",
                "label": "bug",
                "axis": "kind",
                "value": "bug",
                "total": 20,
                "score_min": 0.7,
                "score_max": 0.95,
                "clusters": []
            },
            {
                "id": "kind:feat",
                "label": "feat",
                "axis": "kind",
                "value": "feat",
                "total": 18,
                "score_min": 0.5,
                "score_max": 0.85,
                "clusters": []
            }
        ],
        "page": { "cluster_id": null, "page": 1, "per_page": 20, "total_items": 0, "items": [] }
    }))
    .expect("fixture envelope")
}

/// Two-axis fixture for nesting tests: `kind` outer with `score`
/// sub-clusters under each.
fn fixture_two_axis() -> Envelope {
    serde_json::from_value(json!({
        "result": {
            "input_total": 38,
            "skipped": 0,
            "axes": [
                { "field": "kind", "strategy": "exact", "auto": false },
                { "field": "score", "strategy": "bands", "count": 3, "auto": true }
            ],
            "detection": {
                "format": "json",
                "items_path": ".",
                "score_path": "score",
                "preset": null,
                "fallback_reason": null
            }
        },
        "meta": {},
        "clusters": [
            {
                "id": "kind:bug",
                "label": "bug",
                "axis": "kind",
                "value": "bug",
                "total": 20,
                "score_min": 0.7,
                "score_max": 0.95,
                "clusters": [
                    {
                        "id": "kind:bug,score:excellent",
                        "label": "excellent",
                        "axis": "score",
                        "value": "excellent",
                        "total": 12,
                        "score_min": 0.85,
                        "score_max": 0.95,
                        "clusters": []
                    },
                    {
                        "id": "kind:bug,score:strong",
                        "label": "strong",
                        "axis": "score",
                        "value": "strong",
                        "total": 8,
                        "score_min": 0.7,
                        "score_max": 0.85,
                        "clusters": []
                    }
                ]
            },
            {
                "id": "kind:feat",
                "label": "feat",
                "axis": "kind",
                "value": "feat",
                "total": 18,
                "score_min": 0.5,
                "score_max": 0.85,
                "clusters": []
            }
        ],
        "page": { "cluster_id": null, "page": 1, "per_page": 20, "total_items": 0, "items": [] }
    }))
    .expect("two-axis fixture envelope")
}

/// Fixture with a populated `page.items` block, drilled into `kind:bug`.
fn fixture_with_page() -> Envelope {
    serde_json::from_value(json!({
        "result": {
            "input_total": 38,
            "skipped": 0,
            "axes": [{ "field": "kind", "strategy": "exact", "auto": false }],
            "detection": {
                "format": "json",
                "items_path": ".",
                "score_path": null,
                "preset": null,
                "fallback_reason": null
            }
        },
        "meta": {},
        "clusters": [
            {
                "id": "kind:bug",
                "label": "bug",
                "axis": "kind",
                "value": "bug",
                "total": 20,
                "score_min": null,
                "score_max": null,
                "clusters": []
            }
        ],
        "page": {
            "cluster_id": "kind:bug",
            "page": 1,
            "per_page": 20,
            "total_items": 2,
            "items": [
                { "title": "page-item-alpha-7af3" },
                { "title": "page-item-beta-9c11" }
            ]
        }
    }))
    .expect("fixture with page")
}

/// Build a `RenderOptions` with the given color + width, sidestepping
/// the `#[non_exhaustive]` block on struct-literal construction by
/// starting from `Default` and mutating the public fields.
fn opts(color: bool, width: Option<usize>) -> RenderOptions {
    let mut o = RenderOptions::default();
    o.color = color;
    o.width = width;
    o
}

/// Run the human renderer; panic with the format on failure.
fn human(env: &Envelope, opts: &RenderOptions) -> String {
    render(env, OutputFormat::Human, opts).expect("human render")
}

mod basic {
    //! Smoke-level human format checks: labels, counts, score ranges,
    //! color toggling.

    use super::*;

    #[test]
    fn renders_two_top_level_clusters() {
        let env = fixture_envelope();
        let out = human(&env, &RenderOptions::default());
        assert!(out.contains("bug"), "output missing 'bug':\n{out}");
        assert!(out.contains("feat"), "output missing 'feat':\n{out}");

        // Order is count-desc: bug (20) before feat (18).
        let bug_pos = out.find("bug").expect("bug present");
        let feat_pos = out.find("feat").expect("feat present");
        assert!(
            bug_pos < feat_pos,
            "expected count-desc order (bug before feat); output:\n{out}"
        );
    }

    #[test]
    fn chart_header_names_grouping_axis() {
        let env = fixture_envelope();
        let out = human(&env, &RenderOptions::default());
        let header_pos = out
            .find("grouped by: kind (exact)")
            .expect("grouping header present");
        let bug_pos = out.find("bug").expect("bug present");
        assert!(
            header_pos < bug_pos,
            "grouping header should appear before chart rows; output:\n{out}",
        );
    }

    #[test]
    fn nested_chart_header_names_axis_chain() {
        let env = fixture_two_axis();
        let out = human(&env, &RenderOptions::default());
        assert!(
            out.contains("grouped by: kind (exact) -> score (bands)"),
            "nested grouping header should name both axes; output:\n{out}",
        );
    }

    #[test]
    fn cluster_count_appears() {
        let env = fixture_envelope();
        let out = human(&env, &RenderOptions::default());
        // Each label and its total appear on the same line.
        let bug_line = out
            .lines()
            .find(|l| l.contains("bug"))
            .expect("bug line present");
        assert!(
            bug_line.contains("20"),
            "bug line should contain count 20: {bug_line:?}"
        );
        let feat_line = out
            .lines()
            .find(|l| l.contains("feat"))
            .expect("feat line present");
        assert!(
            feat_line.contains("18"),
            "feat line should contain count 18: {feat_line:?}"
        );
    }

    #[test]
    fn top_level_clusters_have_one_based_ordinals() {
        let env = fixture_envelope();
        let out = human(&env, &RenderOptions::default());

        let bug_line = out
            .lines()
            .find(|l| l.contains("bug"))
            .expect("bug line present");
        let feat_line = out
            .lines()
            .find(|l| l.contains("feat"))
            .expect("feat line present");

        assert!(
            bug_line.trim_start().starts_with("[1]"),
            "first cluster should carry [1] ordinal: {bug_line:?}",
        );
        assert!(
            feat_line.trim_start().starts_with("[2]"),
            "second cluster should carry [2] ordinal: {feat_line:?}",
        );
    }

    #[test]
    fn score_range_uses_en_dash() {
        let env = fixture_envelope();
        let out = human(&env, &RenderOptions::default());
        assert!(
            out.contains('\u{2013}'),
            "expected en-dash (U+2013) in score range; output:\n{out}",
        );
    }

    #[test]
    fn no_color_by_default() {
        let env = fixture_envelope();
        let out = human(&env, &RenderOptions::default());
        assert!(
            !out.contains('\x1b'),
            "default RenderOptions must not emit ANSI escape; output:\n{out}",
        );
    }

    #[test]
    fn color_emits_ansi_when_enabled() {
        let env = fixture_envelope();
        let out = human(&env, &opts(true, None));
        assert!(
            out.contains("\x1b["),
            "color=true should emit at least one ANSI CSI sequence; output:\n{out}",
        );
    }

    #[test]
    fn bars_align_across_uneven_numeric_labels() {
        let env: Envelope = serde_json::from_value(json!({
            "result": {
                "input_total": 6,
                "skipped": 0,
                "axes": [{ "field": "score", "strategy": "bands", "count": 2, "auto": true }],
                "detection": {
                    "format": "json",
                    "items_path": ".",
                    "score_path": "score",
                    "preset": null,
                    "fallback_reason": null
                }
            },
            "meta": {},
            "clusters": [
                {
                    "id": "score:32.37–38.28",
                    "label": "32.37–38.28",
                    "axis": "score",
                    "value": { "min": 32.37, "max": 38.28 },
                    "total": 1,
                    "score_min": 38.28,
                    "score_max": 38.28,
                    "clusters": []
                },
                {
                    "id": "score:8.73–14.64",
                    "label": "8.73–14.64",
                    "axis": "score",
                    "value": { "min": 8.73, "max": 14.64 },
                    "total": 5,
                    "score_min": 8.73,
                    "score_max": 13.68,
                    "clusters": []
                }
            ],
            "page": { "cluster_id": null, "page": 1, "per_page": 20, "total_items": 0, "items": [] }
        }))
        .expect("fixture envelope");

        let out = human(&env, &RenderOptions::default());
        assert!(
            !out.contains("38.28–38.28"),
            "score range is redundant when the cluster axis is the score path:\n{out}",
        );
        assert!(
            !out.contains("8.73–13.68"),
            "score range is redundant when the cluster axis is the score path:\n{out}",
        );
        let lines = out
            .lines()
            .filter(|line| line.contains("score:") || line.contains('\u{2588}'))
            .collect::<Vec<_>>();
        assert_eq!(lines.len(), 2, "expected two cluster lines:\n{out}");

        let bar_cols = lines
            .iter()
            .map(|line| {
                line.chars()
                    .position(|ch| ch == '\u{2588}')
                    .unwrap_or_else(|| panic!("line missing bar glyph: {line:?}"))
            })
            .collect::<Vec<_>>();
        assert_eq!(
            bar_cols[0], bar_cols[1],
            "bar columns should align; lines={lines:?}"
        );
    }
}

mod width {
    //! Width-aware degradation: bars drop first, score ranges drop next.

    use super::*;

    /// Unicode block characters used for the bar widget. If the
    /// renderer drops bars, none of these should appear.
    const BAR_GLYPHS: &[char] = &[
        '\u{2588}', //        '\u{2589}', //        '\u{258A}', //        '\u{258B}', //        '\u{258C}', //        '\u{258D}', //        '\u{258E}', //        '\u{258F}', //    ];

    fn contains_any_bar(s: &str) -> bool {
        s.chars().any(|c| BAR_GLYPHS.contains(&c))
    }

    // Width thresholds below are tuned to the slice-8 fixture's content:
    // a non-truncated cluster line is `  bug  20  0.70–0.95  ████████████`
    // (~34 visible chars). Width 30 fits with the bar dropped but keeps
    // the range; width 12 drops both. The original brief's example
    // values (40 / 20) were too generous to trigger degradation against
    // this fixture and were adjusted upward for behavioral accuracy.
    #[test]
    fn width_drops_bars() {
        let env = fixture_envelope();
        let out = human(&env, &opts(false, Some(30)));
        assert!(
            !contains_any_bar(&out),
            "width=30 should drop bars; output:\n{out}",
        );
    }

    #[test]
    fn width_drops_score_range_after_bars() {
        let env = fixture_envelope();
        let out = human(&env, &opts(false, Some(12)));
        assert!(
            !contains_any_bar(&out),
            "width=12 should drop bars; output:\n{out}",
        );
        assert!(
            !out.contains('\u{2013}'),
            "width=12 should drop score range (en-dash); output:\n{out}",
        );
    }

    #[test]
    fn wide_keeps_everything() {
        let env = fixture_envelope();
        // No width cap: bars + score ranges should appear.
        let out = human(&env, &opts(false, None));
        assert!(
            contains_any_bar(&out),
            "no width cap should keep bars; output:\n{out}",
        );
        assert!(
            out.contains('\u{2013}'),
            "no width cap should keep score range; output:\n{out}",
        );
    }
}

mod nesting {
    //! Indentation: child cluster lines are indented further than their
    //! parent.

    use super::*;

    /// Number of leading whitespace chars (spaces or tabs) on `line`.
    fn leading_ws(line: &str) -> usize {
        line.chars().take_while(|c| c.is_whitespace()).count()
    }

    #[test]
    fn nested_clusters_indented_more_than_parents() {
        let env = fixture_two_axis();
        let out = human(&env, &RenderOptions::default());

        let bug_line = out
            .lines()
            .find(|l| l.contains("bug"))
            .expect("bug line present");
        let excellent_line = out
            .lines()
            .find(|l| l.contains("excellent"))
            .expect("excellent line present");

        let bug_ws = leading_ws(bug_line);
        let excellent_ws = leading_ws(excellent_line);

        assert!(
            excellent_ws > bug_ws,
            "child indent ({excellent_ws}) must exceed parent indent ({bug_ws}); \
             parent: {bug_line:?} child: {excellent_line:?}",
        );
        assert!(
            !excellent_line.trim_start().starts_with('['),
            "nested children should not show top-level drill ordinals: {excellent_line:?}",
        );
    }
}

mod page {
    //! Page items appear after the cluster tree.

    use super::*;

    #[test]
    fn page_items_rendered_below_tree() {
        let env = fixture_with_page();
        let out = human(&env, &RenderOptions::default());

        let bug_pos = out.find("bug").expect("bug label present");
        // Soft-match: at least one of the page-item title values appears,
        // and it appears strictly after the cluster tree's label.
        let item_pos = out
            .find("page-item-alpha-7af3")
            .or_else(|| out.find("page-item-beta-9c11"))
            .expect("at least one page-item value should be rendered");
        assert!(
            item_pos > bug_pos,
            "page items should render after cluster tree; output:\n{out}",
        );
    }

    #[test]
    fn page_items_are_pretty_printed_json() {
        let mut env = fixture_with_page();
        env.page.items = vec![json!({
            "name": "newUser",
            "kind": "variant",
            "module": "Room",
            "file": "TaskSystemManager.swift",
            "span": "129:14-129:14",
            "score": 13.6773815,
            "snippet": "case newUser = 11  //新用户房主任务"
        })];

        let out = human(&env, &RenderOptions::default());

        assert!(
            out.contains("{\n  \"file\": \"TaskSystemManager.swift\""),
            "page item should be pretty JSON; output:\n{out}"
        );
        assert!(
            out.contains("  \"name\": \"newUser\""),
            "pretty JSON keeps readable fields; output:\n{out}"
        );
        assert!(
            !out.contains("\"name\":\"newUser\""),
            "page item should not be compact JSON; output:\n{out}"
        );
    }
}