nornir 0.4.15

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
//! 🧪 **Test** tab — the C6 test-matrix (`test_results`) as a *shining* viz
//! surface (EPIC L5).
//!
//! A gorgeous **per-repo × per-aspect** matrix over the warehouse
//! [`test_results`](crate::warehouse::test_results) table:
//!
//!   * **Grid** — rows = repos (each repo's latest run), columns = aspects
//!     (build · unit · doctest · clippy · fmt · audit · coverage · …). Each cell
//!     is colour-coded by status (green = pass, red = fail/stalled, amber/grey =
//!     skip, faint = not-run) on the active **facett palette**, with zebra rows,
//!     hover highlight, and a selection accent.
//!   * **Metric badges** in cells — coverage `87%`, clippy `⚠3`, audit `🛡0`,
//!     unit `142✓ 2✗` — type-aware, right-aligned.
//!   * **Per-aspect trend sparklines** across recent runs (coverage rising,
//!     warnings falling).
//!   * **Health score** (0–100) per repo as a prominent badge on a colour ramp,
//!     plus a summary strip of total green / red / skip across the matrix.
//!   * **Drill-down** — click a cell to expand its failing cases (name + message).
//!   * **Palette-switchable** — a picker re-skins everything; looks great in all
//!     facett palettes.
//!
//! Everything rendered is exposed via `state_json()["test"]["grid"]` and the
//! `$NORNIR_VIZ_TRACE` IN/OUT/END stream (THE_BIG_PLAN LAW: "see what the user
//! sees" as data).
//!
//! Read path: **local** mode opens the warehouse read-only and calls
//! [`query_test_results`] — lock-tolerant, like the Release tab. **Remote** mode
//! shows a note (no `Test.Results` RPC yet).

use std::path::PathBuf;

use eframe::egui::{self, Color32, CornerRadius, FontId, Pos2, Rect, RichText, ScrollArea, Sense, Stroke, StrokeKind, Vec2};

use super::facett_theme::Theme;
use super::test_matrix_grid::{Cell, Matrix, RepoRow};
use crate::warehouse::iceberg::IcebergWarehouse;
use crate::warehouse::test_results::{
    query_test_results, status, summarize_runs, RunSummary, TestResultRow, TestSelector,
};

/// Where the test results come from (mirrors the other tabs' local/remote split).
enum Src {
    Local(PathBuf),
    /// No `Test.Results` RPC exists yet — remote mode shows a note.
    Remote { endpoint: String },
}

pub struct TestTabState {
    src: Src,
    loaded: bool,
    error: Option<String>,
    /// Every case row, sorted; grouped on demand.
    rows: Vec<TestResultRow>,
    /// Per-run summaries, newest first (kept for the back-compat state_json shape).
    summaries: Vec<RunSummary>,
    /// The selected run_id (defaults to newest) — back-compat / cases view.
    selected_run: Option<String>,
    /// The freshly-built repo × aspect grid (rebuilt on load / inject).
    matrix: Matrix,
    /// The active facett palette (palette-switcher).
    theme: Theme,
    /// The drilled-down cell: `(repo, aspect)`. `None` = no drill-down open.
    selected_cell: Option<(String, String)>,
}

impl TestTabState {
    pub fn local(root: PathBuf) -> Self {
        Self::with(Src::Local(root))
    }

    pub fn remote(endpoint: String) -> Self {
        Self::with(Src::Remote { endpoint })
    }

    fn with(src: Src) -> Self {
        Self {
            src,
            loaded: false,
            error: None,
            rows: Vec::new(),
            summaries: Vec::new(),
            selected_run: None,
            matrix: Matrix::build(&[]),
            theme: Theme::default(),
            selected_cell: None,
        }
    }

    /// Test-only: inject `test_results` rows directly (no warehouse on disk),
    /// marking the tab loaded so `draw`/`state_json` render the injected matrix.
    #[doc(hidden)]
    pub fn inject_for_test(&mut self, mut rows: Vec<TestResultRow>) {
        rows.sort_by(|a, b| {
            (a.ts_micros, &a.run_id, &a.suite, &a.test_name)
                .cmp(&(b.ts_micros, &b.run_id, &b.suite, &b.test_name))
        });
        self.summaries = summarize_runs(&rows);
        self.selected_run = self.summaries.first().map(|s| s.run_id.clone());
        self.matrix = Matrix::build(&rows);
        self.rows = rows;
        self.loaded = true;
        self.error = None;
        self.selected_cell = None;
        self.emit_trace();
    }

    /// Set the active facett palette (C8) — driven by the app-wide 🎨 picker, so
    /// the Test matrix re-skins in lockstep with every other pane. The tab's own
    /// inline palette combo still works and stays in sync (both write `self.theme`).
    pub fn set_palette(&mut self, t: Theme) {
        self.theme = t;
    }

    /// Re-scope (workspace switch / reload): drop the cache so the next draw reloads.
    pub fn reload(&mut self) {
        self.loaded = false;
        self.error = None;
        self.rows.clear();
        self.summaries.clear();
        self.selected_run = None;
        self.matrix = Matrix::build(&[]);
        self.selected_cell = None;
    }

    /// Read every test result from the warehouse (local only).
    fn load(&mut self) {
        if self.loaded {
            return;
        }
        self.loaded = true;
        super::trace::emit_in(
            "test.matrix.load",
            &serde_json::json!({ "source": self.source_label() }),
        );
        let rows = match &self.src {
            Src::Local(root) => match IcebergWarehouse::open_read_only(root)
                .and_then(|wh| wh.block_on(query_test_results(&wh, &TestSelector::All)))
            {
                Ok(rows) => rows,
                Err(e) => {
                    self.error = Some(format!("{e:#}"));
                    return;
                }
            },
            Src::Remote { .. } => return,
        };
        self.summaries = summarize_runs(&rows);
        self.selected_run = self.summaries.first().map(|s| s.run_id.clone());
        self.matrix = Matrix::build(&rows);
        self.rows = rows;
        self.emit_trace();
    }

    fn source_label(&self) -> String {
        match &self.src {
            Src::Local(p) => format!("local {}", p.display()),
            Src::Remote { endpoint } => format!("remote {endpoint} (Test.Results RPC TODO)"),
        }
    }

    /// Emit the grid OUT/END trace — the machine-readable twin of what we paint.
    fn emit_trace(&self) {
        super::trace::emit_out("test.matrix.build", &self.grid_json());
        super::trace::emit_end(
            "test.matrix",
            &serde_json::json!({
                "repos": self.matrix.rows.len(),
                "aspects": self.matrix.aspects.len(),
                "green": self.matrix.total_green,
                "red": self.matrix.total_red,
                "skip": self.matrix.total_skip,
                "blank": self.matrix.total_blank,
            }),
        );
    }

    /// The currently-selected run's summary (or the newest if none chosen).
    fn current(&self) -> Option<&RunSummary> {
        let sel = self.selected_run.as_deref();
        sel.and_then(|id| self.summaries.iter().find(|s| s.run_id == id))
            .or_else(|| self.summaries.first())
    }

    pub fn draw(&mut self, ui: &mut egui::Ui) {
        self.load();

        if let Src::Remote { endpoint } = &self.src {
            ui.add_space(20.0);
            ui.heading("🧪 Test matrix");
            ui.label(format!(
                "Test results live in the warehouse on `{endpoint}`. A streaming \
                 Test.Results RPC is not wired yet — point the viz at a local \
                 warehouse (NORNIR_WAREHOUSE=…) to browse the test matrix, or use \
                 `nornir test history <repo>` on the server host."
            ));
            return;
        }

        if let Some(err) = self.error.clone() {
            ui.colored_label(super::facett_theme::RED, format!("test_results read failed:\n{err}"));
            return;
        }
        if self.matrix.rows.is_empty() {
            ui.vertical_centered(|ui| {
                ui.add_space(40.0);
                ui.heading("🧪 Test — no test runs recorded yet");
                ui.label("Run the standardized matrix to light this up:");
                ui.monospace("nornir test <repo>      # one repo");
                ui.monospace("nornir test all          # every repo");
                ui.monospace("nornir test history <repo>   # CLI twin");
            });
            return;
        }

        let theme = self.theme;

        // ── top strip: palette picker + summary totals ───────────────────────
        egui::TopBottomPanel::top("test_controls").show_inside(ui, |ui| {
            ui.add_space(4.0);
            ui.horizontal_wrapped(|ui| {
                ui.label(RichText::new("🧪 Test matrix").heading().color(theme.text));
                ui.separator();
                ui.label(RichText::new("palette:").color(theme.text_dim));
                let mut chosen = self.theme.name.to_string();
                egui::ComboBox::from_id_salt("test_palette")
                    .selected_text(self.theme.name)
                    .show_ui(ui, |ui| {
                        for name in Theme::names() {
                            ui.selectable_value(&mut chosen, name.to_string(), name);
                        }
                    });
                if chosen != self.theme.name {
                    if let Some(t) = Theme::by_name(&chosen) {
                        self.theme = t;
                        super::trace::emit_event(
                            "test.matrix.palette",
                            &serde_json::json!({ "palette": t.name }),
                        );
                    }
                }
                ui.separator();
                summary_strip(ui, &theme, &self.matrix);
                if ui.button("↻ reload").on_hover_text("re-read test_results").clicked() {
                    self.reload();
                }
            });
            ui.add_space(4.0);
        });

        // ── drill-down panel (bottom) when a cell is selected ────────────────
        if self.selected_cell.is_some() {
            egui::TopBottomPanel::bottom("test_drilldown")
                .resizable(true)
                .default_height(180.0)
                .show_inside(ui, |ui| {
                    self.draw_drilldown(ui, &theme);
                });
        }

        // ── the grid (central) ───────────────────────────────────────────────
        egui::CentralPanel::default().show_inside(ui, |ui| {
            // paint the panel background in the palette bg for full immersion.
            let full = ui.available_rect_before_wrap();
            ui.painter().rect_filled(full, CornerRadius::ZERO, theme.bg);
            ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| {
                self.draw_grid(ui, &theme);
            });
        });
    }

    /// Paint the gorgeous repo × aspect grid.
    fn draw_grid(&mut self, ui: &mut egui::Ui, theme: &Theme) {
        let aspects = self.matrix.aspects.clone();
        let n_cols = aspects.len();

        // layout metrics.
        let repo_w = 150.0_f32;
        let health_w = 90.0_f32;
        let cell_w = 84.0_f32;
        let row_h = 46.0_f32;
        let header_h = 30.0_f32;
        let pad = 4.0_f32;

        let total_w = repo_w + health_w + cell_w * n_cols as f32 + pad * 2.0;
        let total_h = header_h + row_h * self.matrix.rows.len() as f32 + pad * 2.0;
        let (rect, _resp) = ui.allocate_exact_size(Vec2::new(total_w, total_h), Sense::hover());
        let painter = ui.painter_at(rect);
        let origin = rect.min + Vec2::new(pad, pad);

        // ── header row: aspect column labels ─────────────────────────────────
        let mut x = origin.x + repo_w + health_w;
        let head_y = origin.y;
        painter.text(
            origin + Vec2::new(6.0, header_h * 0.5),
            egui::Align2::LEFT_CENTER,
            "repo",
            FontId::proportional(13.0),
            theme.text_dim,
        );
        painter.text(
            origin + Vec2::new(repo_w + 6.0, header_h * 0.5),
            egui::Align2::LEFT_CENTER,
            "health",
            FontId::proportional(13.0),
            theme.text_dim,
        );
        for a in &aspects {
            let r = Rect::from_min_size(Pos2::new(x, head_y), Vec2::new(cell_w, header_h));
            painter.text(
                r.center(),
                egui::Align2::CENTER_CENTER,
                short_aspect(a),
                FontId::proportional(12.5),
                theme.accent,
            );
            x += cell_w;
        }
        // header underline.
        painter.line_segment(
            [
                Pos2::new(origin.x, head_y + header_h),
                Pos2::new(origin.x + total_w - pad * 2.0, head_y + header_h),
            ],
            Stroke::new(1.5, theme.panel_stroke),
        );

        // hover + click handling: hit-test the pointer against cell rects.
        let pointer = ui.input(|i| i.pointer.hover_pos());
        let clicked = ui.input(|i| i.pointer.primary_clicked());
        let mut new_selection: Option<(String, String)> = None;

        // ── one row per repo ─────────────────────────────────────────────────
        for (ri, repo) in self.matrix.rows.iter().enumerate() {
            let y = origin.y + header_h + ri as f32 * row_h;
            let row_rect = Rect::from_min_size(
                Pos2::new(origin.x, y),
                Vec2::new(total_w - pad * 2.0, row_h),
            );
            // zebra striping.
            if ri % 2 == 1 {
                painter.rect_filled(row_rect, CornerRadius::same(2), theme.node_fill.linear_multiply(0.5));
            }
            // hover highlight on the whole row.
            let row_hovered = pointer.map(|p| row_rect.contains(p)).unwrap_or(false);
            if row_hovered {
                painter.rect_filled(row_rect, CornerRadius::same(2), theme.accent.linear_multiply(0.06));
            }

            // repo name.
            painter.text(
                Pos2::new(origin.x + 6.0, y + row_h * 0.5),
                egui::Align2::LEFT_CENTER,
                &repo.repo,
                FontId::proportional(14.0),
                theme.text,
            );

            // health badge.
            draw_health_badge(&painter, theme, repo, Pos2::new(origin.x + repo_w, y), health_w, row_h);

            // aspect cells.
            let mut cx = origin.x + repo_w + health_w;
            for (ci, cell) in repo.cells.iter().enumerate() {
                let aspect = &aspects[ci];
                let crect = Rect::from_min_size(Pos2::new(cx + 3.0, y + 4.0), Vec2::new(cell_w - 6.0, row_h - 8.0));
                let hovered = pointer.map(|p| crect.contains(p)).unwrap_or(false);
                let is_sel = self
                    .selected_cell
                    .as_ref()
                    .map(|(r, a)| r == &repo.repo && a == aspect)
                    .unwrap_or(false);

                draw_cell(&painter, theme, cell, aspect, &repo.sparks[ci], crect, hovered, is_sel);

                if hovered && clicked && cell.ran() {
                    new_selection = Some((repo.repo.clone(), aspect.clone()));
                }
                cx += cell_w;
            }
        }

        if let Some(sel) = new_selection {
            // toggle: click the same cell again closes the drill-down.
            if self.selected_cell.as_ref() == Some(&sel) {
                self.selected_cell = None;
            } else {
                super::trace::emit_event(
                    "test.matrix.drilldown",
                    &serde_json::json!({ "repo": sel.0, "aspect": sel.1 }),
                );
                self.selected_cell = Some(sel);
            }
        }
    }

    /// The drill-down: the failing/'s cases for the selected repo × aspect.
    fn draw_drilldown(&mut self, ui: &mut egui::Ui, theme: &Theme) {
        let Some((repo, aspect)) = self.selected_cell.clone() else { return };
        ui.horizontal(|ui| {
            ui.label(RichText::new(format!("🔎 {repo} · {aspect}")).strong().color(theme.accent));
            ui.separator();
            if ui.button("✕ close").clicked() {
                self.selected_cell = None;
            }
        });
        ui.separator();
        let Some(row) = self.matrix.rows.iter().find(|r| r.repo == repo) else { return };
        let Some(ci) = self.matrix.aspects.iter().position(|a| a == &aspect) else { return };
        let cell = &row.cells[ci];
        ui.horizontal(|ui| {
            let (chip, col) = status_chip(theme, &cell.status);
            ui.label(RichText::new(chip).monospace().strong().color(col));
            let badge = cell.badge(&aspect);
            if !badge.is_empty() {
                ui.label(RichText::new(badge).strong().color(theme.text));
            }
            ui.weak(format!("{} case(s) in latest run", cell.count));
        });
        ui.add_space(4.0);
        ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
            if cell.red_cases.is_empty() {
                ui.colored_label(theme.text_dim, "no failing cases — this aspect is clean ✓");
            }
            for rc in &cell.red_cases {
                ui.horizontal_wrapped(|ui| {
                    let (chip, col) = status_chip(theme, &rc.status);
                    ui.label(RichText::new(chip).monospace().strong().color(col));
                    ui.label(RichText::new(format!("{}::{}", rc.suite, rc.test_name)).color(theme.text));
                    if !rc.message.is_empty() {
                        ui.colored_label(super::facett_theme::RED, &rc.message);
                    }
                });
            }
        });
    }

    /// Test/introspection hook: the matrix the tab renders, as JSON folded into
    /// the app's `state_json` (LAW #6). Carries both the **new grid** shape and
    /// the legacy run/cases shape (for the existing run-summary consumers).
    pub fn state_json(&self) -> serde_json::Value {
        let current = self.current();
        let cases: Vec<serde_json::Value> = current
            .map(|run| {
                self.rows
                    .iter()
                    .filter(|r| r.run_id == run.run_id)
                    .map(|r| {
                        serde_json::json!({
                            "suite": r.suite,
                            "test_name": r.test_name,
                            "status": r.status,
                            "duration_ms": r.duration_ms,
                            "message": r.message,
                            "aspect": r.aspect,
                            "metric": r.metric,
                            "red": status::is_red(&r.status),
                        })
                    })
                    .collect()
            })
            .unwrap_or_default();
        let runs: Vec<serde_json::Value> = self
            .summaries
            .iter()
            .map(|s| {
                serde_json::json!({
                    "run_id": s.run_id,
                    "repo": s.repo,
                    "green": s.green(),
                    "passed": s.passed,
                    "failed": s.failed,
                    "ignored": s.ignored,
                    "stalled": s.stalled,
                    "skipped": s.skipped,
                    "total": s.total(),
                })
            })
            .collect();
        serde_json::json!({
            "source": self.source_label(),
            "error": self.error,
            "palette": self.theme.name,
            "runs": runs,
            "run_count": self.summaries.len(),
            "selected_run": current.map(|s| s.run_id.clone()),
            "selected_repo": current.map(|s| s.repo.clone()),
            "selected_green": current.map(|s| s.green()),
            "selected_cell": self.selected_cell.as_ref().map(|(r, a)| serde_json::json!({ "repo": r, "aspect": a })),
            "cases": cases,
            "grid": self.grid_json(),
        })
    }

    /// The grid itself, as data: aspects, per-repo cells (status + metric +
    /// badge), health scores, sparkline series, and the summary-strip totals.
    fn grid_json(&self) -> serde_json::Value {
        let m = &self.matrix;
        let rows: Vec<serde_json::Value> = m
            .rows
            .iter()
            .map(|r| {
                let cells: Vec<serde_json::Value> = r
                    .cells
                    .iter()
                    .enumerate()
                    .map(|(ci, c)| {
                        let aspect = &m.aspects[ci];
                        serde_json::json!({
                            "aspect": aspect,
                            "status": c.status,
                            "ran": c.ran(),
                            "red": c.is_red(),
                            "green": c.is_green(),
                            "metric": c.metric,
                            "badge": c.badge(aspect),
                            "count": c.count,
                            "passed": c.passed,
                            "failed": c.failed,
                            "red_cases": c.red_cases.iter().map(|rc| serde_json::json!({
                                "test_name": rc.test_name,
                                "suite": rc.suite,
                                "status": rc.status,
                                "message": rc.message,
                            })).collect::<Vec<_>>(),
                            "spark": r.sparks[ci],
                        })
                    })
                    .collect();
                serde_json::json!({
                    "repo": r.repo,
                    "run_id": r.run_id,
                    "health": (r.health * 10.0).round() / 10.0,
                    "cells": cells,
                })
            })
            .collect();
        serde_json::json!({
            "aspects": m.aspects,
            "repos": m.rows.iter().map(|r| r.repo.clone()).collect::<Vec<_>>(),
            "rows": rows,
            "totals": {
                "green": m.total_green,
                "red": m.total_red,
                "skip": m.total_skip,
                "blank": m.total_blank,
            },
        })
    }
}

// ─── painters ────────────────────────────────────────────────────────────────

/// The top summary strip: total green / red / skip / not-run across the matrix.
fn summary_strip(ui: &mut egui::Ui, theme: &Theme, m: &Matrix) {
    let chip = |ui: &mut egui::Ui, col: Color32, label: &str, n: usize| {
        ui.label(RichText::new("").color(col));
        ui.label(RichText::new(format!("{n} {label}")).color(theme.text));
        ui.add_space(6.0);
    };
    chip(ui, super::facett_theme::GREEN, "green", m.total_green);
    chip(ui, super::facett_theme::RED, "red", m.total_red);
    chip(ui, Color32::from_rgb(150, 150, 160), "skip", m.total_skip);
    chip(ui, theme.node_fill, "", m.total_blank);
}

/// The per-repo health badge (a 0–100 pill on the health colour ramp).
fn draw_health_badge(painter: &egui::Painter, theme: &Theme, repo: &RepoRow, top_left: Pos2, w: f32, h: f32) {
    let pill = Rect::from_min_size(Pos2::new(top_left.x + 4.0, top_left.y + 9.0), Vec2::new(w - 12.0, h - 18.0));
    let col = theme.health_color(repo.health);
    painter.rect_filled(pill, CornerRadius::same(7), col.linear_multiply(0.28));
    painter.rect_stroke(pill, CornerRadius::same(7), Stroke::new(1.5, col), StrokeKind::Inside);
    painter.text(
        pill.center(),
        egui::Align2::CENTER_CENTER,
        format!("{:.0}", repo.health),
        FontId::proportional(16.0),
        col,
    );
}

/// Paint one matrix cell: a status-coloured rounded tile, a metric badge, and a
/// faint trend sparkline.
fn draw_cell(
    painter: &egui::Painter,
    theme: &Theme,
    cell: &Cell,
    aspect: &str,
    spark: &[f64],
    rect: Rect,
    hovered: bool,
    selected: bool,
) {
    if !cell.ran() {
        // not-run: a faint dashed-feel tile.
        painter.rect_filled(rect, CornerRadius::same(6), theme.node_fill.linear_multiply(0.35));
        painter.text(rect.center(), egui::Align2::CENTER_CENTER, "·", FontId::proportional(16.0), theme.text_dim);
        return;
    }
    let fill = theme.status_fill(&cell.status);
    let bg_alpha = if hovered { 0.45 } else { 0.30 };
    painter.rect_filled(rect, CornerRadius::same(6), fill.linear_multiply(bg_alpha));
    let stroke_w = if selected { 2.5 } else { 1.2 };
    let stroke_col = if selected { theme.accent } else { fill };
    painter.rect_stroke(rect, CornerRadius::same(6), Stroke::new(stroke_w, stroke_col), StrokeKind::Inside);

    // status mark (top-left) — painted as a primitive so it renders in every
    // font (the bundled emoji font lacks ✓/✗, which tofu as boxes).
    let mark_c = Pos2::new(rect.min.x + 11.0, rect.min.y + 12.0);
    match cell.status.as_str() {
        status::PASS => {
            painter.circle_filled(mark_c, 4.0, fill);
        }
        status::FAIL => {
            // a small ✗ drawn from two strokes.
            let r = 4.0;
            painter.line_segment([mark_c + Vec2::new(-r, -r), mark_c + Vec2::new(r, r)], Stroke::new(2.0, fill));
            painter.line_segment([mark_c + Vec2::new(-r, r), mark_c + Vec2::new(r, -r)], Stroke::new(2.0, fill));
        }
        status::STALLED => {
            painter.circle_stroke(mark_c, 4.0, Stroke::new(2.0, fill));
        }
        _ => {
            painter.circle_stroke(mark_c, 3.5, Stroke::new(1.5, fill)); // skip / ignored
        }
    }

    // metric badge (right-aligned, top). The unit badge's ✓/✗ are painted as
    // colour-coded numerals so they render font-independently.
    if aspect == "unit" {
        let txt = if cell.failed > 0 {
            format!("{}p {}f", cell.passed, cell.failed)
        } else {
            format!("{}p", cell.passed)
        };
        let col = if cell.failed > 0 { super::facett_theme::RED } else { super::facett_theme::GREEN };
        painter.text(
            Pos2::new(rect.max.x - 5.0, rect.min.y + 8.0),
            egui::Align2::RIGHT_TOP,
            txt,
            FontId::monospace(12.0),
            col,
        );
    } else {
        let badge = cell.badge(aspect);
        if !badge.is_empty() {
            painter.text(
                Pos2::new(rect.max.x - 5.0, rect.min.y + 8.0),
                egui::Align2::RIGHT_TOP,
                badge,
                FontId::monospace(12.0),
                theme.text,
            );
        }
    }

    // trend sparkline along the bottom of the cell.
    draw_sparkline(painter, theme, spark, Rect::from_min_max(
        Pos2::new(rect.min.x + 5.0, rect.max.y - 12.0),
        Pos2::new(rect.max.x - 5.0, rect.max.y - 3.0),
    ));
}

/// A tiny sparkline (values pre-normalized to ~0..100, higher = healthier).
fn draw_sparkline(painter: &egui::Painter, theme: &Theme, series: &[f64], rect: Rect) {
    if series.len() < 2 {
        return;
    }
    let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
    for &v in series {
        lo = lo.min(v);
        hi = hi.max(v);
    }
    let span = (hi - lo).max(1.0);
    let n = series.len();
    let pts: Vec<Pos2> = series
        .iter()
        .enumerate()
        .map(|(i, &v)| {
            let t = i as f32 / (n - 1) as f32;
            let x = rect.min.x + t * rect.width();
            let norm = ((v - lo) / span) as f32; // 0..1
            let y = rect.max.y - norm * rect.height();
            Pos2::new(x, y)
        })
        .collect();
    for w in pts.windows(2) {
        painter.line_segment([w[0], w[1]], Stroke::new(1.4, theme.point));
    }
    // highlight the latest point.
    if let Some(last) = pts.last() {
        painter.circle_filled(*last, 1.8, theme.point);
    }
}

/// A status chip glyph + colour on the active palette.
fn status_chip(theme: &Theme, status: &str) -> (&'static str, Color32) {
    match status {
        crate::warehouse::test_results::status::PASS => ("PASS", super::facett_theme::GREEN),
        crate::warehouse::test_results::status::FAIL => ("FAIL", super::facett_theme::RED),
        crate::warehouse::test_results::status::IGNORED => ("IGN ", theme.text_dim),
        crate::warehouse::test_results::status::STALLED => ("STALL", super::facett_theme::AMBER),
        crate::warehouse::test_results::status::SKIP => ("SKIP", Color32::from_rgb(150, 150, 160)),
        _ => ("?", theme.text_dim),
    }
}

/// Compact a long aspect label for the narrow column header.
fn short_aspect(a: &str) -> &str {
    match a {
        "bench-smoke" => "bench",
        "feature-powerset" => "fpow",
        "doctest" => "doc",
        other => other,
    }
}