Skip to main content

rto_render/
obsidian.rs

1//! The Obsidian-vault renderer: each graph node becomes a markdown note whose
2//! edges are `[[wikilinks]]`, so the provenance-tagged graph is browsable in
3//! Obsidian's graph view. Notes carry frontmatter `tags` (`roteiro/kind/*`,
4//! `roteiro/lang/*`, `roteiro/status/*`) so the graph is colourable/filterable —
5//! edge provenance is shown per-link in the body — surface the node's text as the
6//! knowledge base, show an ADR's status, and (when the repository's web host is
7//! known) a clickable **Source** link to the file.
8//!
9//! That text is the node's captured `meta.content` (a doc comment, PDF or image
10//! text) *except* where the caller supplies a full `body` — which it does for
11//! prose documents, because `meta.content` is an embedding budget and a note
12//! rendered from it is the document capped at 1500 characters and collapsed onto
13//! one line. See [`note_body`].
14//!
15//! A generated `_Home` note is the overview: what was
16//! scanned, counts by kind, provenance breakdown, ADR statuses, intent-debt (with
17//! the files it is densest in), an inventory of secret-**named** config keys and
18//! their redaction state, and the most depended-on symbols by directed call
19//! fan-in.
20//! Built from the same [`Explanation`] the query surface returns, so the vault
21//! and the CLI agree.
22
23use std::fmt::Write as _;
24
25use rto_graph::Explanation;
26
27/// Filename of the generated overview note (sorts first in the file list).
28pub const HOME_NOTE: &str = "_Home.md";
29
30/// A rendered vault note: its filename (with `.md`) and markdown content.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct VaultNote {
33    /// Filename including the `.md` extension.
34    pub filename: String,
35    /// Markdown content.
36    pub content: String,
37}
38
39/// Map a node key to a filesystem- and wikilink-safe note stem that is **unique
40/// per key even after case folding**.
41///
42/// A name is a lowercased, readable *hint* slugged from the key, followed by an
43/// unconditional 64-bit FNV-1a hash of the whole, exact key written as 16 hex
44/// digits — `<hint>-<16 hex digits>`. Characters outside `[a-z0-9._-]` collapse
45/// to a single `-` in the hint; the hash carries everything the hint threw away.
46///
47/// **The hash is the unconditional part, not the hint.** A key of nothing but
48/// separators slugs to an empty hint, and the name is then the bare 16 hex
49/// digits — no hint, and no `-` to join it to. The two forms cannot be confused
50/// for one another, which is what makes the exception safe rather than a second
51/// naming rule: a hinted name is at least 18 characters and contains a `-`,
52/// and a bare one is exactly 16 and contains none. That is argued again at the
53/// branch itself, and asserted by
54/// `every_name_carries_the_hash_however_short_the_key`.
55///
56/// # Why the hash is unconditional (issue #574)
57///
58/// It used to be applied only when the slug overran the filename limit, and the
59/// slug alone was lossy twice over. Measured on this repository — 8,239 nodes
60/// rendering to 8,135 notes, 104 of them silently overwritten:
61///
62/// | mechanism | lost | where |
63/// | --- | --- | --- |
64/// | every character outside the safe set becomes `-` and runs collapse, so `…cytoscape.min.js#$a` and `…cytoscape.min.js#a` are one name | 9 | everywhere |
65/// | macOS and Windows fold filename case, so `…#A` and `…#a` are two *names* but one *file* | 95 | macOS, Windows |
66///
67/// The second mechanism is the trap. A lossless-but-case-sensitive encoding
68/// fixes the 9, verifies clean on Linux CI, and still loses 95 notes on a Mac.
69/// So the requirement is stated after folding:
70///
71/// ```text
72/// lower(note_name(k1)) == lower(note_name(k2))  implies  k1 == k2
73/// ```
74///
75/// This matters more than lossiness in a cache would, because the note names are
76/// the vault's **only** stable interface: `reset_vault_dir` deletes and rebuilds
77/// the whole directory on every render, so the one thing that survives a render
78/// is a user's own note *outside* the vault linking in by name (issue #442).
79///
80/// # The trade taken
81///
82/// Two decisions, and what each bought:
83///
84/// **The hint is lowercased rather than case-preserved.** Case-preserving would
85/// also satisfy the requirement — the hash differs for `#A` and `#a`, so the two
86/// names differ in their suffix and stay distinct under folding. It was rejected
87/// because lowercasing makes `note_name(k) == note_name(k).to_lowercase()` an
88/// invariant of the function, and *that* collapses the folded property into the
89/// literal one: there is then no way to write a version of this that is green on
90/// Linux and lossy on macOS, which is the defect shape this repository keeps
91/// finding. The cost is that `parseHTTPHeader` reads as `parsehttpheader`. That
92/// is affordable precisely because the hint is a hint — once a 17-character
93/// suffix is mandatory the name is not something anyone types from memory, so
94/// its job is to be recognisable in a file list, not to be transcribed.
95///
96/// **Readability was spent, deliberately.** Every name grows by 17 characters and
97/// hand-writing a link now needs Obsidian's autocomplete. The alternatives that
98/// keep names short — hashing only the keys observed to collide — make the *set*
99/// of collisions platform-dependent, so one key would get one filename on macOS
100/// and another on Linux and a synced vault would churn. A name that is uglier
101/// everywhere beats a name that is different per platform.
102///
103/// The mapping is not reversible (the hint is lossy and the hash is one-way), but
104/// it does not need to be: every note's frontmatter carries `key:` verbatim, so
105/// name → key is recoverable from the vault itself, which is the direction a
106/// reader actually needs.
107///
108/// # What "unique" rests on
109///
110/// Equal names imply equal hashes, not equal keys — this is a 64-bit hash, not a
111/// proof. Over this repository's 8,239 keys there is no collision, and the
112/// birthday bound at that size is about 2e-12. Should one ever occur it is
113/// *reported*, not silent: `NoteNames` in the render path claims every filename
114/// case-insensitively and warns on a repeat. What is proved outright is the
115/// folding half — the output is lowercase by construction, so case folding is the
116/// identity on it.
117#[must_use]
118pub fn note_name(key: &str) -> String {
119    // Keep the whole stem well under the 255-byte filename limit (leaving room
120    // for ".md"). The hint is ASCII, so byte length equals char count and slicing
121    // is safe.
122    const MAX: usize = 200;
123    // '-' plus the 16 hex digits of the hash.
124    const SUFFIX: usize = 17;
125    const HINT: usize = MAX - SUFFIX;
126
127    let mut hint = String::with_capacity(key.len());
128    let mut prev_dash = false;
129    for c in key.chars() {
130        if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
131            hint.push(c.to_ascii_lowercase());
132            prev_dash = false;
133        } else if !prev_dash {
134            hint.push('-');
135            prev_dash = true;
136        }
137    }
138    let hint = hint.trim_matches('-');
139    // Truncation is only ever cosmetic now: the hash, not the hint, is what keeps
140    // a 300-character grouped `use` distinct from its neighbour.
141    let hint = hint[..hint.len().min(HINT)].trim_end_matches('-');
142    let hash = fnv1a64(key.as_bytes());
143    if hint.is_empty() {
144        // A key of nothing but separators. Bare hex, and it cannot be confused
145        // with a hinted name: those are `<hint>-<16 hex>`, so at least 18
146        // characters, and this is exactly 16 with no `-` in it.
147        format!("{hash:016x}")
148    } else {
149        format!("{hint}-{hash:016x}")
150    }
151}
152
153/// FNV-1a (64-bit) — a dependency-free, deterministic hash carrying everything
154/// [`note_name`]'s hint discards. No cryptographic properties needed: nothing
155/// here defends against a chosen collision, only against an accidental one.
156///
157/// 64 bits rather than fewer because the cost of a collision is exactly the
158/// defect this suffix exists to fix — a note silently overwritten. At 8k keys a
159/// 32-bit hash collides about 0.8% of the time and a 48-bit one about 1e-5;
160/// 64 bits is 2e-12, and stays under 1e-10 for a workspace vault an order of
161/// magnitude larger.
162fn fnv1a64(bytes: &[u8]) -> u64 {
163    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
164    for &b in bytes {
165        hash ^= u64::from(b);
166        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
167    }
168    hash
169}
170
171/// Emit `value` as a YAML **double-quoted** scalar, `"`-delimited and escaped so
172/// it parses back to exactly `value`.
173///
174/// The one escaping rule for this module's frontmatter. It exists because the
175/// three hand-rolled variants it replaced disagreed with each other — `key:` and
176/// `project:` turned a `"` into an apostrophe, and `path:` escaped nothing — and
177/// two of the three could emit YAML that does not mean what it says:
178///
179/// | value | was emitted | parsed back as |
180/// | --- | --- | --- |
181/// | `foo\bar` | `"foo\bar"` | `foo<BS>ar` — `\b` is YAML's **backspace** escape |
182/// | `foo\dir` | `"foo\dir"` | *parse error* — `\d` is not a YAML escape |
183/// | `say"hi".rs` | `"say"hi".rs"` | *parse error* — the scalar ends at the `"` |
184///
185/// The first is the dangerous one: seven characters silently become six, and
186/// nothing anywhere reports it. The other two cost the reader every property on
187/// the note, because Obsidian parses this block as the note's properties and a
188/// block that does not parse yields no properties at all rather than an error.
189///
190/// All three inputs are legal path components on Linux and macOS. None occurs in
191/// this repository today, so this is a latent defect rather than an observed one.
192///
193/// Escapes, per YAML 1.2 §7.3.1: the two structural characters `\` and `"`, then
194/// anything a parser is not obliged to accept literally — C0 controls, `DEL`, the
195/// C1 range, and the three separators (`U+2028`, `U+2029`, `U+FEFF`) that some
196/// parsers treat as line breaks. Short escapes where YAML defines one, so the
197/// common cases stay readable, and `\uXXXX` otherwise.
198fn yaml_double_quoted(value: &str) -> String {
199    let mut out = String::with_capacity(value.len() + 2);
200    out.push('"');
201    for ch in value.chars() {
202        match ch {
203            '\\' => out.push_str(r"\\"),
204            '"' => out.push_str("\\\""),
205            '\n' => out.push_str(r"\n"),
206            '\r' => out.push_str(r"\r"),
207            '\t' => out.push_str(r"\t"),
208            '\u{0}' => out.push_str(r"\0"),
209            '\u{7}' => out.push_str(r"\a"),
210            '\u{8}' => out.push_str(r"\b"),
211            '\u{b}' => out.push_str(r"\v"),
212            '\u{c}' => out.push_str(r"\f"),
213            '\u{1b}' => out.push_str(r"\e"),
214            // Everything else a YAML parser may reject or fold: the rest of C0,
215            // DEL, the C1 range, and the separators that can read as line breaks.
216            c if (c < ' ')
217                || c == '\u{7f}'
218                || ('\u{80}'..='\u{9f}').contains(&c)
219                || matches!(c, '\u{2028}' | '\u{2029}' | '\u{feff}') =>
220            {
221                let _ = write!(out, "\\u{:04x}", c as u32);
222            }
223            c => out.push(c),
224        }
225    }
226    out.push('"');
227    out
228}
229
230/// Emit `value` in YAML **plain** (unquoted) style when that round-trips, and as
231/// [`yaml_double_quoted`] when it would not.
232///
233/// For the frontmatter fields that are written bare today — `kind`, `lang`,
234/// `status`. Those are constrained by *today's* producers (an ADR's status is
235/// validated against the house states; kinds and languages come from extraction),
236/// but `roteiro load` installs a caller-supplied graph artifact whose nodes carry
237/// whatever JSON they carry, so "the producer is careful" is not a property this
238/// renderer can rely on. A `status:` of `Accepted: superseded by 0012` emitted
239/// bare is a parse error, and `Accepted # pending` silently truncates to
240/// `Accepted`.
241///
242/// Escalating only when needed is what keeps the bytes of an existing vault
243/// unchanged — every `kind`, `lang` and `status` in this repository is plain-safe
244/// and stays bare. [`is_plain_safe`] is deliberately stricter than YAML's plain
245/// grammar for the same reason it is safe: a value it rejects is merely quoted.
246fn yaml_scalar(value: &str) -> String {
247    if is_plain_safe(value) {
248        value.to_owned()
249    } else {
250        yaml_double_quoted(value)
251    }
252}
253
254/// Whether `value` can be written as a bare YAML scalar and read back unchanged.
255///
256/// A conservative allowlist rather than YAML's actual plain-scalar grammar, which
257/// is subtle enough (indicator characters, `: ` and ` #` only in some positions,
258/// leading and trailing space, implicit typing) that implementing it is how the
259/// bug this replaces gets written a second time. Getting this wrong in the
260/// strict direction costs a pair of quotation marks; getting it wrong in the
261/// permissive direction costs the note's properties.
262///
263/// So: a leading ASCII letter, then letters, digits, `_`, `-`, `.` and `/` — which
264/// covers every kind, language and status this renderer emits — and never a word
265/// YAML resolves to a boolean or null. That last exclusion is not hypothetical:
266/// `no` is the ISO 639-1 code for Norwegian, and YAML 1.1 parsers read a bare `no`
267/// as `false`.
268fn is_plain_safe(value: &str) -> bool {
269    const NOT_STRINGS: [&str; 11] = [
270        "true", "false", "yes", "no", "on", "off", "null", "nil", "none", "y", "n",
271    ];
272    !value.is_empty()
273        && value.starts_with(|c: char| c.is_ascii_alphabetic())
274        && value
275            .chars()
276            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/'))
277        && !NOT_STRINGS.contains(&value.to_ascii_lowercase().as_str())
278}
279
280/// Which vault a note is being rendered into: a single project's, or one member
281/// of a **workspace** vault spanning several repositories.
282///
283/// This is the whole of the workspace-vault naming rule, in one place. Node keys
284/// are **repository-relative** (`file:README.md` names no repo), so every member
285/// of a workspace produces the same note name for its `README.md` and one would
286/// silently overwrite the rest. Qualifying the key with its project fixes that.
287///
288/// [`VaultScope::PROJECT`] (`project: None`) is not a degenerate case but the
289/// contract: it makes every name in this module reduce to exactly [`note_name`]
290/// of the bare key, with nothing qualified and no `project:` frontmatter.
291///
292/// That reduction is *still* the promise; what it no longer implies is stability
293/// against `main`. #570 could say "a single-project vault's names do not move",
294/// because the only thing moving them would have been workspace qualification.
295/// #574 moves them all, on purpose: the old names were not injective under
296/// filename case folding and the vault lost 104 notes to that. The promise here
297/// was always about **this axis** — turning workspace mode on must not rename a
298/// project's notes — and it holds unchanged. See [`note_name`] for the rename and
299/// what it bought.
300#[derive(Debug, Clone, Copy)]
301pub struct VaultScope<'a> {
302    /// The member project this note belongs to, qualifying its name as
303    /// `<project>::<key>` — the same form ADR-0009's cross-repo links already use.
304    /// `None` ⇒ a single-project vault, and names are unqualified exactly as
305    /// before.
306    pub project: Option<&'a str>,
307    /// The workspace's member project names. An external-ref placeholder whose
308    /// target names one of these is a cross-repo edge the vault can actually
309    /// follow, so it is rendered as a link straight to that member's note. Empty
310    /// for a single-project vault.
311    pub members: &'a std::collections::BTreeSet<String>,
312}
313
314/// The empty member set backing [`VaultScope::PROJECT`] — a single-project vault
315/// has no other members to resolve a cross-repo reference against.
316static NO_MEMBERS: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
317
318impl VaultScope<'_> {
319    /// A single-project vault: names are unqualified, and no cross-repo reference
320    /// resolves. Every name this produces is byte-identical to [`note_name`] of
321    /// the bare key — see the type's documentation for why that reduction is
322    /// load-bearing, and for what it does *not* promise.
323    pub const PROJECT: Self = Self {
324        project: None,
325        members: &NO_MEMBERS,
326    };
327}
328
329impl Default for VaultScope<'_> {
330    fn default() -> Self {
331        Self::PROJECT
332    }
333}
334
335impl VaultScope<'_> {
336    /// Whether an external-ref placeholder `key` is one this vault resolves for
337    /// itself — its target names a member, so every edge to it points at the real
338    /// note and the placeholder need not be rendered at all.
339    ///
340    /// The single rule behind both halves of that: [`link_target`] redirects
341    /// exactly the keys this accepts, and the caller skips writing exactly the
342    /// notes this accepts. They cannot disagree.
343    #[must_use]
344    pub fn redirects_external_ref(&self, key: &str) -> bool {
345        key.strip_prefix("extref:")
346            .and_then(rto_graph::parse_qualified)
347            .is_some_and(|(project, _)| self.members.contains(project))
348    }
349}
350
351/// The note name for a node `key` owned by `scope`'s project.
352///
353/// In a single-project vault (`scope.project == None`) this *is* [`note_name`].
354/// In a workspace vault it is [`note_name`] of the project-qualified key
355/// `<project>::<key>` — reusing ADR-0009's qualified form rather than inventing a
356/// second one, which is what lets a cross-repo external-ref target (already
357/// stored qualified) map to its note by the very same call.
358#[must_use]
359pub fn scoped_note_name(scope: &VaultScope<'_>, key: &str) -> String {
360    match scope.project {
361        None => note_name(key),
362        Some(project) => note_name(&format!("{project}::{key}")),
363    }
364}
365
366/// The note an edge pointing at `key` should link to.
367///
368/// Almost always [`scoped_note_name`]. The exception is the one cross-repo edge
369/// the graph already models: a spoke's inferred link to a hub is stored as an
370/// edge to a **local external-ref placeholder** (`extref:<project>::<key>`,
371/// [`rto_graph::external_ref_key`]) because store integrity requires both ends of
372/// an edge in one store. A workspace vault holds both repos' notes, so when the
373/// placeholder's target names a member the link is pointed at the **real** note
374/// instead of the stand-in.
375///
376/// This invents no edge. It renders the edge that is there, following the
377/// placeholder exactly as [`rto_graph::Workspace::follow_external_ref`] does at
378/// query time — the cross-repo graph has only ever been *rendered* one repo at a
379/// time.
380fn link_target(scope: &VaultScope<'_>, key: &str) -> String {
381    if scope.redirects_external_ref(key) {
382        // `note_name(qualified)` is by construction the same string
383        // `scoped_note_name` produces for that member's own copy of the node.
384        // `strip_prefix`, not `trim_start_matches`: the latter strips the prefix
385        // repeatedly, which would mangle a target that legitimately starts with it.
386        return note_name(key.strip_prefix("extref:").unwrap_or(key));
387    }
388    scoped_note_name(scope, key)
389}
390
391/// Render a node's [`Explanation`] into an Obsidian note: YAML frontmatter (with
392/// `tags` for the graph view and an ADR's `status`), a clickable **Source** link
393/// (when `source_base` — a web "blob" base like
394/// `https://github.com/org/repo/blob/<sha>` — is known and the node has a path),
395/// the content as the knowledge base, and its edges as provenance-labelled
396/// wikilinks.
397///
398/// `body` is the node's **full source text**, which only the caller can fetch:
399/// this function is a pure function of the `Explanation`, and an `Explanation`
400/// carries no repository, store or blob. When it is `Some`, it replaces
401/// `meta.content` in the note's `## Content` section — see [`note_body`] for why
402/// replacing is the only correct combination of the two.
403#[must_use]
404pub fn render_note(ex: &Explanation, source_base: Option<&str>, body: Option<&str>) -> VaultNote {
405    render_note_scoped(ex, source_base, body, &VaultScope::PROJECT)
406}
407
408/// [`render_note`], for one member of a **workspace** vault: identical except
409/// that the note's own name and every link it emits are resolved through `scope`
410/// (see [`VaultScope`]).
411///
412/// With [`VaultScope::PROJECT`] this is [`render_note`] byte for byte, which is
413/// how the single-project vault's compatibility promise is kept by construction
414/// rather than by a parallel code path that has to be kept in step.
415#[must_use]
416pub fn render_note_scoped(
417    ex: &Explanation,
418    source_base: Option<&str>,
419    body: Option<&str>,
420    scope: &VaultScope<'_>,
421) -> VaultNote {
422    let meta = &ex.meta;
423    let status = meta.get("status").and_then(|v| v.as_str());
424    let content = note_body(meta.get("content").and_then(|v| v.as_str()), body);
425
426    let mut c = String::new();
427    c.push_str("---\n");
428    let _ = writeln!(c, "key: {}", yaml_double_quoted(&ex.node.key));
429    let _ = writeln!(c, "kind: {}", yaml_scalar(ex.node.kind.as_str()));
430    // Which member this note came from. Absent in a single-project vault, where
431    // it would be one constant repeated on every note — and where adding it would
432    // change every note's bytes.
433    if let Some(project) = scope.project {
434        let _ = writeln!(c, "project: {}", yaml_double_quoted(project));
435    }
436    if let Some(path) = &ex.node.path {
437        let _ = writeln!(c, "path: {}", yaml_double_quoted(path));
438    }
439    if let Some(lang) = &ex.node.lang {
440        let _ = writeln!(c, "lang: {}", yaml_scalar(lang));
441    }
442    if let Some(status) = status {
443        let _ = writeln!(c, "status: {}", yaml_scalar(status));
444    }
445    // Nested tags group in Obsidian's tag pane and colour the graph view.
446    c.push_str("tags:\n");
447    let _ = writeln!(c, "  - roteiro/kind/{}", tag_slug(&ex.node.kind));
448    // Colours the graph view by member, which is the one thing a workspace vault
449    // is for and a per-project vault has no use for.
450    if let Some(project) = scope.project {
451        let _ = writeln!(c, "  - roteiro/project/{}", tag_slug(project));
452    }
453    if let Some(lang) = &ex.node.lang {
454        let _ = writeln!(c, "  - roteiro/lang/{}", tag_slug(lang));
455    }
456    if let Some(status) = status {
457        let _ = writeln!(c, "  - roteiro/status/{}", tag_slug(status));
458    }
459    c.push_str("---\n\n");
460
461    let _ = writeln!(c, "# {}", ex.node.name);
462    if let Some(status) = status {
463        let _ = writeln!(c, "\n> **Status:** {status}");
464    }
465
466    // A clickable link to the file this node comes from. An absolute URL, so it
467    // works from the downloaded vault too (which has no repo files beside it).
468    if let (Some(base), Some(path)) = (source_base, ex.node.path.as_deref()) {
469        let _ = writeln!(
470            c,
471            "\n**Source:** [`{path}`]({}/{path})",
472            base.trim_end_matches('/')
473        );
474    }
475
476    // The knowledge base: the full source text, or the captured doc comment /
477    // prose / PDF / image text.
478    if let Some(content) = content.map(str::trim).filter(|s| !s.is_empty()) {
479        c.push_str("\n## Content\n\n");
480        c.push_str(content);
481        c.push('\n');
482    }
483
484    if !ex.outgoing.is_empty() {
485        c.push_str("\n## Outgoing\n\n");
486        for e in &ex.outgoing {
487            let _ = writeln!(
488                c,
489                "- {} ({}){} → [[{}]]",
490                e.kind,
491                e.provenance,
492                confidence(e.confidence),
493                link_target(scope, &e.node)
494            );
495        }
496    }
497    if !ex.incoming.is_empty() {
498        c.push_str("\n## Incoming\n\n");
499        for e in &ex.incoming {
500            let _ = writeln!(
501                c,
502                "- [[{}]] {} ({}){} →",
503                link_target(scope, &e.node),
504                e.kind,
505                e.provenance,
506                confidence(e.confidence)
507            );
508        }
509    }
510
511    VaultNote {
512        filename: format!("{}.md", scoped_note_name(scope, &ex.node.key)),
513        content: c,
514    }
515}
516
517/// Choose the text a note shows: the caller's full `body` when it has one, else
518/// the node's stored `content`.
519///
520/// The two are **not** complementary, they are the same text at two fidelities,
521/// so a note shows one of them and never both. `meta.content` is an embedding
522/// budget — extraction caps it (1500 chars) and collapses every whitespace run to
523/// a single space, which is right for a store that ships with the graph and wrong
524/// for a note: a 23 KB document arrives as one 1500-character line with every
525/// heading, table and code fence flattened into it. Where the caller can supply
526/// the source, that is what a reader wants; appending the capped rendering
527/// underneath it would only restate its first 6% badly.
528fn note_body<'a>(content: Option<&'a str>, body: Option<&'a str>) -> Option<&'a str> {
529    body.or(content)
530}
531
532/// `" (0.82)"` for an inferred edge's confidence, else empty.
533fn confidence(c: Option<f64>) -> String {
534    c.map_or_else(String::new, |c| format!(" ({c:.2})"))
535}
536
537/// A tag-safe slug: lowercase, non-alphanumeric runs → `-`. Keeps Obsidian tags
538/// (`roteiro/kind/adr-section`) valid and stable.
539fn tag_slug(s: &str) -> String {
540    let mut out = String::with_capacity(s.len());
541    let mut prev_dash = false;
542    for ch in s.chars() {
543        if ch.is_ascii_alphanumeric() {
544            out.push(ch.to_ascii_lowercase());
545            prev_dash = false;
546        } else if !prev_dash {
547            out.push('-');
548            prev_dash = true;
549        }
550    }
551    out.trim_matches('-').to_owned()
552}
553
554/// One ADR in the overview, with its lifecycle status.
555#[derive(Debug, Clone)]
556pub struct AdrEntry {
557    /// The ADR node key (`adr:<id>`).
558    pub key: String,
559    /// The ADR title.
560    pub name: String,
561    /// Lifecycle status (`Accepted`, …), if recorded.
562    pub status: Option<String>,
563}
564
565/// The `_Home` overview's config-secret inventory figures.
566///
567/// Counts and file paths only — deliberately not the key names, which belong in
568/// `roteiro config-secrets` where the caveat can be stated at length. A vault note
569/// is read casually and out of context, which is exactly the wrong place for a
570/// list that looks like a secret scan's output.
571#[derive(Debug, Clone, Default)]
572pub struct ConfigSecretSummary {
573    /// Config keys whose **name** matched the secret-name heuristic.
574    pub secret_named: usize,
575    /// Of those, how many had their value redacted before persistence.
576    pub redacted: usize,
577    /// Of those, how many are declared in code with no literal value.
578    pub declared: usize,
579    /// Of those, how many carry an unredacted value. Expected to be zero.
580    pub unredacted: usize,
581    /// Distinct files carrying at least one secret-named key, ordered and capped
582    /// by the caller.
583    pub files: Vec<String>,
584}
585
586/// One file in the `_Home` overview's intent-debt density table.
587#[derive(Debug, Clone)]
588pub struct DensityEntry {
589    /// Repository-relative path, used for both the wikilink and the label.
590    pub path: String,
591    /// Retained markers in the file.
592    pub markers: u32,
593    /// The file's length in lines — the denominator.
594    pub lines: u32,
595    /// Markers per 1,000 lines.
596    pub per_kloc: f64,
597}
598
599/// One node in the `_Home` overview's directed-coupling table.
600#[derive(Debug, Clone)]
601pub struct CouplingEntry {
602    /// The node key, for the wikilink.
603    pub key: String,
604    /// The symbol name.
605    pub name: String,
606    /// Distinct callers.
607    pub fan_in: u32,
608    /// Distinct callees.
609    pub fan_out: u32,
610}
611
612/// Aggregate figures for the vault's `_Home` overview note.
613#[derive(Debug, Clone, Default)]
614pub struct VaultSummary {
615    /// Name of the scanned project (repository directory).
616    pub project: String,
617    /// Total node and edge counts.
618    pub total_nodes: usize,
619    /// Total edge count.
620    pub total_edges: usize,
621    /// `(kind, count)` for each node kind, most-frequent first.
622    pub node_counts: Vec<(String, usize)>,
623    /// `(provenance, edge count)` — `derived` / `authored` / `inferred`.
624    pub edge_provenance: Vec<(String, usize)>,
625    /// The ADRs, with status.
626    pub adrs: Vec<AdrEntry>,
627    /// `(category, count)` of intent-debt markers.
628    pub debt: Vec<(String, usize)>,
629    /// The files where that debt is most **concentrated**, already ranked and
630    /// capped by the caller. Empty when the graph has no markers, or when no
631    /// file carrying one has a recorded length.
632    pub densest_files: Vec<DensityEntry>,
633    /// Secret-named config keys and their redaction state. `None` when the graph
634    /// holds no secret-named config key — the section is then absent rather than
635    /// rendering a row of zeroes, which would read as a clean bill of health this
636    /// lens cannot give.
637    pub config_secrets: Option<ConfigSecretSummary>,
638    /// The most depended-on symbols by **directed** call fan-in, already ranked
639    /// and capped by the caller. Empty when the graph has no `calls` edges.
640    pub most_called: Vec<CouplingEntry>,
641    /// Web root of the repository (`https://host/owner/repo`), if derivable from
642    /// the git remote — for a "Repository" link in the overview.
643    pub repo_url: Option<String>,
644    /// Hex commit the graph was rendered from, for a permalink note.
645    pub commit: Option<String>,
646}
647
648/// Render the vault's overview note: what was scanned, the structure by kind,
649/// the provenance breakdown, the decisions (ADRs) and their status, the
650/// intent-debt summary, and how to navigate. The entry point for the vault.
651#[must_use]
652pub fn render_home(s: &VaultSummary) -> VaultNote {
653    let mut c = String::new();
654    c.push_str("---\ntags:\n  - roteiro/home\n---\n\n");
655    let _ = writeln!(c, "# {} — knowledge graph", s.project);
656    c.push_str(
657        "\n*A browsable snapshot of this codebase as one **knowledge graph**, \
658         generated by [Roteiro](https://roteiro.dev). Every symbol, document and \
659         decision is a note, linked to the things it relates to.*\n",
660    );
661    c.push_str(HOW_TO_READ);
662    let _ = writeln!(
663        c,
664        "\n**{} nodes**, **{} edges** across the project.",
665        s.total_nodes, s.total_edges
666    );
667    write_repo_line(&mut c, s);
668    write_summary_sections(&mut c, s, &VaultScope::PROJECT, 2);
669    c.push_str(NAVIGATING);
670
671    VaultNote {
672        filename: HOME_NOTE.to_owned(),
673        content: c,
674    }
675}
676
677/// The "how to read a note" paragraph. Shared verbatim by the single-project and
678/// workspace overviews — the notes themselves are identical in both, so a reader
679/// who learns the format once has learned it for either.
680const HOW_TO_READ: &str = "\n**How to read it.** Open any note to see what a thing is, the intent or \
681     docs behind it (its **Content**), where it lives (its **Source** link), \
682     and how it connects (**Outgoing**/**Incoming** links). Each link is \
683     labelled with how the fact was established — `derived` (extracted from \
684     code), `authored` (human intent: ADRs, blueprints, annotations), or \
685     `inferred` (a scored suggestion). Open Obsidian's **graph view** to see \
686     the whole thing at once.\n";
687
688/// The closing navigation section.
689const NAVIGATING: &str = "\n## Navigating this vault\n\n\
690     - Open the **graph view** to see the whole codebase; notes are coloured/\
691     filterable by their `roteiro/kind/*`, `roteiro/lang/*` and \
692     `roteiro/status/*` tags.\n\
693     - Each note carries its captured **content** (doc comments, prose, PDF/\
694     image text) and its provenance-labelled incoming/outgoing links.\n\
695     - Start from an ADR above, or search the tag pane for a kind.\n";
696
697/// `**Repository:** …` — the web root and the commit the graph was rendered from.
698fn write_repo_line(c: &mut String, s: &VaultSummary) {
699    if let Some(repo) = &s.repo_url {
700        let _ = write!(c, "\n**Repository:** [{repo}]({repo})");
701        if let Some(commit) = &s.commit {
702            let short = &commit[..commit.len().min(12)];
703            let _ = write!(c, " · rendered at commit `{short}`");
704        }
705        c.push('\n');
706    }
707}
708
709/// Every aggregate the overview carries for **one project**: structure by kind,
710/// provenance, ADRs, intent debt (and where it is densest), the config-secret
711/// inventory and directed call coupling.
712///
713/// Factored out of [`render_home`] so a workspace vault's per-member section is
714/// *the same code*, not a reimplementation that can drift: the promise in issue
715/// #442 is that today's per-project view stays a **subset** of the workspace one
716/// rather than a casualty of it. `level` is the markdown heading depth — 2 for a
717/// single-project `_Home`, 3 inside a member's section — and `scope` decides
718/// whether the wikilinks point at bare or project-qualified notes.
719fn write_summary_sections(c: &mut String, s: &VaultSummary, scope: &VaultScope<'_>, level: usize) {
720    let hd = &"#".repeat(level);
721    let sub = &"#".repeat(level + 1);
722    write_structure(c, s, hd);
723    write_decisions(c, s, scope, hd);
724    write_debt(c, s, scope, hd, sub);
725    write_config_secrets(c, s, scope, hd);
726    write_coupling(c, s, scope, hd);
727}
728
729/// `Structure` (nodes by kind) and `Provenance` (edges by how they were established).
730fn write_structure(c: &mut String, s: &VaultSummary, hd: &str) {
731    let _ = write!(c, "\n{hd} Structure\n\n| Kind | Count |\n| --- | --- |\n");
732    for (kind, n) in &s.node_counts {
733        let _ = writeln!(c, "| {kind} | {n} |");
734    }
735
736    if !s.edge_provenance.is_empty() {
737        let _ = write!(
738            c,
739            "\n{hd} Provenance\n\n| Provenance | Edges |\n| --- | --- |\n"
740        );
741        for (prov, n) in &s.edge_provenance {
742            let _ = writeln!(c, "| {prov} | {n} |");
743        }
744    }
745}
746
747/// `Decisions (ADRs)` — the recorded decisions and their lifecycle status.
748fn write_decisions(c: &mut String, s: &VaultSummary, scope: &VaultScope<'_>, hd: &str) {
749    let _ = write!(c, "\n{hd} Decisions (ADRs)\n\n");
750    if s.adrs.is_empty() {
751        c.push_str("*No ADRs found.*\n");
752    } else {
753        for adr in &s.adrs {
754            let status = adr.status.as_deref().unwrap_or("—");
755            let _ = writeln!(
756                c,
757                "- **{status}** — [[{}|{}]]",
758                scoped_note_name(scope, &adr.key),
759                adr.name
760            );
761        }
762    }
763}
764
765/// `Intent debt` — the marker categories, and the files the debt is densest in.
766fn write_debt(c: &mut String, s: &VaultSummary, scope: &VaultScope<'_>, hd: &str, sub: &str) {
767    let _ = write!(c, "\n{hd} Intent debt\n\n");
768    if s.debt.is_empty() {
769        c.push_str("*None recorded.*\n");
770    } else {
771        c.push_str("| Category | Count |\n| --- | --- |\n");
772        for (cat, n) in &s.debt {
773            let _ = writeln!(c, "| {cat} | {n} |");
774        }
775    }
776
777    if !s.densest_files.is_empty() {
778        let _ = write!(
779            c,
780            "\n{sub} Densest files (markers per 1,000 lines)\n\n\
781             *Where the debt above is concentrated, rather than where there is \
782             most of it — a raw count ranks the biggest file first by \
783             construction. The denominator is file length: every line, blanks and \
784             comments included, not source lines of code. Prose matches (`for \
785             now`, `tbd`) count too, so a design document can rank high.*\n\n"
786        );
787        c.push_str("| File | Markers | Lines | Per 1k |\n| --- | --- | --- | --- |\n");
788        for e in &s.densest_files {
789            let _ = writeln!(
790                c,
791                "| [[{}\\|{}]] | {} | {} | {:.2} |",
792                scoped_note_name(scope, &format!("file:{}", e.path)),
793                e.path,
794                e.markers,
795                e.lines,
796                e.per_kloc
797            );
798        }
799    }
800}
801
802/// `Config keys named like secrets` — an inventory and its unconditional caveat.
803fn write_config_secrets(c: &mut String, s: &VaultSummary, scope: &VaultScope<'_>, hd: &str) {
804    if let Some(cs) = &s.config_secrets {
805        let _ = write!(c, "\n{hd} Config keys named like secrets\n\n");
806        let _ = writeln!(
807            c,
808            "**{}** secret-named config key(s): {} redacted before storage, {} \
809             declared in code without a value, {} unredacted.",
810            cs.secret_named, cs.redacted, cs.declared, cs.unredacted
811        );
812        if cs.unredacted > 0 {
813            let _ = writeln!(
814                c,
815                "\n> [!warning] {} key(s) carry an **unredacted** value. Extraction \
816                 always redacts, so these came from an import layer — inspect the \
817                 importing tool, not this repository.",
818                cs.unredacted
819            );
820        }
821        if !cs.files.is_empty() {
822            c.push_str("\nIn:\n");
823            for path in &cs.files {
824                let _ = writeln!(
825                    c,
826                    "- [[{}\\|{path}]]",
827                    scoped_note_name(scope, &format!("file:{path}"))
828                );
829            }
830        }
831        // The caveat is unconditional and comes last, so it is the final thing read
832        // in this section. A vault note is browsed out of context; this is exactly
833        // where "config keys named like secrets" would otherwise be misread as a
834        // secret scan that came back clean.
835        c.push_str(
836            "\n*An inventory of config keys whose **names** look secret, not a secret \
837             scan. Values are redacted before they are stored, so this reports that \
838             such keys exist and were redacted — never a value. It cannot see a \
839             hardcoded credential in source code, cannot judge whether a value is \
840             valid, and cannot tell a real secret from a placeholder. A credential \
841             under an innocuous key name (`dsn`, `endpoint`) does not appear here at \
842             all, so this section being small says nothing about whether this \
843             repository leaks secrets.*\n",
844        );
845    }
846}
847
848/// `Most depended-on (call fan-in)` — directed call coupling, capped.
849fn write_coupling(c: &mut String, s: &VaultSummary, scope: &VaultScope<'_>, hd: &str) {
850    if !s.most_called.is_empty() {
851        let _ = write!(
852            c,
853            "\n{hd} Most depended-on (call fan-in)\n\n\
854             *Distinct callers and callees over `calls` edges — direction kept, so \
855             \"everything calls this\" and \"this calls everything\" are not the same \
856             row. Call targets are resolved by simple name, so a short, generically-\
857             named function can absorb every call to that name: read a large fan-in on \
858             one as a question, not a finding.*\n\n"
859        );
860        c.push_str("| Symbol | Called by | Calls |\n| --- | --- | --- |\n");
861        for e in &s.most_called {
862            let _ = writeln!(
863                c,
864                "| [[{}\\|{}]] | {} | {} |",
865                scoped_note_name(scope, &e.key),
866                e.name,
867                e.fan_in,
868                e.fan_out
869            );
870        }
871    }
872}
873
874/// One cross-repo edge the workspace vault can actually follow: a spoke's node
875/// linking to a hub's, through the external-ref placeholder ADR-0009 persists.
876///
877/// Collected by the caller, which has every member's store open; the renderer
878/// only lays them out. Nothing here is a new edge — these are the `inferred`
879/// links `roteiro links` already reports, rendered for the first time.
880#[derive(Debug, Clone)]
881pub struct CrossLink {
882    /// The member the edge starts in.
883    pub from_project: String,
884    /// The source node's key, within `from_project`.
885    pub from_key: String,
886    /// The source node's display name.
887    pub from_name: String,
888    /// The edge kind (`links`, …).
889    pub kind: String,
890    /// Confidence, for an `inferred` edge.
891    pub confidence: Option<f64>,
892    /// The project-qualified target, `<project>::<key>` (ADR-0009).
893    pub to_qualified: String,
894    /// Whether `to_qualified`'s project is a member of this workspace — and so
895    /// whether the link resolves to a note in this vault, or dangles because the
896    /// target repository is outside it.
897    pub resolves: bool,
898}
899
900/// Aggregate figures for a **workspace** vault's `_Home` overview: the members,
901/// each with exactly the aggregates a single-project `_Home` carries, plus the
902/// cross-repo links between them.
903#[derive(Debug, Clone, Default)]
904pub struct WorkspaceSummary {
905    /// The workspace name (`--workspace-name`).
906    pub name: String,
907    /// One entry per member repository, in stable name order. Each is the very
908    /// same [`VaultSummary`] a per-project vault would render.
909    pub members: Vec<VaultSummary>,
910    /// Cross-repo links between members, already ordered and capped by the caller.
911    pub cross_links: Vec<CrossLink>,
912    /// Cross-repo links found in total, which `cross_links` may be a capped view
913    /// of — so the section can say what it is not showing.
914    pub cross_links_total: usize,
915}
916
917/// Render a **workspace** vault's overview: the members and their scale, the
918/// cross-repo links between them, and then each member's own aggregates —
919/// structure, provenance, ADRs, intent debt, config-secret inventory and call
920/// coupling — under its own heading.
921///
922/// The per-member sections are rendered by the same [`write_summary_sections`]
923/// the single-project `_Home` uses, so the existing view is a **subset** of this
924/// one: someone who came for their repository's coupling and debt tables finds
925/// them, rather than a workspace total that averages them away.
926#[must_use]
927pub fn render_workspace_home(ws: &WorkspaceSummary) -> VaultNote {
928    let members: std::collections::BTreeSet<String> =
929        ws.members.iter().map(|m| m.project.clone()).collect();
930
931    let mut c = String::new();
932    c.push_str("---\ntags:\n  - roteiro/home\n  - roteiro/workspace\n---\n\n");
933    let _ = writeln!(c, "# {} — workspace knowledge graph", ws.name);
934    c.push_str(
935        "\n*A browsable snapshot of a whole **workspace** as one **knowledge \
936         graph**, generated by [Roteiro](https://roteiro.dev). Every symbol, \
937         document and decision in every member repository is a note, linked to the \
938         things it relates to — including across repositories.*\n",
939    );
940    c.push_str(HOW_TO_READ);
941    // The example is *rendered* by `note_name` rather than spelled out. A
942    // hand-written spelling of this sentence survived #574 unchanged, so every
943    // vault v2.0.0 built stated the pre-#574 naming rule — on the first page a
944    // reader opens — while `note_name` was writing something else. This is the
945    // one copy that lives in the crate defining the rule, so it can simply ask:
946    // a derived example cannot drift, and a spelled one already has.
947    //
948    // The *key* it names has to be real too, or the fix trades one false
949    // sentence in `_Home` for another: `<member>::file:README.md` was fabricated
950    // from the member list, and workspace membership does not require a README.
951    // A cross-repo link's **source** end is the strongest key available here —
952    // `from_project` is a member by definition and `from_key` is a node in that
953    // member's own store, which the Cross-repo links table below already links
954    // to by name. The *target* end will not do: `resolves == false` means the
955    // target repository is outside this vault, so `to_qualified` names no note
956    // here — the same false claim one remove away.
957    //
958    // With no cross-repo links there is no key this function can prove is a
959    // node, so the sentence says nothing rather than inventing one. The rule it
960    // states is complete without an example; only the illustration is lost.
961    let example = ws.cross_links.first().map_or_else(String::new, |l| {
962        let key = format!("{}::{}", l.from_project, l.from_key);
963        format!(" Here, `{key}` is the note `{}.md`.", note_name(&key))
964    });
965    let _ = writeln!(
966        c,
967        "\n**Every note is keyed `<project>::<key>`**, because a node key is \
968         repository-relative: the same path or symbol can occur in more than one \
969         member, and without the project the second note would overwrite the \
970         first. A note's *filename* is derived from that key — a readable \
971         lowercase hint, then a hash of the whole key — so no filename contains \
972         `::`.{example} Filter the graph view by a member's `roteiro/project/*` \
973         tag to see one repository at a time."
974    );
975
976    let total_nodes: usize = ws.members.iter().map(|m| m.total_nodes).sum();
977    let total_edges: usize = ws.members.iter().map(|m| m.total_edges).sum();
978    let _ = writeln!(
979        c,
980        "\n**{total_nodes} nodes**, **{total_edges} edges** across **{}** member \
981         repositor{}.",
982        ws.members.len(),
983        if ws.members.len() == 1 { "y" } else { "ies" }
984    );
985
986    c.push_str("\n## Members\n\n| Project | Nodes | Edges | Repository | Commit |\n| --- | --- | --- | --- | --- |\n");
987    for m in &ws.members {
988        let repo = m
989            .repo_url
990            .as_ref()
991            .map_or_else(|| "—".to_owned(), |u| format!("[{u}]({u})"));
992        let commit = m.commit.as_ref().map_or_else(
993            || "—".to_owned(),
994            |c| format!("`{}`", &c[..c.len().min(12)]),
995        );
996        let _ = writeln!(
997            c,
998            "| [[#{}\\|{}]] | {} | {} | {repo} | {commit} |",
999            m.project, m.project, m.total_nodes, m.total_edges
1000        );
1001    }
1002    c.push_str(
1003        "\n*The `Repository` and `Commit` columns say where each member came from \
1004         and what was read. They are **not** a replication manifest — reconstructing \
1005         a workspace from a vault is issue #442 part 2, and nothing here is designed \
1006         to be handed to someone else.*\n",
1007    );
1008
1009    write_cross_links(&mut c, ws);
1010
1011    for m in &ws.members {
1012        let _ = writeln!(c, "\n## {}", m.project);
1013        let _ = writeln!(
1014            c,
1015            "\n**{} nodes**, **{} edges** in this member.",
1016            m.total_nodes, m.total_edges
1017        );
1018        write_repo_line(&mut c, m);
1019        let scope = VaultScope {
1020            project: Some(&m.project),
1021            members: &members,
1022        };
1023        write_summary_sections(&mut c, m, &scope, 3);
1024    }
1025
1026    c.push_str(NAVIGATING);
1027
1028    VaultNote {
1029        filename: HOME_NOTE.to_owned(),
1030        content: c,
1031    }
1032}
1033
1034/// The `## Cross-repo links` section: the edges that only a workspace vault can
1035/// show, and the honest statement of what is missing from them.
1036fn write_cross_links(c: &mut String, ws: &WorkspaceSummary) {
1037    c.push_str("\n## Cross-repo links\n\n");
1038    if ws.cross_links.is_empty() {
1039        c.push_str(
1040            "*None. These are the `inferred` cross-repo links `roteiro links \
1041             --infer --write` persists (ADR-0009); a workspace whose members have \
1042             never been inferred over has none recorded yet.*\n",
1043        );
1044        return;
1045    }
1046    c.push_str(
1047        "*A spoke's config key and the hub key it corresponds to, across \
1048         repositories — the one thing a per-project vault structurally cannot show. \
1049         These are `inferred` matches persisted by `roteiro links --infer --write` \
1050         (ADR-0009), not authored facts: read a row as a candidate correspondence.*\n\n",
1051    );
1052    c.push_str("| From | | To | Kind |\n| --- | --- | --- | --- |\n");
1053    for l in &ws.cross_links {
1054        let from_scope = VaultScope {
1055            project: Some(&l.from_project),
1056            members: &NO_MEMBERS,
1057        };
1058        let to = if l.resolves {
1059            format!("[[{}\\|{}]]", note_name(&l.to_qualified), l.to_qualified)
1060        } else {
1061            // Outside this workspace: there is no note to link to, and a wikilink
1062            // to a note that does not exist reads in Obsidian as one that is
1063            // merely unwritten.
1064            format!("`{}` *(outside this workspace)*", l.to_qualified)
1065        };
1066        let _ = writeln!(
1067            c,
1068            "| [[{}\\|{}]] | {} | {to} | {}{} |",
1069            scoped_note_name(&from_scope, &l.from_key),
1070            l.from_name,
1071            l.from_project,
1072            l.kind,
1073            confidence(l.confidence)
1074        );
1075    }
1076    if ws.cross_links_total > ws.cross_links.len() {
1077        let _ = writeln!(
1078            c,
1079            "\n*Showing {} of {} — the full report is `roteiro links --matrix`.*",
1080            ws.cross_links.len(),
1081            ws.cross_links_total
1082        );
1083    }
1084    c.push_str(
1085        "\n*Shown in one direction only. The edge lives in the spoke's store, \
1086         pointing at a local placeholder for the hub's node, so the hub's own note \
1087         carries no matching **Incoming** entry — Obsidian's **Backlinks** pane \
1088         still shows it, because the link is in the vault.*\n",
1089    );
1090}
1091
1092#[cfg(test)]
1093mod tests {
1094    use super::{
1095        AdrEntry, ConfigSecretSummary, CouplingEntry, CrossLink, DensityEntry, HOME_NOTE,
1096        VaultScope, VaultSummary, WorkspaceSummary, note_name, render_home, render_note,
1097        render_note_scoped, render_workspace_home, scoped_note_name,
1098    };
1099    use rto_graph::{EdgeRef, Explanation, NodeSummary};
1100
1101    /// The shape of a name, pinned once so a change to it is a deliberate edit
1102    /// here rather than a diff spread over twenty other assertions.
1103    ///
1104    /// Everything else in this module composes `note_name` instead of repeating
1105    /// its output, because those tests are about *which key a link points at* and
1106    /// were never about the spelling.
1107    #[test]
1108    fn note_name_is_a_lowercase_hint_and_a_hash_of_the_whole_key() {
1109        assert_eq!(
1110            note_name("sym:rust:src/a.rs#Store"),
1111            "sym-rust-src-a.rs-store-b4cbf6633003361f"
1112        );
1113        assert_eq!(note_name("adr:0001"), "adr-0001-559a2e837953b2ff");
1114        assert_eq!(
1115            note_name("file:src/main.rs"),
1116            "file-src-main.rs-4a72627453f6780e"
1117        );
1118        // Deterministic: the suffix is a pure function of the key, so a vault
1119        // renders the same names on every machine and every run.
1120        assert_eq!(note_name("adr:0001"), note_name("adr:0001"));
1121    }
1122
1123    /// **The property `note_name` exists to have** (issue #574): distinct keys
1124    /// give distinct notes *on a case-folding filesystem*, which is where the
1125    /// vault was losing them.
1126    ///
1127    /// Asserted over lowercased names, not names. On macOS and Windows two names
1128    /// differing only in case are one file, so a name set that is distinct as
1129    /// strings can still be a vault with notes missing — and Linux CI cannot see
1130    /// it. Folding here makes the assertion say what the filesystem says, on
1131    /// every platform.
1132    ///
1133    /// The keys are the two mechanisms that were actually losing notes, taken
1134    /// from this repository's own render rather than invented: the vendored
1135    /// `cytoscape.min.js` bundle whose minified single-letter symbols differ only
1136    /// by a sigil or by case, and a pair of grouped Rust `use` keys differing
1137    /// only by a trailing comma. `render_cli` runs the same assertion end to end
1138    /// over a rendered vault; this is the unit-level statement of it.
1139    #[test]
1140    fn distinct_keys_give_distinct_notes_even_after_case_folding() {
1141        const JS: &str = "sym:javascript:crates/roteiro/src/assets/cytoscape.min.js";
1142        let keys: Vec<String> = [
1143            // Slug lossiness: the sigil and the letter both slugged to the same
1144            // thing (9 notes lost this way, on every platform).
1145            format!("{JS}#$a"),
1146            format!("{JS}#a"),
1147            format!("{JS}#$o"),
1148            format!("{JS}#o"),
1149            // Case folding: distinct names, one file (95 notes lost this way, and
1150            // only on macOS and Windows).
1151            format!("{JS}#A"),
1152            format!("{JS}#O"),
1153            format!("{JS}#S"),
1154            format!("{JS}#s"),
1155            // Real source symbols, same shape.
1156            "sym:rust:crates/rto-exec/src/sandbox_store.rs#Store".into(),
1157            "sym:rust:crates/rto-exec/src/sandbox_store.rs#store".into(),
1158            // A trailing comma is the whole difference between these two.
1159            "import:rust:crate::engine::{ChatRequest,Engine,ModelInfo,}".into(),
1160            "import:rust:crate::engine::{ChatRequest,Engine,ModelInfo}".into(),
1161            // Nothing but separators: no hint at all, so the name is bare hash.
1162            "::".into(),
1163            "##".into(),
1164            // Over the length bound, differing only past the truncation point —
1165            // the case truncation alone used to merge.
1166            format!("import:rust:{}A", "a::b::c,".repeat(60)),
1167            format!("import:rust:{}a", "a::b::c,".repeat(60)),
1168        ]
1169        .into();
1170
1171        let folded: std::collections::BTreeSet<String> =
1172            keys.iter().map(|k| note_name(k).to_lowercase()).collect();
1173        assert_eq!(
1174            folded.len(),
1175            keys.len(),
1176            "two keys share a note after case folding; the vault would hold one \
1177             file for both and report two"
1178        );
1179    }
1180
1181    /// Case folding is the identity on a note name, so the assertion above is not
1182    /// weaker than the filesystem it stands in for.
1183    ///
1184    /// This is the reason the hint is lowercased rather than case-preserved: it
1185    /// makes "distinct names" and "distinct files on macOS" the same statement,
1186    /// so there is no version of this module that passes on Linux and loses notes
1187    /// on a Mac. Without it, the two assertions could drift apart and only the
1188    /// weaker one would ever run in CI.
1189    #[test]
1190    fn a_note_name_is_already_lowercase() {
1191        for key in [
1192            "sym:rust:src/a.rs#Store",
1193            "file:README.md",
1194            "app::file:CHANGELOG.md",
1195            "sym:javascript:a.js#ABC",
1196        ] {
1197            let name = note_name(key);
1198            assert_eq!(name, name.to_lowercase(), "`{key}` kept case in its name");
1199        }
1200    }
1201
1202    /// `_Home` is a name in the same namespace as every note, and it is not
1203    /// derived from a key — so nothing must be able to collide with it. The
1204    /// mandatory suffix gives that for free: every generated name either ends in
1205    /// `-<16 hex>` or *is* 16 hex digits, and `_home` is neither.
1206    #[test]
1207    fn no_key_can_claim_the_home_note() {
1208        for key in ["_Home", "file:_Home", "_home", "::_Home::"] {
1209            assert_ne!(
1210                format!("{}.md", note_name(key)).to_lowercase(),
1211                HOME_NOTE.to_lowercase(),
1212                "`{key}` would overwrite the overview note"
1213            );
1214        }
1215    }
1216
1217    #[test]
1218    fn render_note_emits_frontmatter_and_wikilinks() {
1219        let ex = Explanation {
1220            schema: rto_graph::SCHEMA,
1221            node: NodeSummary {
1222                key: "sym:rust:a.rs#main".into(),
1223                kind: "fn".into(),
1224                name: "main".into(),
1225                path: Some("a.rs".into()),
1226                lang: Some("rust".into()),
1227            },
1228            meta: serde_json::Value::Null,
1229            outgoing: vec![EdgeRef {
1230                kind: "calls".into(),
1231                provenance: "derived",
1232                confidence: None,
1233                node: "sym:rust:a.rs#helper".into(),
1234            }],
1235            incoming: vec![EdgeRef {
1236                kind: "references".into(),
1237                provenance: "authored",
1238                confidence: None,
1239                node: "adr:0001".into(),
1240            }],
1241        };
1242        let note = render_note(&ex, None, None);
1243        assert_eq!(
1244            note.filename,
1245            format!("{}.md", note_name("sym:rust:a.rs#main"))
1246        );
1247        assert!(note.content.contains("kind: fn"));
1248        // No source base → no Source link.
1249        assert!(!note.content.contains("**Source:**"));
1250        assert!(note.content.contains("# main"));
1251        assert!(note.content.contains(&format!(
1252            "- calls (derived) → [[{}]]",
1253            note_name("sym:rust:a.rs#helper")
1254        )));
1255        assert!(note.content.contains(&format!(
1256            "- [[{}]] references (authored) →",
1257            note_name("adr:0001")
1258        )));
1259        // Tags for the graph view.
1260        assert!(note.content.contains("- roteiro/kind/fn"));
1261        assert!(note.content.contains("- roteiro/lang/rust"));
1262    }
1263
1264    #[test]
1265    fn note_name_bounds_long_keys_deterministically() {
1266        let long = format!("import:rust:{}", "a::b::c,".repeat(60));
1267        let a = note_name(&long);
1268        let b = note_name(&long);
1269        assert_eq!(a, b, "deterministic");
1270        assert!(
1271            a.len() <= 205,
1272            "bounded under the filename limit: {}",
1273            a.len()
1274        );
1275        assert_ne!(
1276            note_name(&format!("{long}x")),
1277            a,
1278            "different keys stay distinct after truncation"
1279        );
1280        // Truncation must not leave a doubled separator before the suffix — the
1281        // hint is trimmed after cutting, not before.
1282        assert!(!a.contains("--"), "{a}");
1283    }
1284
1285    /// A short key is bounded too, and every name carries the suffix — the hash
1286    /// is no longer reached for only when the hint overruns.
1287    ///
1288    /// That gating was the defect (#574): two keys short enough to skip the hash
1289    /// had nothing left to tell them apart once the slug had flattened them.
1290    #[test]
1291    fn every_name_carries_the_hash_however_short_the_key() {
1292        for key in ["a", "adr:0001", "file:README.md"] {
1293            let name = note_name(key);
1294            let (hint, hash) = name.rsplit_once('-').expect("a suffixed name");
1295            assert!(!hint.is_empty(), "{name}");
1296            assert_eq!(hash.len(), 16, "{name}");
1297            assert!(
1298                hash.chars().all(|c| c.is_ascii_hexdigit()),
1299                "the suffix is the key's hash, not part of the hint: {name}"
1300            );
1301        }
1302        // A key with no hint at all is the bare hash, which cannot be mistaken
1303        // for a hinted name (those are at least 18 characters).
1304        let bare = note_name("::");
1305        assert_eq!(bare.len(), 16, "{bare}");
1306        assert!(!bare.contains('-'), "{bare}");
1307    }
1308
1309    #[test]
1310    fn render_note_surfaces_content_and_status() {
1311        let ex = Explanation {
1312            schema: rto_graph::SCHEMA,
1313            node: NodeSummary {
1314                key: "adr:0001".into(),
1315                kind: "adr".into(),
1316                name: "Build Roteiro".into(),
1317                path: Some("docs/adr/0001.md".into()),
1318                lang: None,
1319            },
1320            meta: serde_json::json!({ "status": "Accepted", "content": "The decision text." }),
1321            outgoing: vec![],
1322            incoming: vec![],
1323        };
1324        let note = render_note(&ex, Some("https://github.com/org/repo/blob/abc123"), None);
1325        assert!(note.content.contains("status: Accepted"));
1326        assert!(note.content.contains("- roteiro/status/accepted"));
1327        assert!(note.content.contains("> **Status:** Accepted"));
1328        assert!(note.content.contains("## Content\n\nThe decision text."));
1329        // A clickable link to the actual ADR file on the repository host.
1330        assert!(
1331            note.content.contains(
1332                "**Source:** [`docs/adr/0001.md`](https://github.com/org/repo/blob/abc123/docs/adr/0001.md)"
1333            ),
1334            "{}",
1335            note.content
1336        );
1337    }
1338
1339    /// The structured document a prose note is supposed to reproduce: headings, a
1340    /// table and a fenced code block, none of which survive whitespace collapse.
1341    const DOC: &str = "# Working offline\n\nRoteiro is **offline-capable**.\n\n| Host | What |\n| --- | --- |\n| `example.com` | models |\n\n```sh\nroteiro model pull\n```\n";
1342
1343    fn prose_note(content: Option<&str>) -> Explanation {
1344        Explanation {
1345            schema: rto_graph::SCHEMA,
1346            node: NodeSummary {
1347                key: "file:docs/OFFLINE_SETUP.md".into(),
1348                kind: "file".into(),
1349                name: "OFFLINE_SETUP.md".into(),
1350                path: Some("docs/OFFLINE_SETUP.md".into()),
1351                lang: None,
1352            },
1353            meta: content.map_or(
1354                serde_json::Value::Null,
1355                |c| serde_json::json!({ "content": c }),
1356            ),
1357            outgoing: vec![],
1358            incoming: vec![],
1359        }
1360    }
1361
1362    /// The whole readability defect, in one assertion pair: a note built from
1363    /// `meta.content` alone is the document whitespace-collapsed onto one line,
1364    /// and a note built from the source is the document.
1365    ///
1366    /// The newline count is the claim. A character count alone would pass on a
1367    /// note that had merely grown longer while staying flat, which is exactly the
1368    /// failure being fixed — `meta.content` is capped *and* collapsed, and only
1369    /// the collapse is what makes it unreadable.
1370    #[test]
1371    fn a_supplied_body_supersedes_the_collapsed_stored_content() {
1372        // What extraction stores: the same text, whitespace-collapsed.
1373        let collapsed = DOC.split_whitespace().collect::<Vec<_>>().join(" ");
1374        let ex = prose_note(Some(&collapsed));
1375
1376        let note = render_note(&ex, None, Some(DOC));
1377        assert!(
1378            note.content.contains(DOC.trim()),
1379            "the source document is reproduced verbatim: {}",
1380            note.content
1381        );
1382        assert!(
1383            !note.content.contains(&collapsed),
1384            "the collapsed rendering is replaced, not appended: {}",
1385            note.content
1386        );
1387        assert!(
1388            note.content.contains("\n| Host | What |\n"),
1389            "a table needs its own lines to be a table: {}",
1390            note.content
1391        );
1392        assert!(
1393            note.content.contains("\n```sh\n"),
1394            "a fenced block needs its own lines to be a fence: {}",
1395            note.content
1396        );
1397
1398        // The flat control: the same node with no body is the one-line note.
1399        let flat = render_note(&ex, None, None);
1400        assert!(
1401            flat.content.contains(&collapsed),
1402            "without a body the stored content is still shown: {}",
1403            flat.content
1404        );
1405        assert!(
1406            content_lines(&note.content) > content_lines(&flat.content),
1407            "structure restored: {} line(s) with a body vs {} without",
1408            content_lines(&note.content),
1409            content_lines(&flat.content)
1410        );
1411        assert_eq!(
1412            content_lines(&flat.content),
1413            1,
1414            "the defect: the stored content is a single line"
1415        );
1416    }
1417
1418    /// A doc comment is a summary of a definition, not a document, and its note is
1419    /// correct as it stands. The caller supplies no body for these, so this pins
1420    /// the unchanged path — the fix must not depend on every node gaining one.
1421    #[test]
1422    fn a_note_with_no_body_is_unchanged() {
1423        let ex = Explanation {
1424            schema: rto_graph::SCHEMA,
1425            node: NodeSummary {
1426                key: "sym:rust:a.rs#main".into(),
1427                kind: "fn".into(),
1428                name: "main".into(),
1429                path: Some("a.rs".into()),
1430                lang: Some("rust".into()),
1431            },
1432            meta: serde_json::json!({ "content": "Entry point." }),
1433            outgoing: vec![],
1434            incoming: vec![],
1435        };
1436        assert!(
1437            render_note(&ex, None, None)
1438                .content
1439                .contains("## Content\n\nEntry point.")
1440        );
1441    }
1442
1443    /// Lines in the note's `## Content` section.
1444    fn content_lines(note: &str) -> usize {
1445        let body = note
1446            .split_once("## Content\n\n")
1447            .map_or("", |(_, rest)| rest);
1448        let body = body.split_once("\n## ").map_or(body, |(head, _)| head);
1449        body.trim_end().lines().count()
1450    }
1451
1452    #[test]
1453    fn render_note_shows_inferred_confidence() {
1454        let ex = Explanation {
1455            schema: rto_graph::SCHEMA,
1456            node: NodeSummary {
1457                key: "file:a.md".into(),
1458                kind: "file".into(),
1459                name: "a.md".into(),
1460                path: Some("a.md".into()),
1461                lang: None,
1462            },
1463            meta: serde_json::Value::Null,
1464            outgoing: vec![EdgeRef {
1465                kind: "related".into(),
1466                provenance: "inferred",
1467                confidence: Some(0.82),
1468                node: "file:b.md".into(),
1469            }],
1470            incoming: vec![],
1471        };
1472        let note = render_note(&ex, None, None);
1473        assert!(
1474            note.content.contains(&format!(
1475                "related (inferred) (0.82) → [[{}]]",
1476                note_name("file:b.md")
1477            )),
1478            "{}",
1479            note.content
1480        );
1481    }
1482
1483    #[test]
1484    fn render_home_summarises_the_graph() {
1485        let summary = VaultSummary {
1486            project: "demo".into(),
1487            total_nodes: 3,
1488            total_edges: 2,
1489            node_counts: vec![("fn".into(), 2), ("adr".into(), 1)],
1490            edge_provenance: vec![("derived".into(), 1), ("authored".into(), 1)],
1491            adrs: vec![AdrEntry {
1492                key: "adr:0001".into(),
1493                name: "First".into(),
1494                status: Some("Accepted".into()),
1495            }],
1496            debt: vec![("todo".into(), 4)], // roteiro:ignore
1497            densest_files: vec![DensityEntry {
1498                path: "src/small.rs".into(),
1499                markers: 3,
1500                lines: 120,
1501                per_kloc: 25.0,
1502            }],
1503            config_secrets: Some(ConfigSecretSummary {
1504                secret_named: 4,
1505                redacted: 3,
1506                declared: 1,
1507                unredacted: 0,
1508                files: vec![".env".into()],
1509            }),
1510            most_called: vec![CouplingEntry {
1511                key: "sym:rust:a.rs#helper".into(),
1512                name: "helper".into(),
1513                fan_in: 7,
1514                fan_out: 1,
1515            }],
1516            repo_url: Some("https://github.com/org/repo".into()),
1517            commit: Some("abcdef0123456789".into()),
1518        };
1519        let note = render_home(&summary);
1520        assert_eq!(note.filename, HOME_NOTE);
1521        assert!(note.content.contains("# demo — knowledge graph"));
1522        assert!(note.content.contains("**3 nodes**, **2 edges**"));
1523        assert!(note.content.contains("| fn | 2 |"));
1524        assert!(note.content.contains("| derived | 1 |"));
1525        assert!(note.content.contains(&format!(
1526            "**Accepted** — [[{}|First]]",
1527            note_name("adr:0001")
1528        )));
1529        assert!(note.content.contains("| todo | 4 |")); // roteiro:ignore
1530        // Directed coupling: the two fans are separate columns, and the wikilink's
1531        // own `|` is escaped so it cannot break the table it sits in.
1532        assert!(
1533            note.content.contains(&format!(
1534                "| [[{}\\|helper]] | 7 | 1 |",
1535                note_name("sym:rust:a.rs#helper")
1536            )),
1537            "{}",
1538            note.content
1539        );
1540        assert!(
1541            note.content.contains("resolved by simple name"),
1542            "the precision caveat travels with the figures"
1543        );
1544        // Density: the count and the denominator are both shown, so the ratio can
1545        // be checked rather than taken on trust, and the wikilink's own `|` is
1546        // escaped so it cannot break the table it sits in.
1547        assert!(
1548            note.content.contains(&format!(
1549                "| [[{}\\|src/small.rs]] | 3 | 120 | 25.00 |",
1550                note_name("file:src/small.rs")
1551            )),
1552            "{}",
1553            note.content
1554        );
1555        assert!(
1556            note.content.contains("not source lines of code"),
1557            "the denominator caveat travels with the figures"
1558        );
1559        // Config secrets: counts and files, and no key names — a vault note is
1560        // browsed out of context, which is the wrong place for a list that would
1561        // read as a secret scan's output.
1562        assert!(
1563            note.content.contains(
1564                "**4** secret-named config key(s): 3 redacted before storage, 1 \
1565                 declared in code without a value, 0 unredacted."
1566            ),
1567            "{}",
1568            note.content
1569        );
1570        assert!(
1571            note.content
1572                .contains(&format!("- [[{}\\|.env]]", note_name("file:.env"))),
1573            "{}",
1574            note.content
1575        );
1576        assert!(
1577            note.content.contains("not a secret scan")
1578                && note.content.contains("cannot see a hardcoded credential"),
1579            "the limitation travels with the figures: {}",
1580            note.content
1581        );
1582        assert!(
1583            !note.content.contains("[!warning]"),
1584            "no warning when nothing is unredacted: {}",
1585            note.content
1586        );
1587        // A repository link + short-commit permalink note.
1588        assert!(
1589            note.content
1590                .contains("**Repository:** [https://github.com/org/repo](https://github.com/org/repo) · rendered at commit `abcdef012345`"),
1591            "{}",
1592            note.content
1593        );
1594    }
1595
1596    #[test]
1597    fn render_home_omits_density_for_a_graph_with_no_markers() {
1598        // A clean repository has no markers, so there is no density to rank. An
1599        // empty table under a heading reads as "measured, and there is nothing";
1600        // the section is absent instead. Same rule as the coupling table below.
1601        let note = render_home(&VaultSummary {
1602            project: "clean".into(),
1603            total_nodes: 1,
1604            ..VaultSummary::default()
1605        });
1606        assert!(
1607            !note.content.contains("Densest files"),
1608            "no heading without rows: {}",
1609            note.content
1610        );
1611        // The intent-debt section itself still renders — density is an addition
1612        // to it, not a replacement.
1613        assert!(note.content.contains("## Intent debt"));
1614        assert!(note.content.contains("*None recorded.*"));
1615    }
1616
1617    #[test]
1618    fn render_home_omits_config_secrets_rather_than_rendering_zeroes() {
1619        // A row of zeroes under this heading would read as "scanned, and clean" —
1620        // a conclusion the lens cannot support, since a credential under an
1621        // innocuous key name never appears in it. The section is absent instead.
1622        let note = render_home(&VaultSummary {
1623            project: "clean".into(),
1624            total_nodes: 1,
1625            ..VaultSummary::default()
1626        });
1627        assert!(
1628            !note.content.contains("named like secrets"),
1629            "no heading without figures: {}",
1630            note.content
1631        );
1632    }
1633
1634    #[test]
1635    fn render_home_warns_loudly_about_an_unredacted_value() {
1636        // Extraction cannot produce this state, so if it appears something else
1637        // put an unredacted value in the store — and the note must say where to
1638        // look rather than implicating the repository.
1639        let note = render_home(&VaultSummary {
1640            project: "imported".into(),
1641            total_nodes: 1,
1642            config_secrets: Some(ConfigSecretSummary {
1643                secret_named: 1,
1644                redacted: 0,
1645                declared: 0,
1646                unredacted: 1,
1647                files: vec!["imported.env".into()],
1648            }),
1649            ..VaultSummary::default()
1650        });
1651        assert!(
1652            note.content.contains("[!warning]") && note.content.contains("**unredacted**"),
1653            "{}",
1654            note.content
1655        );
1656        assert!(
1657            note.content.contains("came from an import layer"),
1658            "and it points at the importing tool, not the repository: {}",
1659            note.content
1660        );
1661    }
1662
1663    #[test]
1664    fn render_home_omits_coupling_for_a_graph_with_no_calls() {
1665        // A prose-only vault has no `calls` edges. An empty table under a heading
1666        // reads as "measured, and there is nothing" — the section is absent instead.
1667        let note = render_home(&VaultSummary {
1668            project: "docs".into(),
1669            total_nodes: 1,
1670            ..VaultSummary::default()
1671        });
1672        assert!(
1673            !note.content.contains("Most depended-on"),
1674            "no heading without rows: {}",
1675            note.content
1676        );
1677        // The rest of the overview is unaffected.
1678        assert!(note.content.contains("# docs — knowledge graph"));
1679    }
1680
1681    // ---- Workspace vaults (issue #442 part 1) --------------------------------
1682
1683    /// A `Explanation` for `key`, with one outgoing edge to `to`.
1684    fn node_linking_to(key: &str, name: &str, to: &str) -> Explanation {
1685        Explanation {
1686            schema: rto_graph::SCHEMA,
1687            node: NodeSummary {
1688                key: key.into(),
1689                kind: "config_key".into(),
1690                name: name.into(),
1691                path: Some("config.toml".into()),
1692                lang: None,
1693            },
1694            meta: serde_json::Value::Null,
1695            outgoing: vec![EdgeRef {
1696                kind: "links".into(),
1697                provenance: "inferred",
1698                confidence: Some(0.91),
1699                node: to.into(),
1700            }],
1701            incoming: vec![],
1702        }
1703    }
1704
1705    fn members(names: &[&str]) -> std::collections::BTreeSet<String> {
1706        names.iter().map(|s| (*s).to_owned()).collect()
1707    }
1708
1709    /// **Rewritten deliberately under #574.** #570 landed this as "a project
1710    /// scope leaves every note name exactly as it was", and read that two ways at
1711    /// once: `PROJECT` reduces to `note_name`, *and* `note_name` itself does not
1712    /// move. #574 breaks the second half on purpose — the old names were not
1713    /// injective under filename case folding and this repository's vault lost 104
1714    /// notes to it — so the two halves are separated here rather than having
1715    /// expected values quietly updated underneath the old title.
1716    ///
1717    /// What survives is the half #570 was actually about, and it is unweakened:
1718    /// **turning workspace mode on must not rename a project's notes.** Names may
1719    /// move when `note_name` changes, for a reason argued at `note_name`; they may
1720    /// never move because a repository happens to sit inside a configured
1721    /// workspace, because that would happen by inference rather than by a release.
1722    ///
1723    /// The other half of #570's promise — that a project render is byte-identical
1724    /// apart from names — is now [`render_note_is_the_project_scoped_render_byte_for_byte`]
1725    /// and `render_cli`'s end-to-end pair.
1726    #[test]
1727    fn a_project_scope_never_qualifies_a_name() {
1728        // A user's own notes live outside the vault and link into it *by name*
1729        // (#442), so a rename breaks them silently, with no error and nothing to
1730        // grep for. Whatever workspace mode does, `VaultScope::PROJECT` must
1731        // reduce to `note_name` of the bare key.
1732        for key in [
1733            "file:README.md",
1734            "adr:0001",
1735            "sym:rust:src/a.rs#Store",
1736            "extref:other::file:README.md",
1737            "cfgkey:config.toml#serve.addr",
1738        ] {
1739            assert_eq!(
1740                scoped_note_name(&VaultScope::PROJECT, key),
1741                note_name(key),
1742                "single-project name moved for `{key}`"
1743            );
1744            // And the qualified form really is a different name, so the assertion
1745            // above is not vacuously true of every scope.
1746            let ms = members(&["app"]);
1747            assert_ne!(
1748                scoped_note_name(
1749                    &VaultScope {
1750                        project: Some("app"),
1751                        members: &ms,
1752                    },
1753                    key
1754                ),
1755                note_name(key),
1756                "qualification must move the name for `{key}`, or nothing above holds"
1757            );
1758        }
1759    }
1760
1761    #[test]
1762    fn render_note_is_the_project_scoped_render_byte_for_byte() {
1763        let ex = node_linking_to("cfgkey:config.toml#addr", "addr", "sym:rust:a.rs#A");
1764        assert_eq!(
1765            render_note(&ex, Some("https://h/b"), Some("body")),
1766            render_note_scoped(&ex, Some("https://h/b"), Some("body"), &VaultScope::PROJECT),
1767            "the unscoped entry point must stay the scoped one at PROJECT, so the \
1768             two cannot drift apart"
1769        );
1770    }
1771
1772    #[test]
1773    fn each_member_gets_its_own_note_for_the_same_key() {
1774        // The collision the whole feature exists for: node keys are
1775        // repository-relative, so every member's `README.md` is `file:README.md`.
1776        let ms = members(&["api", "sdk"]);
1777        let names: Vec<String> = ["api", "sdk"]
1778            .iter()
1779            .map(|p| {
1780                scoped_note_name(
1781                    &VaultScope {
1782                        project: Some(p),
1783                        members: &ms,
1784                    },
1785                    "file:README.md",
1786                )
1787            })
1788            .collect();
1789        assert_eq!(
1790            names,
1791            [
1792                note_name("api::file:README.md"),
1793                note_name("sdk::file:README.md")
1794            ]
1795        );
1796        assert_ne!(names[0], names[1], "two members must not share one note");
1797    }
1798
1799    /// The two names this feature has, pinned together in one place.
1800    ///
1801    /// They are easy to conflate and were, in this PR, described inconsistently
1802    /// in two doc comments — the **key** is `<project>::<key>` (ADR-0009's
1803    /// cross-repo form, which is why cross-repo links resolve), and the **note
1804    /// name** is [`note_name`] of that key, in which `::` has become `-`. A
1805    /// reader told the wrong one goes looking for a file with `::` in it.
1806    ///
1807    /// Asserting both here means the next description that drifts has something
1808    /// to disagree with, rather than waiting for a reviewer to read two comments
1809    /// side by side.
1810    #[test]
1811    fn the_qualified_key_and_the_note_name_are_different_strings() {
1812        let ms = members(&["app"]);
1813        let scope = VaultScope {
1814            project: Some("app"),
1815            members: &ms,
1816        };
1817        // The key: project-qualified, `::` intact — this is what the graph and
1818        // ADR-0009's external refs use.
1819        let qualified = "app::file:README.md";
1820        // The note name: `note_name` of exactly that key, `::` slugged to `-`,
1821        // the whole hint lowercased, and the key's own hash appended.
1822        assert_eq!(
1823            scoped_note_name(&scope, "file:README.md"),
1824            "app-file-readme.md-a114bde6dcaba1c1"
1825        );
1826        assert_eq!(note_name(qualified), "app-file-readme.md-a114bde6dcaba1c1");
1827        assert!(
1828            !scoped_note_name(&scope, "file:README.md").contains("::"),
1829            "no note name ever contains `::`"
1830        );
1831        // And on disk the stem gains the extension, which is the string a reader
1832        // actually looks for.
1833        let note = render_note_scoped(
1834            &node_with("file:README.md", Some("README.md"), None),
1835            None,
1836            None,
1837            &scope,
1838        );
1839        assert_eq!(note.filename, "app-file-readme.md-a114bde6dcaba1c1.md");
1840    }
1841
1842    /// `_Home` must *show* a name, not spell the form out.
1843    ///
1844    /// The test above pins the distinction in the code. It did not stop the
1845    /// distinction being described wrongly in the same file, because it guards
1846    /// the function and not the sentences: `render_workspace_home` went on
1847    /// writing the pre-#574 form into the `_Home` of every workspace vault
1848    /// v2.0.0 built, and nothing here disagreed with it.
1849    ///
1850    /// So this asserts the property that made that possible is gone — the
1851    /// paragraph now contains a string `note_name` actually produced for a key
1852    /// the workspace really holds, which a hand-written spelling cannot
1853    /// satisfy. It is not a tautology despite both sides calling `note_name`:
1854    /// what it rejects is the *shape* of the old copy, a form written out by
1855    /// hand next to the function that could have rendered it.
1856    ///
1857    /// That the *key* is real is the other half, and the reason the example is
1858    /// drawn from `cross_links` rather than invented from the member list —
1859    /// a name rendered for a node the vault does not hold is a true sentence
1860    /// about a note nobody can open. The empty case is
1861    /// `the_workspace_home_claims_no_example_note_when_it_has_no_real_key`.
1862    #[test]
1863    fn the_workspace_home_names_an_example_note_name_actually_produces() {
1864        let ws = WorkspaceSummary {
1865            name: "platform".into(),
1866            members: vec![member_summary("api", 7), member_summary("sdk", 4)],
1867            cross_links: vec![CrossLink {
1868                from_project: "sdk".into(),
1869                from_key: "cfgkey:config.toml#addr".into(),
1870                from_name: "addr".into(),
1871                kind: "links".into(),
1872                confidence: Some(0.91),
1873                to_qualified: "api::cfgkey:config.toml#addr".into(),
1874                resolves: true,
1875            }],
1876            cross_links_total: 1,
1877        };
1878        let note = render_workspace_home(&ws);
1879
1880        // The source end of the first cross-repo link, rendered through the real
1881        // function. `from_project` is a member and `from_key` is one of its own
1882        // nodes, so this is a note the render writes rather than one the
1883        // sentence assumes.
1884        let expected = format!("{}.md", note_name("sdk::cfgkey:config.toml#addr"));
1885        assert!(
1886            note.content.contains(&expected),
1887            "the naming paragraph must show a real name ({expected}), not a \
1888             hand-written form:\n{}",
1889            note.content
1890        );
1891        // And the key form it is derived *from* is still stated, because that is
1892        // the half a reader needs to look a note up by its frontmatter.
1893        assert!(
1894            note.content.contains("`<project>::<key>`"),
1895            "{}",
1896            note.content
1897        );
1898        // No filename anywhere in the vault carries `::`.
1899        assert!(!expected.contains("::"), "{expected}");
1900    }
1901
1902    /// With no cross-repo links there is no key the renderer can prove is a
1903    /// node, so it must say nothing rather than fabricate one.
1904    ///
1905    /// The example this replaced was `<first member>::file:README.md`, invented
1906    /// from the member list — and membership does not require a README, so
1907    /// `_Home` could assert a note that was never written. That is the very
1908    /// defect this PR exists to fix, one remove away, so the empty case gets an
1909    /// assertion of its own rather than an assumption.
1910    #[test]
1911    fn the_workspace_home_claims_no_example_note_when_it_has_no_real_key() {
1912        let ws = WorkspaceSummary {
1913            name: "platform".into(),
1914            members: vec![member_summary("api", 7), member_summary("sdk", 4)],
1915            cross_links: vec![],
1916            cross_links_total: 0,
1917        };
1918        let note = render_workspace_home(&ws);
1919
1920        assert!(
1921            !note.content.contains("is the note "),
1922            "no cross-repo link means no provable key, so no `Here, X is the \
1923             note Y` claim:\n{}",
1924            note.content
1925        );
1926        // The fabricated form specifically: never emitted, with or without links.
1927        assert!(
1928            !note.content.contains("::file:README.md"),
1929            "{}",
1930            note.content
1931        );
1932        // The rule itself is still stated — only the illustration is absent.
1933        assert!(
1934            note.content.contains("`<project>::<key>`")
1935                && note.content.contains("no filename contains `::`"),
1936            "{}",
1937            note.content
1938        );
1939    }
1940
1941    #[test]
1942    fn a_member_note_declares_which_member_it_came_from() {
1943        let ms = members(&["api"]);
1944        let ex = node_linking_to("cfgkey:config.toml#addr", "addr", "sym:rust:a.rs#A");
1945        let note = render_note_scoped(
1946            &ex,
1947            None,
1948            None,
1949            &VaultScope {
1950                project: Some("api"),
1951                members: &ms,
1952            },
1953        );
1954        assert_eq!(
1955            note.filename,
1956            format!("{}.md", note_name("api::cfgkey:config.toml#addr"))
1957        );
1958        assert!(
1959            note.content.contains("project: \"api\""),
1960            "{}",
1961            note.content
1962        );
1963        assert!(
1964            note.content.contains("- roteiro/project/api"),
1965            "the tag is what filters the graph view to one repository: {}",
1966            note.content
1967        );
1968        // A within-member edge is qualified to the same member, not left bare.
1969        assert!(
1970            note.content
1971                .contains(&format!("→ [[{}]]", note_name("api::sym:rust:a.rs#A"))),
1972            "{}",
1973            note.content
1974        );
1975    }
1976
1977    #[test]
1978    fn a_project_note_declares_no_project() {
1979        let ex = node_linking_to("cfgkey:config.toml#addr", "addr", "sym:rust:a.rs#A");
1980        let note = render_note(&ex, None, None);
1981        assert!(!note.content.contains("project:"), "{}", note.content);
1982        assert!(
1983            !note.content.contains("roteiro/project/"),
1984            "a per-project vault would carry one constant on every note — and \
1985             adding it would change every note's bytes: {}",
1986            note.content
1987        );
1988    }
1989
1990    #[test]
1991    fn a_cross_repo_edge_links_straight_to_the_other_members_note() {
1992        // ADR-0009: the spoke's edge points at a *local placeholder* for the hub's
1993        // node, because store integrity needs both ends in one store. A workspace
1994        // vault holds both, so the link goes to the real note. No new edge — the
1995        // resolver already follows this placeholder at query time.
1996        let ms = members(&["spoke", "hub"]);
1997        let scope = VaultScope {
1998            project: Some("spoke"),
1999            members: &ms,
2000        };
2001        let ex = node_linking_to(
2002            "cfgkey:config.toml#addr",
2003            "addr",
2004            &rto_graph::external_ref_key("hub::cfgkey:config.toml#addr"),
2005        );
2006        let note = render_note_scoped(&ex, None, None, &scope);
2007        assert!(
2008            note.content.contains(&format!(
2009                "→ [[{}]]",
2010                note_name("hub::cfgkey:config.toml#addr")
2011            )),
2012            "the edge must land on the hub's own note: {}",
2013            note.content
2014        );
2015        assert!(
2016            !note.content.contains("extref"),
2017            "and never on the placeholder: {}",
2018            note.content
2019        );
2020        // The same rule decides that the placeholder is not written as a note, so
2021        // the two halves cannot disagree.
2022        assert!(
2023            scope.redirects_external_ref(&rto_graph::external_ref_key(
2024                "hub::cfgkey:config.toml#addr"
2025            ))
2026        );
2027    }
2028
2029    #[test]
2030    fn a_cross_repo_edge_out_of_the_workspace_keeps_its_placeholder() {
2031        // The target repo is not in this vault, so there is no note to point at.
2032        // Redirecting anyway would produce a link that resolves to nothing —
2033        // Obsidian shows that as merely unwritten, which is a worse lie than a
2034        // placeholder that honestly says "elsewhere".
2035        let ms = members(&["spoke"]);
2036        let scope = VaultScope {
2037            project: Some("spoke"),
2038            members: &ms,
2039        };
2040        let key = rto_graph::external_ref_key("elsewhere::cfgkey:config.toml#addr");
2041        assert!(!scope.redirects_external_ref(&key));
2042        let ex = node_linking_to("cfgkey:config.toml#addr", "addr", &key);
2043        let note = render_note_scoped(&ex, None, None, &scope);
2044        assert!(
2045            note.content.contains(&format!(
2046                "→ [[{}]]",
2047                note_name("spoke::extref:elsewhere::cfgkey:config.toml#addr")
2048            )),
2049            "{}",
2050            note.content
2051        );
2052    }
2053
2054    #[test]
2055    fn a_single_project_vault_never_redirects_an_external_ref() {
2056        // No members ⇒ nothing to resolve against, so today's vault keeps rendering
2057        // the placeholder exactly as it does now.
2058        let key = rto_graph::external_ref_key("hub::cfgkey:config.toml#addr");
2059        assert!(!VaultScope::PROJECT.redirects_external_ref(&key));
2060        assert_eq!(
2061            scoped_note_name(&VaultScope::PROJECT, &key),
2062            note_name(&key)
2063        );
2064    }
2065
2066    fn member_summary(project: &str, fan_in: u32) -> VaultSummary {
2067        VaultSummary {
2068            project: project.to_owned(),
2069            total_nodes: 3,
2070            total_edges: 2,
2071            node_counts: vec![("fn".into(), 2)],
2072            edge_provenance: vec![("derived".into(), 2)],
2073            adrs: vec![AdrEntry {
2074                key: "adr:0001".into(),
2075                name: "First".into(),
2076                status: Some("Accepted".into()),
2077            }],
2078            debt: vec![("todo".into(), 4)], // roteiro:ignore
2079            densest_files: vec![DensityEntry {
2080                path: "src/small.rs".into(),
2081                markers: 3,
2082                lines: 120,
2083                per_kloc: 25.0,
2084            }],
2085            config_secrets: None,
2086            most_called: vec![CouplingEntry {
2087                key: "sym:rust:a.rs#helper".into(),
2088                name: "helper".into(),
2089                fan_in,
2090                fan_out: 1,
2091            }],
2092            repo_url: Some(format!("https://github.com/org/{project}")),
2093            commit: Some("abcdef0123456789".into()),
2094        }
2095    }
2096
2097    #[test]
2098    fn the_workspace_home_keeps_every_members_own_aggregates() {
2099        // The promise in issue #442: the existing per-project `_Home` view is a
2100        // *subset* of the workspace one, not a casualty of it. Someone who came for
2101        // their repository's coupling and debt tables must still find them —
2102        // not a workspace total that averages them away.
2103        let ws = WorkspaceSummary {
2104            name: "platform".into(),
2105            members: vec![member_summary("api", 7), member_summary("sdk", 4)],
2106            cross_links: vec![],
2107            cross_links_total: 0,
2108        };
2109        let note = render_workspace_home(&ws);
2110        assert_eq!(note.filename, HOME_NOTE);
2111        assert!(
2112            note.content
2113                .contains("# platform — workspace knowledge graph")
2114        );
2115        // Summed, and the members listed.
2116        assert!(
2117            note.content
2118                .contains("**6 nodes**, **4 edges** across **2** member")
2119        );
2120        assert!(note.content.contains("| [[#api\\|api]] | 3 | 2 |"));
2121
2122        for project in ["api", "sdk"] {
2123            assert!(
2124                note.content.contains(&format!("\n## {project}\n")),
2125                "each member gets its own section"
2126            );
2127        }
2128        // Today's sections, one level deeper, once per member.
2129        for section in [
2130            "### Structure",
2131            "### Provenance",
2132            "### Decisions (ADRs)",
2133            "### Intent debt",
2134            "#### Densest files",
2135            "### Most depended-on",
2136        ] {
2137            assert_eq!(
2138                note.content.matches(section).count(),
2139                2,
2140                "`{section}` must appear once per member: {}",
2141                note.content
2142            );
2143        }
2144        // And every link inside a member's section resolves within that member.
2145        assert!(note.content.contains(&format!(
2146            "**Accepted** — [[{}|First]]",
2147            note_name("api::adr:0001")
2148        )));
2149        assert!(note.content.contains(&format!(
2150            "**Accepted** — [[{}|First]]",
2151            note_name("sdk::adr:0001")
2152        )));
2153        assert!(note.content.contains(&format!(
2154            "[[{}\\|helper]] | 7 |",
2155            note_name("api::sym:rust:a.rs#helper")
2156        )));
2157        assert!(note.content.contains(&format!(
2158            "[[{}\\|src/small.rs]]",
2159            note_name("sdk::file:src/small.rs")
2160        )));
2161    }
2162
2163    #[test]
2164    fn the_workspace_home_renders_cross_repo_links_and_marks_the_ones_it_cannot_follow() {
2165        let ws = WorkspaceSummary {
2166            name: "platform".into(),
2167            members: vec![member_summary("api", 7), member_summary("sdk", 4)],
2168            cross_links: vec![
2169                CrossLink {
2170                    from_project: "sdk".into(),
2171                    from_key: "cfgkey:config.toml#addr".into(),
2172                    from_name: "addr".into(),
2173                    kind: "links".into(),
2174                    confidence: Some(0.91),
2175                    to_qualified: "api::cfgkey:config.toml#addr".into(),
2176                    resolves: true,
2177                },
2178                CrossLink {
2179                    from_project: "sdk".into(),
2180                    from_key: "cfgkey:config.toml#other".into(),
2181                    from_name: "other".into(),
2182                    kind: "links".into(),
2183                    confidence: None,
2184                    to_qualified: "absent::cfgkey:config.toml#other".into(),
2185                    resolves: false,
2186                },
2187            ],
2188            cross_links_total: 2,
2189        };
2190        let note = render_workspace_home(&ws);
2191        // Resolvable: a link to the other member's note, with its confidence.
2192        assert!(
2193            note.content.contains(&format!(
2194                "| [[{}\\|addr]] | sdk | [[{}\\|api::cfgkey:config.toml#addr]] | links (0.91) |",
2195                note_name("sdk::cfgkey:config.toml#addr"),
2196                note_name("api::cfgkey:config.toml#addr"),
2197            )),
2198            "{}",
2199            note.content
2200        );
2201        // Outside the workspace: stated as such, never as a wikilink — Obsidian
2202        // renders a link to a missing note as one that is merely unwritten.
2203        assert!(
2204            note.content
2205                .contains("`absent::cfgkey:config.toml#other` *(outside this workspace)*"),
2206            "{}",
2207            note.content
2208        );
2209        assert!(
2210            !note.content.contains("[[absent-"),
2211            "a dangling wikilink would read as a note someone forgot to write: {}",
2212            note.content
2213        );
2214    }
2215
2216    #[test]
2217    fn the_workspace_home_says_when_it_has_truncated_the_cross_links() {
2218        // A capped table that does not say it is capped reads as the whole set.
2219        let ws = WorkspaceSummary {
2220            name: "platform".into(),
2221            members: vec![member_summary("api", 7)],
2222            cross_links: vec![CrossLink {
2223                from_project: "api".into(),
2224                from_key: "cfgkey:config.toml#addr".into(),
2225                from_name: "addr".into(),
2226                kind: "links".into(),
2227                confidence: None,
2228                to_qualified: "api::cfgkey:config.toml#addr".into(),
2229                resolves: true,
2230            }],
2231            cross_links_total: 40,
2232        };
2233        let note = render_workspace_home(&ws);
2234        assert!(note.content.contains("Showing 1 of 40"), "{}", note.content);
2235        assert!(note.content.contains("roteiro links --matrix"));
2236    }
2237
2238    #[test]
2239    fn a_workspace_with_no_cross_repo_links_says_why_rather_than_showing_nothing() {
2240        let ws = WorkspaceSummary {
2241            name: "platform".into(),
2242            members: vec![member_summary("api", 7)],
2243            cross_links: vec![],
2244            cross_links_total: 0,
2245        };
2246        let note = render_workspace_home(&ws);
2247        assert!(note.content.contains("## Cross-repo links"));
2248        assert!(
2249            note.content.contains("links --infer --write"),
2250            "an empty section must name what would fill it, or it reads as \
2251             \"these repos are unrelated\": {}",
2252            note.content
2253        );
2254        // Singular, because getting this wrong on a one-member workspace is the
2255        // kind of thing nobody notices until it ships.
2256        assert!(note.content.contains("**1** member repository."));
2257    }
2258
2259    // ---- YAML frontmatter escaping -------------------------------------------
2260
2261    /// Parse a note's frontmatter block with a **real** YAML parser and return
2262    /// `field`'s value, or the parse error.
2263    ///
2264    /// Every assertion below goes through this rather than checking the emitted
2265    /// bytes. An escaper that is wrong in a self-consistent way passes a
2266    /// byte-comparison — that is precisely how `"foo\bar"` survived: it looks
2267    /// exactly like what was asked for, and means something else.
2268    fn frontmatter_field(note: &str, field: &str) -> Result<Option<String>, String> {
2269        let block = note
2270            .strip_prefix("---\n")
2271            .and_then(|rest| rest.split_once("\n---\n"))
2272            .map(|(block, _)| block)
2273            .expect("note must open with a frontmatter block");
2274        let docs = yaml_rust2::YamlLoader::load_from_str(block).map_err(|e| e.to_string())?;
2275        Ok(docs[0][field].as_str().map(ToOwned::to_owned))
2276    }
2277
2278    /// A node whose key, path and language are whatever the test needs.
2279    fn node_with(key: &str, path: Option<&str>, lang: Option<&str>) -> Explanation {
2280        Explanation {
2281            schema: rto_graph::SCHEMA,
2282            node: NodeSummary {
2283                key: key.into(),
2284                kind: "fn".into(),
2285                name: "n".into(),
2286                path: path.map(ToOwned::to_owned),
2287                lang: lang.map(ToOwned::to_owned),
2288            },
2289            meta: serde_json::Value::Null,
2290            outgoing: vec![],
2291            incoming: vec![],
2292        }
2293    }
2294
2295    /// The three measured failure modes of the escaping this replaced, each
2296    /// asserted on the **parsed** value.
2297    ///
2298    /// Before the fix: `foo\bar` parsed back as `foo<BS>ar` (silently six
2299    /// characters, not seven), and the other two made the whole block
2300    /// unparseable — which in Obsidian costs the note *every* property, with no
2301    /// error shown.
2302    #[test]
2303    fn a_backslash_or_quote_in_a_path_still_parses_back_to_itself() {
2304        for path in [
2305            r"foo\bar",     // `\b` was YAML's backspace escape: silent corruption
2306            r"foo\dir",     // `\d` is not a YAML escape at all: parse error
2307            "say\"hi\".rs", // an unescaped `"` ended the scalar early: parse error
2308            r"a\\b",
2309            "trailing-backslash\\",
2310        ] {
2311            let note = render_note(&node_with("file:x", Some(path), None), None, None);
2312            assert_eq!(
2313                frontmatter_field(&note.content, "path"),
2314                Ok(Some(path.to_owned())),
2315                "path {path:?} must round-trip"
2316            );
2317        }
2318    }
2319
2320    /// `key:` is not hypothetical for this: node keys already carry `:` and `#`,
2321    /// and a symbol name can contain a quotation mark.
2322    #[test]
2323    fn a_node_key_round_trips_whatever_punctuation_it_carries() {
2324        for key in [
2325            "sym:rust:src/a.rs#Store",
2326            r"sym:rust:src\weird.rs#Thing",
2327            "sym:rust:a.rs#say\"hi\"",
2328            "cfgkey:config.toml#serve.addr",
2329        ] {
2330            let note = render_note(&node_with(key, None, None), None, None);
2331            assert_eq!(
2332                frontmatter_field(&note.content, "key"),
2333                Ok(Some(key.to_owned())),
2334                "key {key:?} must round-trip"
2335            );
2336        }
2337        // The old rule turned a `"` into an apostrophe, so the note reported a key
2338        // that was not the node's key — parseable, and wrong.
2339        let note = render_note(
2340            &node_with("sym:rust:a.rs#say\"hi\"", None, None),
2341            None,
2342            None,
2343        );
2344        assert!(
2345            !note.content.contains("say'hi'"),
2346            "a quotation mark must be escaped, not rewritten: {}",
2347            note.content
2348        );
2349    }
2350
2351    /// A member directory name is a path component, so it reaches the same rule.
2352    #[test]
2353    fn a_member_project_name_round_trips() {
2354        let ms: std::collections::BTreeSet<String> =
2355            std::iter::once(r"odd\name".to_owned()).collect();
2356        let note = render_note_scoped(
2357            &node_with("file:x", None, None),
2358            None,
2359            None,
2360            &VaultScope {
2361                project: Some(r"odd\name"),
2362                members: &ms,
2363            },
2364        );
2365        assert_eq!(
2366            frontmatter_field(&note.content, "project"),
2367            Ok(Some(r"odd\name".to_owned()))
2368        );
2369    }
2370
2371    /// The **bare** fields are the other half of the same class, and were missed
2372    /// by the review that found the quoted ones: `status` is written unquoted, and
2373    /// `roteiro load` installs a caller-supplied artifact whose nodes carry
2374    /// whatever they carry.
2375    #[test]
2376    fn a_bare_field_is_quoted_only_when_being_bare_would_change_it() {
2377        let with_status = |status: &str| {
2378            let mut ex = node_with("adr:0001", None, None);
2379            ex.meta = serde_json::json!({ "status": status });
2380            render_note(&ex, None, None)
2381        };
2382
2383        // Would be a parse error bare; would silently truncate bare.
2384        for status in [
2385            "Accepted: superseded by 0012",
2386            "Accepted # pending",
2387            "{draft}",
2388            "",
2389        ] {
2390            let note = with_status(status);
2391            assert_eq!(
2392                frontmatter_field(&note.content, "status"),
2393                Ok(Some(status.to_owned())),
2394                "status {status:?} must round-trip"
2395            );
2396        }
2397
2398        // …and a safe one stays bare, which is what keeps an existing vault's
2399        // bytes unchanged.
2400        let note = with_status("Accepted");
2401        assert!(
2402            note.content.contains("\nstatus: Accepted\n"),
2403            "a plain-safe status must not gain quotes: {}",
2404            note.content
2405        );
2406    }
2407
2408    /// `no` is Norwegian, and a bare `no` reads as `false` to a YAML **1.1**
2409    /// parser.
2410    ///
2411    /// The only assertion here that pins emitted bytes, and deliberately so:
2412    /// `yaml-rust2` implements YAML 1.2, whose core schema resolves a bare `no`
2413    /// to the *string* `no`, so a round-trip through this test's own oracle
2414    /// cannot see the problem — it passes either way. The exposure is to the
2415    /// parser on the other side, and Obsidian's is not this one. Quoting costs
2416    /// two characters on a value that never occurs here; guessing which YAML
2417    /// version every downstream reader implements does not seem like the better
2418    /// bet.
2419    #[test]
2420    fn a_language_that_spells_a_yaml_boolean_is_quoted() {
2421        let note = render_note(&node_with("file:x", None, Some("no")), None, None);
2422        assert!(
2423            note.content.contains("\nlang: \"no\"\n"),
2424            "a bare `no` is `false` to a 1.1 parser and must be quoted: {}",
2425            note.content
2426        );
2427        assert_eq!(
2428            frontmatter_field(&note.content, "lang"),
2429            Ok(Some("no".to_owned())),
2430            "and it must still read back as the string: {}",
2431            note.content
2432        );
2433        // And an ordinary language is untouched.
2434        let rust = render_note(&node_with("file:x", None, Some("rust")), None, None);
2435        assert!(rust.content.contains("\nlang: rust\n"), "{}", rust.content);
2436    }
2437
2438    /// Control characters and the separators some parsers fold as line breaks.
2439    #[test]
2440    fn control_characters_cannot_break_out_of_the_block() {
2441        for path in [
2442            "a\nb",
2443            "a\tb",
2444            "a\u{0}b",
2445            "a\u{2028}b",
2446            "a\u{7f}b",
2447            "a\u{85}b",
2448        ] {
2449            let note = render_note(&node_with("file:x", Some(path), None), None, None);
2450            assert_eq!(
2451                frontmatter_field(&note.content, "path"),
2452                Ok(Some(path.to_owned())),
2453                "path {path:?} must round-trip"
2454            );
2455            // A raw newline would end the scalar and inject a sibling key.
2456            assert_eq!(
2457                note.content.matches("\npath: ").count(),
2458                1,
2459                "the value must stay on one line: {}",
2460                note.content
2461            );
2462        }
2463    }
2464
2465    /// The escaping is *only* an escaping: for a value with nothing to escape it
2466    /// must emit the same bytes it always did, or #442's promise that a
2467    /// single-project vault is byte-identical does not hold.
2468    #[test]
2469    fn an_ordinary_value_is_emitted_exactly_as_before() {
2470        let note = render_note(
2471            &node_with("sym:rust:src/a.rs#Store", Some("src/a.rs"), Some("rust")),
2472            None,
2473            None,
2474        );
2475        assert!(
2476            note.content
2477                .contains("\nkey: \"sym:rust:src/a.rs#Store\"\n")
2478        );
2479        assert!(note.content.contains("\nkind: fn\n"));
2480        assert!(note.content.contains("\npath: \"src/a.rs\"\n"));
2481        assert!(note.content.contains("\nlang: rust\n"));
2482    }
2483
2484    /// The plain-style decision is checked against a real parser rather than
2485    /// against itself: whatever `is_plain_safe` accepts must actually round-trip
2486    /// bare, and whatever it rejects must round-trip quoted.
2487    #[test]
2488    fn the_plain_style_decision_agrees_with_a_real_yaml_parser() {
2489        for value in [
2490            "fn",
2491            "config_key",
2492            "rust",
2493            "Accepted",
2494            "a.b",
2495            "a/b",
2496            "a-b_c",
2497            "no",
2498            "yes",
2499            "true",
2500            "null",
2501            "y",
2502            "N",
2503            "",
2504            " lead",
2505            "trail ",
2506            "a: b",
2507            "a #c",
2508            "{x}",
2509            "[x]",
2510            "*x",
2511            "&x",
2512            "!x",
2513            "#x",
2514            ">x",
2515            "|x",
2516            "%x",
2517            "@x",
2518            "`x",
2519            "\"x",
2520            "'x",
2521            ",x",
2522            "123",
2523            "1.5",
2524            "-x",
2525            ".x",
2526            "a\\b",
2527        ] {
2528            let emitted = super::yaml_scalar(value);
2529            let doc = format!("v: {emitted}");
2530            let parsed = yaml_rust2::YamlLoader::load_from_str(&doc)
2531                .unwrap_or_else(|e| panic!("{value:?} emitted {emitted:?}: {e}"));
2532            assert_eq!(
2533                parsed[0]["v"].as_str(),
2534                Some(value),
2535                "{value:?} emitted as {emitted:?} did not round-trip"
2536            );
2537        }
2538    }
2539}