nornir 0.4.11

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
//! Data-only diagram renderers for the viz tabs.
//!
//! Each viz tab paints a diagram with egui — on screen only. These are the
//! **pure-data counterparts**: headless functions that turn the same
//! [`Timeline`] data model into an exportable Markdown / Mermaid diagram, with
//! **no egui dependency**. They are compiled wherever [`model`](super::model)
//! is (the `server` build too — see [`super`] module docs), so the docs
//! exporter, the `Viz.Timeline` RPC, and the CLI can all render the viz
//! diagrams without a display (CLI parity with the GUI).
//!
//! House style mirrors [`crate::introspect::Graph::to_mermaid`]: Mermaid graphs
//! are emitted inside a fenced ```` ```mermaid ```` block so they render in the
//! Codeberg / GitHub web UI with no build step; tabular diagrams are plain
//! GitHub-flavoured Markdown tables.
//!
//! There is one renderer per **diagram-bearing** viz tab (the interactive /
//! tabular ops tabs — LiveRun, Warehouse, Mcp, Search — have no static diagram
//! to export). The eight:
//!
//! | renderer | viz tab | shape |
//! |----------|---------|-------|
//! | [`timeline_mermaid`]     | Timeline   | Mermaid timeline (per-repo sections) |
//! | [`lane_summary_table`]   | Timeline   | per-repo lane summary table |
//! | [`depgraph_mermaid`]     | DepGraph   | Mermaid `graph LR`, edges labelled by `via` crates |
//! | [`snapshot_edge_list`]   | DepGraph   | cross-repo edge / adjacency list |
//! | [`gate_matrix_table`]    | Gates      | release × repo gate-verdict matrix |
//! | [`release_versions_table`] | Funnel   | published crate versions per release |
//! | [`bench_history_table`]  | Bench      | per-repo primary-metric trend (newest first) |
//! | [`bench_compare_table`]  | TimeTravel | latest bench metric across repos |

use std::collections::BTreeSet;
use std::fmt::Write as _;

use crate::warehouse::dep_graph::DepGraphSnapshot;

use super::model::{BenchHistory, Lane, Timeline};

/// Mermaid-safe identifier: the same mapping [`crate::introspect`] uses, so a
/// crate/repo name becomes a bare node id (`skade-katalog` → `skade_katalog`).
fn sanitize(s: &str) -> String {
    s.replace([':', '-', '.', '/', ' '], "_")
}

/// Short git sha (first 7 chars) for compact node/cell labels.
fn short_sha(sha: &str) -> &str {
    &sha[..sha.len().min(7)]
}

/// Pipe-escape a cell value so a stray `|` can't break a Markdown table.
fn cell(s: &str) -> String {
    s.replace('|', "\\|")
}

/// The latest published version for a lane node, if any (`crate v1.2.3` or just
/// the version when the crate name is empty).
fn node_version(versions: &[(String, String)]) -> String {
    versions
        .iter()
        .map(|(c, v)| if c.is_empty() { format!("v{v}") } else { format!("{c} v{v}") })
        .collect::<Vec<_>>()
        .join(", ")
}

// ── Timeline tab ────────────────────────────────────────────────────────────

/// **Timeline tab → Mermaid `timeline`.** One section per repo lane, one event
/// per recorded release (`sha` + gate verdict + published versions). Empty
/// lanes (bench-only repos) are skipped. Returns an italic placeholder when the
/// timeline has no releases at all.
pub fn timeline_mermaid(tl: &Timeline) -> String {
    if !tl.has_releases() {
        return "_no releases recorded yet_\n".to_string();
    }
    let mut s = String::from("```mermaid\ntimeline\n");
    let _ = writeln!(s, "  title {} release timeline", tl.workspace_name);
    for lane in &tl.lanes {
        if lane.nodes.is_empty() {
            continue;
        }
        let _ = writeln!(s, "  section {}", lane.repo);
        for n in &lane.nodes {
            let date = n.timestamp.format("%Y-%m-%d");
            let mut label = format!("{} {}", short_sha(&n.sha), n.gate_status);
            let ver = node_version(&n.published_versions);
            if !ver.is_empty() {
                label.push_str("");
                label.push_str(&ver);
            }
            // Mermaid timeline: `<period> : <event>` (colons inside the event
            // text would split it, so swap them for a dash).
            let _ = writeln!(s, "    {} : {}", date, label.replace(':', "-"));
        }
    }
    s.push_str("```\n");
    s
}

/// **Timeline tab → summary table.** One row per repo lane: number of recorded
/// releases, the newest release's sha / gate / version. The at-a-glance
/// counterpart to the swim-lane painting.
pub fn lane_summary_table(tl: &Timeline) -> String {
    if tl.lanes.is_empty() {
        return "_no repos in this workspace_\n".to_string();
    }
    let mut s = String::from("| Repo | Releases | Latest sha | Gate | Version |\n");
    s.push_str("|------|---------:|-----------|------|---------|\n");
    for lane in &tl.lanes {
        let (sha, gate, ver) = match lane.nodes.last() {
            Some(n) => (
                short_sha(&n.sha).to_string(),
                n.gate_status.clone(),
                node_version(&n.published_versions),
            ),
            None => ("".into(), "".into(), String::new()),
        };
        let ver = if ver.is_empty() { "".to_string() } else { ver };
        let _ = writeln!(
            s,
            "| {} | {} | {} | {} | {} |",
            cell(&lane.repo),
            lane.nodes.len(),
            cell(&sha),
            cell(&gate),
            cell(&ver),
        );
    }
    s
}

// ── DepGraph tab ────────────────────────────────────────────────────────────

/// Pick the snapshot to draw: the explicitly latest one, else the
/// highest-`timestamp` snapshot in the map.
fn latest_snapshot(tl: &Timeline) -> Option<&DepGraphSnapshot> {
    tl.latest_snapshot
        .as_ref()
        .or_else(|| tl.snapshots.values().max_by_key(|s| s.timestamp))
}

/// **DepGraph tab → Mermaid `graph LR`.** The cross-repo dependency snapshot:
/// one node per repo, one edge `from -.-> to` labelled with the crates that
/// justify it (`via`). Mirrors the woven-threads painting. Returns an italic
/// placeholder when no snapshot was captured.
pub fn depgraph_mermaid(tl: &Timeline) -> String {
    let Some(snap) = latest_snapshot(tl) else {
        return "_no dependency-graph snapshot captured yet_\n".to_string();
    };
    let mut nodes: BTreeSet<&str> = BTreeSet::new();
    for e in &snap.edges {
        nodes.insert(e.from.as_str());
        nodes.insert(e.to.as_str());
    }
    let mut s = String::from("```mermaid\ngraph LR\n");
    for n in &nodes {
        let _ = writeln!(s, "  {}[\"{}\"]", sanitize(n), n);
    }
    for e in &snap.edges {
        let via: Vec<&str> = e.via.iter().map(String::as_str).collect();
        if via.is_empty() {
            let _ = writeln!(s, "  {} -.-> {}", sanitize(&e.from), sanitize(&e.to));
        } else {
            let _ = writeln!(
                s,
                "  {} -.->|{}| {}",
                sanitize(&e.from),
                via.join(", "),
                sanitize(&e.to),
            );
        }
    }
    s.push_str("```\n");
    s
}

/// **DepGraph tab → edge list.** The same cross-repo snapshot as a flat,
/// Mermaid-free Markdown list (`from → to (via crateA, crateB)`) for hosts that
/// don't render Mermaid. Sorted for deterministic output.
pub fn snapshot_edge_list(tl: &Timeline) -> String {
    let Some(snap) = latest_snapshot(tl) else {
        return "_no dependency-graph snapshot captured yet_\n".to_string();
    };
    if snap.edges.is_empty() {
        return "_no cross-repo dependency edges in the latest snapshot_\n".to_string();
    }
    let mut lines: Vec<String> = snap
        .edges
        .iter()
        .map(|e| {
            let via: Vec<&str> = e.via.iter().map(String::as_str).collect();
            if via.is_empty() {
                format!("- `{}` → `{}`", e.from, e.to)
            } else {
                format!("- `{}` → `{}` (via {})", e.from, e.to, via.join(", "))
            }
        })
        .collect();
    lines.sort();
    let mut s = lines.join("\n");
    s.push('\n');
    s
}

// ── Gates tab ───────────────────────────────────────────────────────────────

/// **Gates tab → verdict matrix.** Rows = recorded releases (chronological),
/// columns = repos, cells = the gate verdict (`✓` succeeded, `✗` failed,
/// otherwise the raw status). The tabular view of which release passed the gate
/// for which repo.
pub fn gate_matrix_table(tl: &Timeline) -> String {
    if !tl.has_releases() {
        return "_no releases recorded yet_\n".to_string();
    }
    // Column order = lane order (already repo-sorted in the model).
    let repos: Vec<&Lane> = tl.lanes.iter().filter(|l| !l.nodes.is_empty()).collect();
    if repos.is_empty() {
        return "_no gated releases recorded yet_\n".to_string();
    }
    let mut header = String::from("| Release |");
    let mut divider = String::from("|---------|");
    for l in &repos {
        let _ = write!(header, " {} |", cell(&l.repo));
        divider.push_str(":--:|");
    }
    let mut s = format!("{header}\n{divider}\n");

    for rid in &tl.release_order {
        // Find any node for this release to label the row by date.
        let label = repos
            .iter()
            .flat_map(|l| l.nodes.iter())
            .find(|n| &n.release_id == rid)
            .map(|n| n.timestamp.format("%Y-%m-%d %H:%M").to_string())
            .unwrap_or_else(|| rid.to_string());
        let mut row = format!("| {} |", cell(&label));
        for l in &repos {
            let mark = l
                .nodes
                .iter()
                .find(|n| &n.release_id == rid)
                .map(|n| gate_mark(&n.gate_status))
                .unwrap_or("·".to_string());
            let _ = write!(row, " {mark} |");
        }
        let _ = writeln!(s, "{row}");
    }
    s
}

fn gate_mark(status: &str) -> String {
    if status.starts_with("succeeded") {
        "".to_string()
    } else if status.starts_with("failed") {
        "".to_string()
    } else {
        cell(status)
    }
}

// ── Funnel tab ──────────────────────────────────────────────────────────────

/// **Funnel tab → published-versions table.** One row per (repo, release) that
/// published at least one crate, listing the crate@version it cut. The
/// release-output side of the funnel.
pub fn release_versions_table(tl: &Timeline) -> String {
    let mut rows: Vec<(String, String, String)> = Vec::new(); // (date, repo, versions)
    for lane in &tl.lanes {
        for n in &lane.nodes {
            if n.published_versions.is_empty() {
                continue;
            }
            rows.push((
                n.timestamp.format("%Y-%m-%d").to_string(),
                lane.repo.clone(),
                node_version(&n.published_versions),
            ));
        }
    }
    if rows.is_empty() {
        return "_no published versions recorded yet_\n".to_string();
    }
    rows.sort();
    let mut s = String::from("| Date | Repo | Published |\n");
    s.push_str("|------|------|-----------|\n");
    for (date, repo, ver) in rows {
        let _ = writeln!(s, "| {} | {} | {} |", date, cell(&repo), cell(&ver));
    }
    s
}

// ── Bench / TimeTravel tabs ─────────────────────────────────────────────────

/// **Bench tab → per-repo history table.** For each repo with bench points, the
/// N newest runs (newest first) of its primary metric — the textual sparkline.
/// `limit` caps rows per repo (`None` → all).
pub fn bench_history_table(tl: &Timeline, limit: Option<usize>) -> String {
    let mut histories: Vec<&BenchHistory> =
        tl.bench_history.values().filter(|h| !h.points.is_empty()).collect();
    histories.sort_by(|a, b| a.repo.cmp(&b.repo));
    if histories.is_empty() {
        return "_no benchmark history recorded yet_\n".to_string();
    }
    let mut s = String::from("| Repo | Date | Version | Metric | Value | Machine |\n");
    s.push_str("|------|------|---------|--------|------:|---------|\n");
    for h in histories {
        let mut pts: Vec<_> = h.points.iter().collect();
        pts.sort_by_key(|p| std::cmp::Reverse(p.timestamp)); // newest first
        if let Some(n) = limit {
            pts.truncate(n);
        }
        for p in pts {
            let _ = writeln!(
                s,
                "| {} | {} | {} | {} | {} | {} |",
                cell(&h.repo),
                p.timestamp.format("%Y-%m-%d"),
                cell(&p.version),
                cell(&p.primary_metric_name),
                fmt_num(p.primary_metric_value),
                cell(&p.machine),
            );
        }
    }
    s
}

/// **TimeTravel tab → latest-bench comparison table.** One row per repo, its
/// most recent run's primary metric — the cross-repo "where does each stand
/// now" view that the TimeTravel reel scrubs through.
pub fn bench_compare_table(tl: &Timeline) -> String {
    let mut rows: Vec<(String, String, f64, String, String)> = Vec::new();
    for (repo, h) in &tl.bench_history {
        if let Some(p) = h.points.iter().max_by_key(|p| p.timestamp) {
            rows.push((
                repo.clone(),
                p.primary_metric_name.clone(),
                p.primary_metric_value,
                p.version.clone(),
                p.timestamp.format("%Y-%m-%d").to_string(),
            ));
        }
    }
    if rows.is_empty() {
        return "_no benchmark history recorded yet_\n".to_string();
    }
    rows.sort_by(|a, b| a.0.cmp(&b.0));
    let mut s = String::from("| Repo | Latest metric | Value | Version | Date |\n");
    s.push_str("|------|---------------|------:|---------|------|\n");
    for (repo, metric, val, ver, date) in rows {
        let _ = writeln!(
            s,
            "| {} | {} | {} | {} | {} |",
            cell(&repo),
            cell(&metric),
            fmt_num(val),
            cell(&ver),
            date,
        );
    }
    s
}

/// Compact numeric formatting: integers without a decimal point and with
/// thousands separators, fractions to 3 sig figs.
fn fmt_num(v: f64) -> String {
    if v.fract() == 0.0 && v.abs() < 1e15 {
        let i = v as i64;
        let s = i.abs().to_string();
        let mut out = String::new();
        for (idx, ch) in s.chars().enumerate() {
            if idx > 0 && (s.len() - idx).is_multiple_of(3) {
                out.push(',');
            }
            out.push(ch);
        }
        if i < 0 { format!("-{out}") } else { out }
    } else if v.abs() >= 1000.0 {
        format!("{v:.0}")
    } else {
        format!("{v:.3}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::warehouse::dep_graph::CrossRepoEdge;
    use chrono::{TimeZone, Utc};
    use std::collections::BTreeMap;
    use uuid::Uuid;

    fn sample_timeline() -> Timeline {
        let sid = Uuid::from_u128(1);
        let rid = Uuid::from_u128(2);
        let ts = Utc.with_ymd_and_hms(2026, 6, 10, 12, 0, 0).unwrap();
        let snap = DepGraphSnapshot {
            snapshot_id: sid,
            workspace_name: "skade".into(),
            timestamp: ts,
            edges: vec![CrossRepoEdge {
                from: "skade".into(),
                to: "skade-katalog".into(),
                via: BTreeSet::from(["skade-katalog".to_string()]),
            }],
        };
        let mut snapshots = BTreeMap::new();
        snapshots.insert(sid, snap.clone());
        let mut release_snapshot = BTreeMap::new();
        release_snapshot.insert(rid, sid);

        let node = super::super::model::LaneNode {
            release_id: rid,
            timestamp: ts,
            sha: "deadbeefcafef00d".into(),
            branch: "main".into(),
            dirty: false,
            gate_status: "succeeded".into(),
            tests_passed: 9,
            tests_failed: 0,
            published_versions: vec![("skade".into(), "0.1.4".into())],
        };
        let mut bench_history = BTreeMap::new();
        bench_history.insert(
            "skade".to_string(),
            BenchHistory {
                repo: "skade".into(),
                points: vec![super::super::model::BenchPoint {
                    timestamp: ts,
                    primary_metric_name: "skade_table_exists_ops_sec".into(),
                    primary_metric_value: 2_000_000.0,
                    metrics: vec![("skade_table_exists.ops_sec".into(), 2_000_000.0)],
                    version: "0.1.4".into(),
                    machine: "oden".into(),
                }],
            },
        );

        Timeline {
            workspace_name: "skade".into(),
            lanes: vec![Lane { repo: "skade".into(), nodes: vec![node] }],
            release_order: vec![rid],
            release_snapshot,
            snapshots,
            latest_snapshot: Some(snap),
            bench_history,
        }
    }

    #[test]
    fn timeline_mermaid_has_section_and_event() {
        let tl = sample_timeline();
        let out = timeline_mermaid(&tl);
        assert!(out.starts_with("```mermaid\ntimeline\n"), "{out}");
        assert!(out.contains("section skade"), "{out}");
        assert!(out.contains("deadbee"), "short sha: {out}");
        assert!(out.contains("skade v0.1.4"), "version: {out}");
        assert!(out.trim_end().ends_with("```"));
    }

    #[test]
    fn depgraph_mermaid_labels_edge_via() {
        let out = depgraph_mermaid(&sample_timeline());
        assert!(out.contains("graph LR"), "{out}");
        assert!(out.contains("skade_katalog"), "{out}");
        assert!(out.contains("-.->|skade-katalog|"), "edge label: {out}");
    }

    #[test]
    fn snapshot_edge_list_is_sorted_markdown() {
        let out = snapshot_edge_list(&sample_timeline());
        assert!(out.contains("- `skade` → `skade-katalog` (via skade-katalog)"), "{out}");
    }

    #[test]
    fn gate_matrix_marks_success() {
        let out = gate_matrix_table(&sample_timeline());
        assert!(out.contains("| Release |"), "{out}");
        assert!(out.contains("skade"), "{out}");
        assert!(out.contains(''), "succeeded → check: {out}");
    }

    #[test]
    fn release_versions_lists_published() {
        let out = release_versions_table(&sample_timeline());
        assert!(out.contains("skade v0.1.4"), "{out}");
        assert!(out.contains("2026-06-10"), "{out}");
    }

    #[test]
    fn bench_history_table_newest_first_with_thousands() {
        let out = bench_history_table(&sample_timeline(), Some(20));
        assert!(out.contains("skade_table_exists_ops_sec"), "{out}");
        assert!(out.contains("2,000,000"), "thousands sep: {out}");
    }

    #[test]
    fn bench_compare_table_one_row_per_repo() {
        let out = bench_compare_table(&sample_timeline());
        assert!(out.contains("| skade |"), "{out}");
        assert!(out.contains("2,000,000"), "{out}");
    }

    #[test]
    fn lane_summary_shows_latest() {
        let out = lane_summary_table(&sample_timeline());
        assert!(out.contains("| skade |"), "{out}");
        assert!(out.contains("deadbee"), "{out}");
        assert!(out.contains("succeeded"), "{out}");
    }

    #[test]
    fn empty_timeline_placeholders() {
        let tl = Timeline {
            workspace_name: "empty".into(),
            lanes: vec![],
            release_order: vec![],
            release_snapshot: BTreeMap::new(),
            snapshots: BTreeMap::new(),
            latest_snapshot: None,
            bench_history: BTreeMap::new(),
        };
        assert!(timeline_mermaid(&tl).contains("no releases"));
        assert!(depgraph_mermaid(&tl).contains("no dependency-graph snapshot"));
        assert!(bench_history_table(&tl, None).contains("no benchmark history"));
        assert!(gate_matrix_table(&tl).contains("no releases"));
    }
}