roteiro 1.5.0

Roteiro: a provenance-tagged knowledge graph for your codebase — structure, intent, and context in one queryable store
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
//! Cross-repo **config override matrix + drift view** (ADR-0009 step 7, "views").
//!
//! The workspace overview the prototype validated: a grid of the hub's config
//! keys against each spoke repo, showing which spoke overrides which key (and to
//! what), plus a **drift** list of spoke keys the hub doesn't define. Built from
//! the same inferred matches `roteiro links --infer` produces, then rendered as a
//! self-contained HTML page (`--html`), a text table, or JSON.
//!
//! Pure data + rendering: the caller feeds in the already-matched inputs (each
//! carrying its own [`Provenance`]), so this module has no store/workspace
//! dependencies and is fully unit-testable.

use std::collections::BTreeMap;

use rto_graph::Provenance;

/// One matched override fed into the matrix.
pub struct MatchInput {
    /// The hub config key this override maps to.
    pub hub_key: String,
    /// The source file the hub key was read from — the `<file>` component of the
    /// hub `config_key` node's `cfgkey:<file>#<dotted>` id. Carried onto the [`Row`]
    /// so a client (the explorer's "hide tooling config" toggle) and the CLI can
    /// classify the row as app vs tooling config. Empty when the source is unknown.
    pub file: String,
    /// The spoke's own key (its naming convention).
    pub spoke_key: String,
    /// The spoke's value for it.
    pub spoke_value: String,
    /// Match confidence in `0.0..=1.0` (meaningful only for inferred links; an
    /// authored link carries no score, so callers pass `0.0`).
    pub confidence: f64,
    /// How this override link was produced — [`Provenance::Authored`] (a declared
    /// `[[links]]`) or [`Provenance::Inferred`] (a confidence-scored match). The
    /// real per-cell provenance, carried onto the [`Cell`].
    pub provenance: Provenance,
}

/// One spoke's contribution to the matrix.
pub struct SpokeInput {
    /// The spoke project (repo dir name).
    pub name: String,
    /// Its matched overrides against the hub.
    pub matches: Vec<MatchInput>,
    /// Its orphan `(key, value)`s — no hub counterpart (the drift candidates).
    pub orphans: Vec<(String, String)>,
}

/// One spoke's overriding value for a hub key.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Cell {
    /// The spoke's value.
    pub value: String,
    /// The spoke's key (may differ in convention from the hub's).
    pub spoke_key: String,
    /// Match confidence.
    pub confidence: f64,
    /// How the override link was produced (authored vs inferred). The real
    /// per-cell provenance the UI colours by (gold authored / slate inferred),
    /// replacing the old confidence≥1.0 heuristic.
    pub provenance: Provenance,
    /// The spoke value differs from the hub's default — a *real* override, not a
    /// redundant restatement. The signal a reader scans for.
    pub differs: bool,
}

/// One hub key's row: its default value and each spoke's override of it.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Row {
    /// The hub config key.
    pub hub_key: String,
    /// The source file the hub key was read from (the `<file>` in the hub
    /// `config_key` node's `cfgkey:<file>#<dotted>` id) — the classifier input for
    /// the "hide tooling config" filter (see [`MatchInput::file`]). Additive and
    /// backward-compatible: older clients simply ignore it. Empty when unknown.
    pub file: String,
    /// The hub's own value (the default the spokes override).
    pub hub_value: String,
    /// Overriding cell per spoke name (only spokes that override this key).
    pub cells: BTreeMap<String, Cell>,
}

/// A spoke key with no hub counterpart — the drift candidate.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Drift {
    /// The spoke project.
    pub spoke: String,
    /// The orphan key.
    pub key: String,
    /// Its value.
    pub value: String,
}

/// The assembled cross-repo override matrix.
#[derive(Debug, Clone, serde::Serialize)]
pub struct OverrideMatrix {
    /// The hub project (source of truth).
    pub hub: String,
    /// Spoke column order (only spokes that override at least one hub key).
    pub spokes: Vec<String>,
    /// One row per overridden hub key, sorted by key.
    pub rows: Vec<Row>,
    /// Orphan spoke keys (drift), sorted by `(spoke, key)`.
    pub drift: Vec<Drift>,
}

/// Assemble the matrix from each spoke's matches and orphans. `hub_values` maps a
/// hub key to its value (to flag which overrides actually *differ*). Deterministic:
/// rows sorted by hub key, columns and drift sorted by name.
#[must_use]
pub fn build(
    hub: &str,
    hub_values: &BTreeMap<String, String>,
    spokes: Vec<SpokeInput>,
) -> OverrideMatrix {
    let mut rows: BTreeMap<String, Row> = BTreeMap::new();
    let mut columns: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    let mut drift: Vec<Drift> = Vec::new();
    // Hub keys whose matches disagreed on a source file. A `Row` is keyed by the
    // dotted `hub_key` alone, but the same dotted key can exist in more than one hub
    // file (a `config_key` node is keyed by `cfgkey:<file>#<dotted>`). If two matches
    // resolve the same `hub_key` to *different* non-empty files, the row's file is
    // ambiguous — record that so it can never be re-adopted from a later match, and
    // leave `row.file` empty (so the opt-in tooling filter treats it as app config
    // rather than hiding it on an arbitrary file).
    let mut ambiguous_file: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();

    for spoke in spokes {
        for m in spoke.matches {
            let hub_value = hub_values.get(&m.hub_key).cloned().unwrap_or_default();
            let differs = hub_value != m.spoke_value;
            let row = rows.entry(m.hub_key.clone()).or_insert_with(|| Row {
                hub_key: m.hub_key.clone(),
                file: String::new(),
                hub_value: hub_value.clone(),
                cells: BTreeMap::new(),
            });
            // Reconcile the row's source file across all matches for this hub key:
            // adopt the first non-empty file, but clear it (permanently, via
            // `ambiguous_file`) the moment a later match reports a different one.
            if !m.file.is_empty() && !ambiguous_file.contains(&m.hub_key) {
                if row.file.is_empty() {
                    row.file.clone_from(&m.file);
                } else if row.file != m.file {
                    row.file.clear();
                    ambiguous_file.insert(m.hub_key.clone());
                }
            }
            let cell = Cell {
                value: m.spoke_value,
                spoke_key: m.spoke_key,
                confidence: m.confidence,
                provenance: m.provenance,
                differs,
            };
            // A spoke may set the same hub key in more than one file. Keep a *real*
            // override visible: never let a redundant restatement (`differs = false`)
            // overwrite a differing cell already recorded for this spoke+key.
            match row.cells.entry(spoke.name.clone()) {
                std::collections::btree_map::Entry::Vacant(v) => {
                    v.insert(cell);
                }
                std::collections::btree_map::Entry::Occupied(mut o) => {
                    if cell.differs && !o.get().differs {
                        o.insert(cell);
                    }
                }
            }
            columns.insert(spoke.name.clone());
        }
        for (key, value) in spoke.orphans {
            drift.push(Drift {
                spoke: spoke.name.clone(),
                key,
                value,
            });
        }
    }
    drift.sort_by(|a, b| (&a.spoke, &a.key).cmp(&(&b.spoke, &b.key)));

    OverrideMatrix {
        hub: hub.to_owned(),
        spokes: columns.into_iter().collect(),
        rows: rows.into_values().collect(),
        drift,
    }
}

/// Whether the matrix has nothing to show (no overrides and no drift).
#[must_use]
pub fn is_empty(m: &OverrideMatrix) -> bool {
    m.rows.is_empty() && m.drift.is_empty()
}

/// Render the matrix as a plain-text table for the terminal.
#[must_use]
pub fn render_text(m: &OverrideMatrix) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    let _ = writeln!(
        out,
        "cross-repo config overrides (hub: {}, {} spoke(s))",
        m.hub,
        m.spokes.len()
    );
    for row in &m.rows {
        let _ = writeln!(out, "\n  {} = {}", row.hub_key, row.hub_value);
        for spoke in &m.spokes {
            if let Some(cell) = row.cells.get(spoke) {
                let flag = if cell.differs { "" } else { "=" };
                let _ = writeln!(
                    out,
                    "    {flag} {spoke}: {} ({:.2})",
                    cell.value, cell.confidence
                );
            }
        }
    }
    if !m.drift.is_empty() {
        let _ = writeln!(out, "\n  drift — {} orphan key(s):", m.drift.len());
        for d in &m.drift {
            let _ = writeln!(out, "    {}: {} = {}", d.spoke, d.key, d.value);
        }
    }
    out
}

/// Render the matrix as a **self-contained** HTML page (inline CSS, no external
/// assets) — the `render web-graph` output: open it straight in a browser.
#[must_use]
pub fn render_html(m: &OverrideMatrix) -> String {
    use std::fmt::Write as _;
    let mut thead = String::from("<th scope=\"col\">config key</th><th scope=\"col\">hub</th>");
    for s in &m.spokes {
        let _ = write!(thead, "<th scope=\"col\">{}</th>", esc(s));
    }

    let mut tbody = String::new();
    for row in &m.rows {
        let _ = write!(
            tbody,
            "<tr><th scope=\"row\"><code>{}</code></th><td class=\"hub\"><code>{}</code></td>",
            esc(&row.hub_key),
            esc(&row.hub_value)
        );
        for spoke in &m.spokes {
            match row.cells.get(spoke) {
                Some(cell) => {
                    let cls = if cell.differs {
                        "cell over"
                    } else {
                        "cell same"
                    };
                    let _ = write!(
                        tbody,
                        "<td class=\"{cls}\"><code>{}</code>\
                         <span class=\"conf\" title=\"confidence\">{:.2}</span></td>",
                        esc(&cell.value),
                        cell.confidence
                    );
                }
                None => tbody.push_str("<td class=\"cell none\">·</td>"),
            }
        }
        tbody.push_str("</tr>");
    }

    let drift = if m.drift.is_empty() {
        String::new()
    } else {
        let mut rows = String::new();
        for d in &m.drift {
            let _ = write!(
                rows,
                "<tr><td>{}</td><td><code>{}</code></td><td><code>{}</code></td></tr>",
                esc(&d.spoke),
                esc(&d.key),
                esc(&d.value)
            );
        }
        format!(
            "<h2>Drift — {} orphan key(s)</h2>\
             <p class=\"muted\">Spoke keys with no hub counterpart: the app doesn't \
             define these, so a rename or removal in the hub can't warn you.</p>\
             <table class=\"drift\"><thead><tr><th scope=\"col\">spoke</th>\
             <th scope=\"col\">key</th><th scope=\"col\">value</th></tr></thead>\
             <tbody>{rows}</tbody></table>",
            m.drift.len()
        )
    };

    let body = if is_empty(m) {
        "<p class=\"muted\">No cross-repo config overrides or drift found.</p>".to_owned()
    } else {
        format!(
            "<table class=\"matrix\"><thead><tr>{thead}</tr></thead><tbody>{tbody}</tbody></table>\
             <p class=\"legend\"><span class=\"swatch over\"></span> overrides the hub value \
             &nbsp; <span class=\"swatch same\"></span> matches it (redundant) \
             &nbsp; <span class=\"swatch none\"></span> not set</p>{drift}"
        )
    };

    format!(
        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
         <title>Cross-repo config overrides — {hub}</title><style>{CSS}</style></head><body>\
         <main><h1>Cross-repo config overrides</h1>\
         <p class=\"muted\">Hub <strong>{hub}</strong> · {nspokes} spoke(s) · ADR-0009</p>\
         {body}</main></body></html>",
        hub = esc(&m.hub),
        nspokes = m.spokes.len(),
    )
}

/// Minimal, theme-aware, self-contained stylesheet for the overview page.
const CSS: &str = "\
:root{--bg:#fff;--fg:#1a1a2e;--muted:#6b7280;--line:#e5e7eb;--hub:#f3f4f6;\
--over:#fef3c7;--over-fg:#92400e;--same:#ecfdf5;--same-fg:#065f46;--accent:#4f46e5}\
@media(prefers-color-scheme:dark){:root{--bg:#0f1117;--fg:#e5e7eb;--muted:#9ca3af;\
--line:#262b36;--hub:#1a1d27;--over:#3b2f10;--over-fg:#fcd34d;--same:#0f2a1f;\
--same-fg:#6ee7b7;--accent:#a5b4fc}}\
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);\
font:15px/1.5 ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif}\
main{max-width:1100px;margin:0 auto;padding:2rem 1.25rem}\
h1{font-size:1.5rem;margin:0 0 .25rem}h2{font-size:1.15rem;margin:2rem 0 .5rem}\
.muted{color:var(--muted);margin:.25rem 0 1.5rem}\
code{font:13px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}\
table{border-collapse:collapse;width:100%;overflow-x:auto;display:block}\
@media(min-width:720px){table{display:table}}\
th,td{border:1px solid var(--line);padding:.4rem .6rem;text-align:left;vertical-align:top}\
thead th{position:sticky;top:0;background:var(--bg);font-size:.8rem;\
text-transform:uppercase;letter-spacing:.03em;color:var(--muted)}\
tbody th[scope=row]{background:var(--hub);white-space:nowrap}\
td.hub{background:var(--hub);color:var(--muted)}\
td.cell{white-space:nowrap}td.over{background:var(--over);color:var(--over-fg)}\
td.same{background:var(--same);color:var(--same-fg)}td.none{color:var(--muted);text-align:center}\
.conf{display:inline-block;margin-left:.4rem;font-size:.7rem;opacity:.7;\
font-variant-numeric:tabular-nums}\
.legend{color:var(--muted);font-size:.85rem;margin:1rem 0}\
.swatch{display:inline-block;width:.8rem;height:.8rem;border-radius:3px;\
vertical-align:-1px;border:1px solid var(--line)}\
.swatch.over{background:var(--over)}.swatch.same{background:var(--same)}\
.swatch.none{background:var(--bg)}\
table.drift td:first-child{white-space:nowrap;color:var(--muted)}";

/// Escape text for HTML body or attribute content (both quote styles), so the
/// helper stays safe if reused inside single-quoted attributes.
fn esc(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn matrix() -> OverrideMatrix {
        let hub_values = BTreeMap::from([
            ("serve.addr".to_owned(), "127.0.0.1:8017".to_owned()),
            ("serve.tools".to_owned(), "true".to_owned()),
        ]);
        let spokes = vec![SpokeInput {
            name: "deploy".to_owned(),
            matches: vec![
                MatchInput {
                    hub_key: "serve.addr".to_owned(),
                    file: "config.toml".to_owned(),
                    spoke_key: "SERVE_ADDR".to_owned(),
                    spoke_value: "0.0.0.0:8443".to_owned(), // differs → override
                    confidence: 0.9,
                    provenance: Provenance::Inferred,
                },
                MatchInput {
                    hub_key: "serve.tools".to_owned(),
                    file: "config.toml".to_owned(),
                    spoke_key: "SERVE_TOOLS".to_owned(),
                    spoke_value: "true".to_owned(), // same → redundant
                    confidence: 0.98,
                    provenance: Provenance::Inferred,
                },
            ],
            orphans: vec![("MAX_CONNECTIONS".to_owned(), "512".to_owned())],
        }];
        build("app", &hub_values, spokes)
    }

    #[test]
    fn build_pivots_matches_into_rows_and_flags_real_overrides() {
        let m = matrix();
        assert_eq!(m.hub, "app");
        assert_eq!(m.spokes, vec!["deploy".to_owned()]);
        assert_eq!(m.rows.len(), 2);
        let addr = m.rows.iter().find(|r| r.hub_key == "serve.addr").unwrap();
        assert!(
            addr.cells["deploy"].differs,
            "different value is an override"
        );
        let tools = m.rows.iter().find(|r| r.hub_key == "serve.tools").unwrap();
        assert!(!tools.cells["deploy"].differs, "equal value is redundant");
        assert_eq!(m.drift.len(), 1);
        assert_eq!(m.drift[0].key, "MAX_CONNECTIONS");
    }

    #[test]
    fn a_redundant_restatement_never_hides_a_real_override() {
        // The same spoke sets serve.addr in two files — one matching the hub
        // (redundant), one differing (a real override). The override must win
        // regardless of the order they're fed in.
        let hub_values = BTreeMap::from([("serve.addr".to_owned(), "127.0.0.1:8017".to_owned())]);
        let same = || MatchInput {
            hub_key: "serve.addr".to_owned(),
            file: "config.toml".to_owned(),
            spoke_key: "serve.addr".to_owned(),
            spoke_value: "127.0.0.1:8017".to_owned(),
            confidence: 0.98,
            provenance: Provenance::Inferred,
        };
        let over = || MatchInput {
            hub_key: "serve.addr".to_owned(),
            file: "config.toml".to_owned(),
            spoke_key: "SERVE_ADDR".to_owned(),
            spoke_value: "0.0.0.0:8443".to_owned(),
            confidence: 0.9,
            provenance: Provenance::Inferred,
        };
        for matches in [vec![same(), over()], vec![over(), same()]] {
            let m = build(
                "app",
                &hub_values,
                vec![SpokeInput {
                    name: "deploy".to_owned(),
                    matches,
                    orphans: vec![],
                }],
            );
            let cell = &m.rows[0].cells["deploy"];
            assert!(
                cell.differs,
                "override must survive a redundant restatement"
            );
            assert_eq!(cell.value, "0.0.0.0:8443");
        }
    }

    #[test]
    fn build_carries_real_per_cell_provenance() {
        // An authored override and an inferred one, side by side: each cell must
        // carry its own provenance verbatim — not a confidence-derived guess.
        let hub_values = BTreeMap::from([
            ("serve.addr".to_owned(), "127.0.0.1:8017".to_owned()),
            ("serve.tools".to_owned(), "true".to_owned()),
        ]);
        let m = build(
            "app",
            &hub_values,
            vec![SpokeInput {
                name: "deploy".to_owned(),
                matches: vec![
                    MatchInput {
                        hub_key: "serve.addr".to_owned(),
                        file: "config.toml".to_owned(),
                        spoke_key: "SERVE_ADDR".to_owned(),
                        spoke_value: "0.0.0.0:8443".to_owned(),
                        confidence: 0.0, // authored links carry no score
                        provenance: Provenance::Authored,
                    },
                    MatchInput {
                        hub_key: "serve.tools".to_owned(),
                        file: "config.toml".to_owned(),
                        spoke_key: "SERVE_TOOLS".to_owned(),
                        spoke_value: "false".to_owned(),
                        confidence: 0.9,
                        provenance: Provenance::Inferred,
                    },
                ],
                orphans: vec![],
            }],
        );
        let addr = m.rows.iter().find(|r| r.hub_key == "serve.addr").unwrap();
        assert_eq!(addr.cells["deploy"].provenance, Provenance::Authored);
        let tools = m.rows.iter().find(|r| r.hub_key == "serve.tools").unwrap();
        assert_eq!(tools.cells["deploy"].provenance, Provenance::Inferred);
        // It serializes to the stable lowercase token the UI colours by.
        let json = serde_json::to_value(&m).unwrap();
        let addr_cell = &json["rows"]
            .as_array()
            .unwrap()
            .iter()
            .find(|r| r["hub_key"] == "serve.addr")
            .unwrap()["cells"]["deploy"];
        assert_eq!(addr_cell["provenance"], "authored");
    }

    #[test]
    fn build_carries_the_hub_source_file_onto_each_row() {
        // Each row records the file its hub key was read from, so a client (the
        // explorer's "hide tooling config" toggle) and the CLI can classify the row
        // as app vs tooling config. A `Cargo.toml`-sourced key rides through the
        // build unchanged (the filter is opt-in — build never drops it) and its file
        // serialises verbatim, ready for `is_tooling_config_path`.
        let hub_values = BTreeMap::from([
            ("serve.addr".to_owned(), "127.0.0.1:8017".to_owned()),
            ("package.name".to_owned(), "roteiro".to_owned()),
        ]);
        let m = build(
            "app",
            &hub_values,
            vec![SpokeInput {
                name: "deploy".to_owned(),
                matches: vec![
                    MatchInput {
                        hub_key: "serve.addr".to_owned(),
                        file: "config.toml".to_owned(),
                        spoke_key: "SERVE_ADDR".to_owned(),
                        spoke_value: "0.0.0.0:8443".to_owned(),
                        confidence: 0.9,
                        provenance: Provenance::Inferred,
                    },
                    MatchInput {
                        hub_key: "package.name".to_owned(),
                        file: "Cargo.toml".to_owned(),
                        spoke_key: "PACKAGE_NAME".to_owned(),
                        spoke_value: "deploy".to_owned(),
                        confidence: 0.9,
                        provenance: Provenance::Inferred,
                    },
                ],
                orphans: vec![],
            }],
        );
        let app = m.rows.iter().find(|r| r.hub_key == "serve.addr").unwrap();
        assert_eq!(app.file, "config.toml");
        let tooling = m.rows.iter().find(|r| r.hub_key == "package.name").unwrap();
        assert_eq!(tooling.file, "Cargo.toml");
        // The per-row file serialises additively for the client/CLI to classify.
        let json = serde_json::to_value(&m).unwrap();
        let tooling_json = json["rows"]
            .as_array()
            .unwrap()
            .iter()
            .find(|r| r["hub_key"] == "package.name")
            .unwrap();
        assert_eq!(tooling_json["file"], "Cargo.toml");
    }

    #[test]
    fn a_hub_key_from_two_different_files_yields_an_ambiguous_empty_row_file() {
        // A `Row` is keyed by the dotted `hub_key` alone, but the same dotted key can
        // live in more than one hub file. If matches disagree on the source file, the
        // row's file is ambiguous: `build` must clear it (not keep an arbitrary
        // first-seen file), so the opt-in tooling filter treats the row as app config
        // and never hides it on a guess. Order-independent, and a re-stated file must
        // not resurrect the cleared value.
        let hub_values = BTreeMap::from([("shared.key".to_owned(), "v".to_owned())]);
        let m = |file: &str, spoke_key: &str| MatchInput {
            hub_key: "shared.key".to_owned(),
            file: file.to_owned(),
            spoke_key: spoke_key.to_owned(),
            spoke_value: "x".to_owned(),
            confidence: 0.9,
            provenance: Provenance::Inferred,
        };
        // Two spokes resolve the same hub key to different files; a third repeats the
        // first file — the row must stay ambiguous (empty) regardless.
        for matches in [
            vec![
                m("config.toml", "A"),
                m("Cargo.toml", "B"),
                m("config.toml", "C"),
            ],
            vec![m("Cargo.toml", "B"), m("config.toml", "A")],
        ] {
            let spokes = matches
                .into_iter()
                .enumerate()
                .map(|(i, mat)| SpokeInput {
                    name: format!("spoke{i}"),
                    matches: vec![mat],
                    orphans: vec![],
                })
                .collect();
            let built = build("app", &hub_values, spokes);
            let row = built
                .rows
                .iter()
                .find(|r| r.hub_key == "shared.key")
                .unwrap();
            assert_eq!(
                row.file, "",
                "conflicting hub-key files must leave the row file empty (unclassifiable), not an arbitrary pick"
            );
        }

        // Sanity: a hub key seen in ONE consistent file keeps that file — ambiguity
        // only clears on a genuine conflict, so tooling rows still classify.
        let consistent = build(
            "app",
            &hub_values,
            vec![
                SpokeInput {
                    name: "a".to_owned(),
                    matches: vec![m("Cargo.toml", "A")],
                    orphans: vec![],
                },
                SpokeInput {
                    name: "b".to_owned(),
                    matches: vec![m("Cargo.toml", "B")],
                    orphans: vec![],
                },
            ],
        );
        assert_eq!(consistent.rows[0].file, "Cargo.toml");
    }

    #[test]
    fn render_html_is_self_contained_and_escapes() {
        let m = matrix();
        let html = render_html(&m);
        assert!(html.starts_with("<!doctype html>"));
        assert!(html.contains("<style>"), "inline CSS, no external asset");
        assert!(!html.contains("href=\"style.css\""));
        assert!(html.contains("serve.addr") && html.contains("0.0.0.0:8443"));
        assert!(html.contains("MAX_CONNECTIONS"), "drift is shown");
        // The differing override is class `over`, the redundant one `same`.
        assert!(html.contains("cell over") && html.contains("cell same"));
    }

    #[test]
    fn render_html_escapes_injected_markup() {
        let hub_values = BTreeMap::from([("k".to_owned(), "<v>".to_owned())]);
        let m = build("app", &hub_values, vec![]);
        let html = render_html(&m);
        assert!(!html.contains("<v>"), "hub value must be escaped");
    }

    #[test]
    fn text_table_marks_overrides_and_lists_drift() {
        let t = render_text(&matrix());
        assert!(t.contains("serve.addr = 127.0.0.1:8017"));
        assert!(t.contains("≠ deploy: 0.0.0.0:8443"));
        assert!(t.contains("= deploy: true"));
        assert!(t.contains("drift") && t.contains("MAX_CONNECTIONS"));
    }
}