Skip to main content

dbmd_core/
stats.rs

1//! `stats` — store overview, **computed on demand** (a SWEEP, like `du` —
2//! never a maintained or precomputed cache).
3//!
4//! Serves both the human (how big is my brain, what's the shape) and the agent
5//! (orientation). Deliberately excludes graph density / degree / top-linked
6//! analytics — low agent value, and a human who wants graph metrics opens the
7//! store in Obsidian, so we never build the full graph just for stats.
8
9use std::collections::{BTreeMap, HashSet};
10use std::path::{Path, PathBuf};
11
12use regex::Regex;
13
14use crate::store::{Layer, Store};
15
16/// A point-in-time overview of a store. Pure data; the CLI formats it to text
17/// or JSON.
18#[derive(Debug, Clone, Default, PartialEq)]
19pub struct Stats {
20    /// Total content-file count across all layers.
21    pub total_files: usize,
22    /// File count per layer.
23    pub files_per_layer: BTreeMap<Layer, usize>,
24    /// Total size on disk, in bytes.
25    pub total_size_bytes: u64,
26    /// Count per `type:` value (the type distribution).
27    pub type_distribution: BTreeMap<String, usize>,
28    /// Number of orphan files (no incoming and no outgoing wiki-links).
29    pub orphan_count: usize,
30    /// Number of broken wiki-links (target file doesn't exist).
31    pub broken_link_count: usize,
32    /// Top types by count, descending (ties broken by type name ascending).
33    pub top_types: Vec<(String, usize)>,
34}
35
36/// How many entries [`Stats::top_types`] holds.
37const TOP_TYPES_LIMIT: usize = 10;
38
39/// One content file discovered by the SWEEP, with everything `stats` needs:
40/// where it lives, how big it is, its declared `type`, and the wiki-link
41/// targets it emits (store-relative, `.md` stripped, short-form excluded).
42struct FileFacts {
43    /// Store-relative path *without* the `.md` extension — the node id used to
44    /// resolve wiki-links and detect orphans.
45    node_id: PathBuf,
46    /// The layer this file lives under.
47    layer: Layer,
48    /// File size on disk, in bytes.
49    size_bytes: u64,
50    /// The declared `type:`, if the frontmatter has one.
51    type_: Option<String>,
52    /// Every wiki-link target this file emits, store-relative with any trailing
53    /// `.md` stripped, in source order (not deduped, short-form included).
54    /// Resolved against the complete node set in a second pass.
55    raw_targets: Vec<PathBuf>,
56}
57
58impl FileFacts {
59    /// The subset of [`raw_targets`](FileFacts::raw_targets) that could resolve
60    /// to a store node: full store-relative paths. Short-form targets (no `/`)
61    /// are dropped — they're a `WIKI_LINK_SHORT_FORM` validation error, not a
62    /// graph edge, so stats neither counts them as broken nor lets them wire a
63    /// file out of orphan status.
64    fn resolvable_targets(&self) -> impl Iterator<Item = &PathBuf> {
65        self.raw_targets.iter().filter(|t| is_full_path(t))
66    }
67}
68
69/// **SWEEP.** Walk the store once and compute its [`Stats`]. Run occasionally
70/// (overview / orientation), never on the interactive loop.
71pub fn compute(store: &Store) -> crate::Result<Stats> {
72    let link_re = wiki_link_regex();
73
74    // First pass: walk every layer once, recording per-file facts and the set
75    // of node ids that exist on disk. Link resolution waits for the second
76    // pass, once every node's existence is known.
77    let mut existing_nodes: HashSet<PathBuf> = HashSet::new();
78    let mut facts: Vec<FileFacts> = Vec::new();
79
80    for layer in Layer::all() {
81        let layer_root = store.root.join(layer_dir_name(layer));
82        for abs in walk_layer_content_files(&layer_root)? {
83            let rel = abs.strip_prefix(&store.root).unwrap_or(&abs).to_path_buf();
84            let node_id = strip_md(&rel);
85            existing_nodes.insert(node_id.clone());
86
87            let size_bytes = std::fs::metadata(&abs).map(|m| m.len()).unwrap_or(0);
88            let text = std::fs::read_to_string(&abs).unwrap_or_default();
89            let type_ = parse_type(&text);
90            let raw_targets = extract_link_targets(&text, &link_re);
91
92            facts.push(FileFacts {
93                node_id,
94                layer,
95                size_bytes,
96                type_,
97                raw_targets,
98            });
99        }
100    }
101
102    // Second pass: classify every file's links against the complete node set,
103    // counting broken links (full-path targets with no file on disk) and
104    // recording which nodes receive an incoming edge. Short-form targets are a
105    // validation error elsewhere, not a stats edge, so they're skipped here:
106    // they neither wire a file in nor count as broken.
107    let mut stats = Stats::default();
108    let mut linked_to: HashSet<PathBuf> = HashSet::new();
109    for file in &facts {
110        for target in file.resolvable_targets() {
111            // A self-link is not a graph edge — skip it (matches `graph::orphans`,
112            // so the two surfaces agree on whether a self-only-linking file is an
113            // orphan). It is neither incoming nor broken.
114            if target == &file.node_id {
115                continue;
116            }
117            if existing_nodes.contains(target) {
118                linked_to.insert(target.clone());
119            } else if target_resolves_on_disk(&store.root, target) {
120                // A link to an existing non-`.md` source artifact (a `.eml`,
121                // `.pdf`, …) is a live edge, not a broken one — `sources/` holds
122                // such files by design and `graph` resolves them on disk. The
123                // target has no `.md` node, so it can't be `linked_to` (no `.md`
124                // file is un-orphaned by it), but it must NOT be counted broken.
125            } else {
126                // Broken links count occurrences, not distinct targets.
127                stats.broken_link_count += 1;
128            }
129        }
130    }
131
132    // Third pass: roll the per-file facts up into the aggregate Stats. A file is
133    // an orphan iff it has neither a resolvable outgoing edge nor an incoming one.
134    for file in &facts {
135        stats.total_files += 1;
136        *stats.files_per_layer.entry(file.layer).or_insert(0) += 1;
137        stats.total_size_bytes += file.size_bytes;
138
139        if let Some(t) = &file.type_ {
140            *stats.type_distribution.entry(t.clone()).or_insert(0) += 1;
141        }
142
143        let has_outgoing = file.resolvable_targets().any(|t| {
144            t != &file.node_id
145                && (existing_nodes.contains(t) || target_resolves_on_disk(&store.root, t))
146        });
147        let has_incoming = linked_to.contains(&file.node_id);
148        if !has_outgoing && !has_incoming {
149            stats.orphan_count += 1;
150        }
151    }
152
153    stats.top_types = top_types(&stats.type_distribution, TOP_TYPES_LIMIT);
154
155    Ok(stats)
156}
157
158/// On-disk folder name for a layer. Local copy so `stats` doesn't couple to
159/// [`Layer::dir_name`].
160fn layer_dir_name(layer: Layer) -> &'static str {
161    match layer {
162        Layer::Sources => "sources",
163        Layer::Records => "records",
164    }
165}
166
167/// Recursively collect the `.md` **content** files under one layer root,
168/// skipping hidden entries (`.git`, dotfiles), the layer's immediate `log/`
169/// archive directory, and the `index.md` catalog meta files. Returns absolute
170/// paths. A missing layer root yields an empty list (a store need not have
171/// both layers).
172///
173/// Only an immediate child of the layer named `log` (`sources/log/`) is the
174/// rotation-archive directory and skipped — matching `render::tree`, which
175/// skips `log` only as an immediate layer child, and the indexer, which indexes
176/// `log` dirs nested deeper. A directory named `log` nested under a type-folder
177/// (`sources/emails/log/`) is ordinary content and is counted, so stats agrees
178/// with `tree` / `index` / `query` instead of making the subtree invisible.
179fn walk_layer_content_files(layer_root: &Path) -> crate::Result<Vec<PathBuf>> {
180    let mut out = Vec::new();
181    if !layer_root.is_dir() {
182        return Ok(out);
183    }
184    let walker = walkdir::WalkDir::new(layer_root)
185        .into_iter()
186        .filter_entry(|e| {
187            // Skip hidden dirs/files. `depth()` is relative to the layer root
188            // (root = 0), so the layer's immediate `log/` archive is depth 1.
189            let name = e.file_name().to_string_lossy();
190            if name.starts_with('.') {
191                return false;
192            }
193            if e.file_type().is_dir() && name == "log" && e.depth() == 1 {
194                return false;
195            }
196            true
197        });
198    for entry in walker {
199        let entry = entry.map_err(|e| {
200            crate::Error::Io(
201                e.into_io_error()
202                    .unwrap_or_else(|| std::io::Error::other("walk error")),
203            )
204        })?;
205        if !entry.file_type().is_file() {
206            continue;
207        }
208        let path = entry.path();
209        let name = entry.file_name().to_string_lossy();
210        // Content files are `.md`; `index.md` is a meta catalog file, not
211        // content, and `index.jsonl` / other sidecars aren't `.md` at all.
212        if !name.ends_with(".md") || name == "index.md" {
213            continue;
214        }
215        out.push(path.to_path_buf());
216    }
217    out.sort();
218    Ok(out)
219}
220
221/// The wiki-link matcher: `[[target]]` or `[[target|display]]`. Captures the
222/// target (group 1), excluding `]` and `|`. Anchored on the literal brackets so
223/// it ignores `[markdown](links)`.
224fn wiki_link_regex() -> Regex {
225    // `[^\[\]|]+` keeps the target free of brackets and the display pipe.
226    Regex::new(r"\[\[([^\[\]|]+)(?:\|[^\]]*)?\]\]").expect("static wiki-link regex is valid")
227}
228
229/// Every wiki-link target in a file's full text (frontmatter + body), trimmed,
230/// with any trailing `.md` removed. Order-preserving; not deduped.
231///
232/// Fenced code blocks (```/~~~) are skipped, mirroring
233/// `validate::extract_wiki_links`: a `[[...]]` that lives only inside a code
234/// fence is illustrative syntax in a doc, not a graph edge, so stats must not
235/// count it as broken or use it to un-orphan a file. (Frontmatter never carries
236/// code fences, so this scan stays line-based over the whole file without
237/// dropping the frontmatter links stats deliberately counts as edges.)
238fn extract_link_targets(text: &str, re: &Regex) -> Vec<PathBuf> {
239    let mut out = Vec::new();
240    // Track the open fence as `(fence byte, run length)`, not a single boolean:
241    // an inner fence of the *other* character (a `~~~` line inside an open ```
242    // block, or vice versa) — or a shorter run — is content, and must NOT close
243    // the block. A naive toggle inverts the fence state on such a line and then
244    // mis-classifies every link for the rest of the file. Mirrors `render`'s
245    // `opening_fence` / `is_closing_fence`.
246    let mut fence: Option<(u8, usize)> = None;
247    for line in text.lines() {
248        let content = line.trim_end_matches(['\n', '\r']);
249        if let Some(f) = fence {
250            if is_closing_fence(content, f) {
251                fence = None;
252            }
253            continue;
254        }
255        if let Some(opened) = opening_fence(content) {
256            fence = Some(opened);
257            continue;
258        }
259        for cap in re.captures_iter(line) {
260            if let Some(m) = cap.get(1) {
261                let raw = m.as_str().trim();
262                out.push(strip_md(Path::new(raw)));
263            }
264        }
265    }
266    out
267}
268
269/// If `line` opens a fenced code block, return its `(fence byte, run length)`.
270/// A fence is at least three backticks or tildes, with up to three leading
271/// spaces of indentation. Mirrors `render::opening_fence`.
272fn opening_fence(line: &str) -> Option<(u8, usize)> {
273    let indent = line.len() - line.trim_start_matches(' ').len();
274    if indent > 3 {
275        return None;
276    }
277    let rest = &line[indent..];
278    let byte = rest.bytes().next()?;
279    if byte != b'`' && byte != b'~' {
280        return None;
281    }
282    let run = rest.len() - rest.trim_start_matches(byte as char).len();
283    if run < 3 {
284        return None;
285    }
286    // A backtick fence's info string may not itself contain a backtick.
287    if byte == b'`' && rest[run..].contains('`') {
288        return None;
289    }
290    Some((byte, run))
291}
292
293/// True if `line` closes the currently open fence `(byte, len)`: same fence
294/// char, a run at least as long, and nothing else but trailing whitespace.
295/// Mirrors `render::is_closing_fence`.
296fn is_closing_fence(line: &str, fence: (u8, usize)) -> bool {
297    let (byte, open_len) = fence;
298    let indent = line.len() - line.trim_start_matches(' ').len();
299    if indent > 3 {
300        return false;
301    }
302    let rest = &line[indent..];
303    let run = rest.len() - rest.trim_start_matches(byte as char).len();
304    if run < open_len {
305        return false;
306    }
307    rest[run..].trim().is_empty()
308}
309
310/// Drop a trailing `.md` from a path, leaving everything else intact.
311fn strip_md(path: &Path) -> PathBuf {
312    let s = path.to_string_lossy();
313    match s.strip_suffix(".md") {
314        Some(stem) => PathBuf::from(stem),
315        None => path.to_path_buf(),
316    }
317}
318
319/// True if a wiki-link target is a full store-relative path: it has a path
320/// separator AND its first segment is a recognized layer (`sources`/`records`/
321/// `wiki`) with a non-empty remainder. Short-form targets like `sarah-chen`
322/// are false, and so are non-layer multi-segment targets like
323/// `contacts/sarah-chen` (a missing layer prefix). Doctrine: only true
324/// store-relative paths resolve to a node.
325///
326/// This mirrors `validate::is_full_store_path` so `stats.broken_link_count`
327/// agrees with `validate`'s `WIKI_LINK_BROKEN` total: a non-layer target like
328/// `[[contacts/sarah]]` is a short-form error in `validate` (never broken), and
329/// must likewise be excluded here rather than counted as a broken edge.
330fn is_full_path(target: &Path) -> bool {
331    let mut parts = target.components();
332    let first = match parts.next() {
333        Some(std::path::Component::Normal(s)) => s.to_string_lossy(),
334        _ => return false,
335    };
336    let has_rest = parts.next().is_some();
337    matches!(first.as_ref(), "sources" | "records") && has_rest
338}
339
340/// True if `target` stays inside the store: every component is `Normal` (a
341/// `CurDir` `.` is harmless and allowed), with no `..` (`ParentDir`), absolute
342/// (`RootDir`), or platform-prefix component. Mirrors
343/// `graph::is_within_store_target` and validate's `is_safe_store_relative_path`,
344/// so the containment decision is identical across the three surfaces. Used to
345/// gate any on-disk probe in [`target_resolves_on_disk`] before a `join`.
346fn is_within_store_target(target: &Path) -> bool {
347    target.components().all(|c| {
348        matches!(
349            c,
350            std::path::Component::Normal(_) | std::path::Component::CurDir
351        )
352    })
353}
354
355/// True if a full-path wiki-link `target` (already `.md`-stripped, store-
356/// relative) resolves to a real **non-`.md`** file on disk — a source artifact
357/// like a `.eml` or `.pdf` under `sources/`. Called only after the `.md` node
358/// set has already been checked, so this exists to reconcile stats with `graph`
359/// (which resolves on disk) and `validate`: a link to an existing source file
360/// is a live edge, never a broken link or an orphan-maker.
361///
362/// Two on-disk shapes are recognized, mirroring `graph::resolve_existing` plus
363/// the bare-stem case sources use:
364///
365/// - the target as written is itself a real file (`[[sources/emails/msg.eml]]`
366///   → `sources/emails/msg.eml`);
367/// - the target is a bare stem and a sibling file shares that stem with a
368///   non-`.md` extension (`[[sources/emails/msg]]` → `sources/emails/msg.eml`).
369///
370/// A bare `.md` target is *not* handled here (an existing `.md` file is already
371/// a node in `existing_nodes`); this is strictly the non-`.md` source case.
372///
373/// **Containment gate.** A target that escapes the store root (any `..`,
374/// absolute, or platform-prefix component) is never probed: it returns `false`
375/// before any `join`/`is_file`/`read_dir`, so `[[sources/../../secret]]` can
376/// never reach the filesystem as a live edge or existence oracle outside the
377/// store. This mirrors `graph::is_within_store_target` and validate's
378/// `is_safe_store_relative_path` (which reject `..` before any probe), keeping
379/// the broken-link surface in agreement: an escaping target is counted broken
380/// (validate's `WIKI_LINK_BROKEN`), never silently treated as resolved.
381fn target_resolves_on_disk(store_root: &Path, target: &Path) -> bool {
382    // Reject any non-`Normal` component (`..`, RootDir, Prefix) up front — never
383    // let a wiki-link turn a stats probe into a filesystem escape.
384    if !is_within_store_target(target) {
385        return false;
386    }
387    // The target as written points at a real file (e.g. an explicit `.eml`).
388    let literal = store_root.join(target);
389    if literal.is_file() {
390        return true;
391    }
392    // Bare-stem case: look for a sibling `<stem>.<ext>` with a non-`.md`
393    // extension in the target's parent directory. Restricted to the bare form
394    // (no extension on the target) so an explicit but missing `.pdf` link still
395    // reads as broken rather than silently matching a different file.
396    if target.extension().is_some() {
397        return false;
398    }
399    let stem = match target.file_name() {
400        Some(name) => name,
401        None => return false,
402    };
403    let parent_abs = store_root.join(match target.parent() {
404        Some(p) => p,
405        None => return false,
406    });
407    let entries = match std::fs::read_dir(&parent_abs) {
408        Ok(e) => e,
409        Err(_) => return false,
410    };
411    for entry in entries.flatten() {
412        let path = entry.path();
413        if !path.is_file() {
414            continue;
415        }
416        // Same stem, and an extension that is present and not `.md`.
417        if path.file_stem() == Some(stem) {
418            match path.extension().and_then(|e| e.to_str()) {
419                Some("md") | None => continue,
420                Some(_) => return true,
421            }
422        }
423    }
424    false
425}
426
427/// Read the `type:` value from a file's leading YAML frontmatter block, if the
428/// file has one. Returns `None` when there's no frontmatter or no `type` key.
429/// Self-contained (does not route through the crate's parser): split on the
430/// `---` fences, parse the block as a YAML mapping, read `type` as a string.
431fn parse_type(text: &str) -> Option<String> {
432    let yaml = frontmatter_block(text)?;
433    let value: serde_norway::Value = serde_norway::from_str(&yaml).ok()?;
434    let mapping = value.as_mapping()?;
435    let type_val = mapping.get(serde_norway::Value::String("type".to_string()))?;
436    let s = type_val.as_str()?.trim();
437    if s.is_empty() {
438        None
439    } else {
440        Some(s.to_string())
441    }
442}
443
444/// Extract the raw YAML between a leading `---` fence and its closing `---`.
445/// The opening fence must be the very first line of the file (the universal
446/// frontmatter contract: frontmatter is the first thing in the file).
447fn frontmatter_block(text: &str) -> Option<String> {
448    // Normalize away a leading BOM, but require `---` as the first line.
449    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
450    let mut lines = text.lines();
451    let first = lines.next()?;
452    if first.trim_end() != "---" {
453        return None;
454    }
455    let mut body = String::new();
456    for line in lines {
457        if line.trim_end() == "---" {
458            return Some(body);
459        }
460        body.push_str(line);
461        body.push('\n');
462    }
463    // No closing fence: not a valid frontmatter block.
464    None
465}
466
467/// Sort a type distribution into the top `limit` types by count descending,
468/// ties broken by type name ascending.
469fn top_types(dist: &BTreeMap<String, usize>, limit: usize) -> Vec<(String, usize)> {
470    let mut pairs: Vec<(String, usize)> = dist.iter().map(|(k, v)| (k.clone(), *v)).collect();
471    // BTreeMap iteration is already name-ascending; a stable sort by count
472    // descending therefore yields (count desc, name asc).
473    pairs.sort_by_key(|p| std::cmp::Reverse(p.1));
474    pairs.truncate(limit);
475    pairs
476}
477
478#[cfg(test)]
479mod tests {
480    use super::*;
481    use crate::parser::Config;
482    use std::fs;
483    use tempfile::TempDir;
484
485    /// Build a `Store` rooted at a fresh tempdir with an empty `DB.md` marker.
486    /// Bypasses `Store::open` by constructing the struct directly —
487    /// `stats::compute` only reads `store.root`.
488    fn temp_store() -> (TempDir, Store) {
489        let dir = TempDir::new().expect("tempdir");
490        fs::write(dir.path().join("DB.md"), "---\ntype: db-md\n---\n").expect("write DB.md");
491        let store = Store {
492            root: dir.path().to_path_buf(),
493            config: Config::default(),
494        };
495        (dir, store)
496    }
497
498    /// Like [`temp_store`], but roots the store one level *inside* the tempdir
499    /// (`<tempdir>/store`) so `store.root.parent()` is the test's own private
500    /// tempdir rather than the shared OS temp root. Tests that plant a file
501    /// "above the store root" must use this — writing into `store.root.parent()`
502    /// of a top-level `TempDir` lands in `$TMPDIR`, which is shared across every
503    /// parallel test (and across test binaries under `cargo test --workspace`),
504    /// so two such tests collide on the same path and race.
505    fn temp_store_nested() -> (TempDir, Store) {
506        let dir = TempDir::new().expect("tempdir");
507        let root = dir.path().join("store");
508        fs::create_dir_all(&root).expect("create store root");
509        fs::write(root.join("DB.md"), "---\ntype: db-md\n---\n").expect("write DB.md");
510        let store = Store {
511            root,
512            config: Config::default(),
513        };
514        (dir, store)
515    }
516
517    /// Write a content file at a store-relative path, creating parent dirs.
518    fn write_rel(store: &Store, rel: &str, contents: &str) {
519        let abs = store.root.join(rel);
520        if let Some(parent) = abs.parent() {
521            fs::create_dir_all(parent).expect("mkdir parents");
522        }
523        fs::write(abs, contents).expect("write content file");
524    }
525
526    /// A minimal content file body: frontmatter with the given type, no links.
527    fn doc(type_: &str, summary: &str) -> String {
528        format!("---\ntype: {type_}\nsummary: \"{summary}\"\n---\n\nbody\n")
529    }
530
531    #[test]
532    fn empty_store_is_all_zeros() {
533        let (_d, store) = temp_store();
534        let s = compute(&store).expect("compute");
535        assert_eq!(s.total_files, 0);
536        assert_eq!(s.total_size_bytes, 0);
537        assert!(s.files_per_layer.is_empty());
538        assert!(s.type_distribution.is_empty());
539        assert_eq!(s.orphan_count, 0);
540        assert_eq!(s.broken_link_count, 0);
541        assert!(s.top_types.is_empty());
542    }
543
544    #[test]
545    fn counts_files_per_layer_and_total() {
546        let (_d, store) = temp_store();
547        write_rel(&store, "sources/emails/a.md", &doc("email", "a"));
548        write_rel(&store, "sources/emails/b.md", &doc("email", "b"));
549        write_rel(&store, "records/contacts/c.md", &doc("contact", "c"));
550        // A conclusion record (former wiki-page) lives in the records layer.
551        write_rel(&store, "records/profiles/p.md", &doc("profile", "p"));
552
553        let s = compute(&store).expect("compute");
554        assert_eq!(s.total_files, 4);
555        assert_eq!(s.files_per_layer.get(&Layer::Sources), Some(&2));
556        assert_eq!(s.files_per_layer.get(&Layer::Records), Some(&2));
557    }
558
559    #[test]
560    fn ignores_meta_files_and_non_md_and_dotdirs_and_log() {
561        let (_d, store) = temp_store();
562        // Real content.
563        write_rel(&store, "records/contacts/real.md", &doc("contact", "real"));
564        // Meta + non-content that must NOT be counted.
565        write_rel(
566            &store,
567            "records/contacts/index.md",
568            "---\ntype: index\nscope: type-folder\n---\n",
569        );
570        write_rel(&store, "records/contacts/index.jsonl", "{}\n");
571        write_rel(&store, "records/notes.txt", "not markdown\n");
572        // `log/` archive tree under a layer is skipped wholesale.
573        write_rel(&store, "sources/log/2026-04.md", &doc("email", "archived"));
574        // Hidden dir contents are skipped.
575        write_rel(
576            &store,
577            "records/.obsidian/cache.md",
578            &doc("profile", "hidden"),
579        );
580
581        let s = compute(&store).expect("compute");
582        assert_eq!(s.total_files, 1, "only the one real content file counts");
583        assert_eq!(s.files_per_layer.get(&Layer::Records), Some(&1));
584        assert_eq!(s.files_per_layer.get(&Layer::Sources), None);
585    }
586
587    #[test]
588    fn total_size_is_sum_of_content_file_bytes() {
589        let (_d, store) = temp_store();
590        let a = doc("email", "a");
591        let b = "---\ntype: contact\nsummary: x\n---\n\nlonger body text here\n".to_string();
592        write_rel(&store, "sources/emails/a.md", &a);
593        write_rel(&store, "records/contacts/b.md", &b);
594        // A skipped file's bytes must not be included.
595        write_rel(
596            &store,
597            "records/contacts/index.md",
598            "---\ntype: index\n---\nbig meta file padding padding\n",
599        );
600
601        let s = compute(&store).expect("compute");
602        let expected = a.len() as u64 + b.len() as u64;
603        assert_eq!(s.total_size_bytes, expected);
604    }
605
606    #[test]
607    fn type_distribution_counts_each_type_value() {
608        let (_d, store) = temp_store();
609        write_rel(&store, "sources/emails/a.md", &doc("email", "a"));
610        write_rel(&store, "sources/emails/b.md", &doc("email", "b"));
611        write_rel(&store, "sources/emails/c.md", &doc("email", "c"));
612        write_rel(&store, "records/contacts/d.md", &doc("contact", "d"));
613        write_rel(&store, "records/proposals/e.md", &doc("proposal", "e"));
614
615        let s = compute(&store).expect("compute");
616        assert_eq!(s.type_distribution.get("email"), Some(&3));
617        assert_eq!(s.type_distribution.get("contact"), Some(&1));
618        assert_eq!(s.type_distribution.get("proposal"), Some(&1));
619        assert_eq!(s.type_distribution.len(), 3);
620    }
621
622    #[test]
623    fn file_without_type_is_counted_in_totals_but_not_distribution() {
624        let (_d, store) = temp_store();
625        // A content file with frontmatter but no `type:` key.
626        write_rel(
627            &store,
628            "records/themes/x.md",
629            "---\nsummary: no type here\n---\n\nbody\n",
630        );
631        // A content file with no frontmatter at all.
632        write_rel(
633            &store,
634            "records/themes/y.md",
635            "just a body, no frontmatter\n",
636        );
637
638        let s = compute(&store).expect("compute");
639        assert_eq!(s.total_files, 2, "untyped files still count toward totals");
640        assert_eq!(s.files_per_layer.get(&Layer::Records), Some(&2));
641        assert!(
642            s.type_distribution.is_empty(),
643            "no type key => no distribution entry, not an empty-string bucket"
644        );
645    }
646
647    #[test]
648    fn top_types_orders_by_count_desc_then_name_asc() {
649        let (_d, store) = temp_store();
650        // contact x3, email x3 (tie), decision x1.
651        write_rel(&store, "records/contacts/c1.md", &doc("contact", "1"));
652        write_rel(&store, "records/contacts/c2.md", &doc("contact", "2"));
653        write_rel(&store, "records/contacts/c3.md", &doc("contact", "3"));
654        write_rel(&store, "sources/emails/e1.md", &doc("email", "1"));
655        write_rel(&store, "sources/emails/e2.md", &doc("email", "2"));
656        write_rel(&store, "sources/emails/e3.md", &doc("email", "3"));
657        write_rel(&store, "records/decisions/d1.md", &doc("decision", "1"));
658
659        let s = compute(&store).expect("compute");
660        assert_eq!(
661            s.top_types,
662            vec![
663                ("contact".to_string(), 3),
664                ("email".to_string(), 3),
665                ("decision".to_string(), 1),
666            ],
667            "ties (contact, email both 3) break by name ascending; decision trails"
668        );
669    }
670
671    #[test]
672    fn top_types_is_capped_at_ten() {
673        let (_d, store) = temp_store();
674        // 12 distinct custom types, each one file.
675        for i in 0..12 {
676            let t = format!("type{i:02}");
677            write_rel(&store, &format!("records/{t}/f.md"), &doc(&t, "x"));
678        }
679        let s = compute(&store).expect("compute");
680        assert_eq!(s.top_types.len(), 10, "top_types caps at 10");
681        assert_eq!(
682            s.type_distribution.len(),
683            12,
684            "distribution keeps all types"
685        );
686    }
687
688    #[test]
689    fn orphans_are_files_with_no_incoming_and_no_outgoing_links() {
690        let (_d, store) = temp_store();
691        // a -> b (a has outgoing, b has incoming). c is isolated => orphan.
692        write_rel(
693            &store,
694            "records/contacts/a.md",
695            "---\ntype: contact\nsummary: a\n---\n\nSee [[records/contacts/b]].\n",
696        );
697        write_rel(&store, "records/contacts/b.md", &doc("contact", "b"));
698        write_rel(&store, "records/contacts/c.md", &doc("contact", "c"));
699
700        let s = compute(&store).expect("compute");
701        assert_eq!(s.orphan_count, 1, "only c is an orphan");
702    }
703
704    #[test]
705    fn a_file_with_only_a_self_link_is_an_orphan_matching_graph() {
706        let (_d, store) = temp_store();
707        // A file that links only to ITSELF has no real graph edge, so it must be
708        // an orphan — consistent with `graph::orphans` (which skips self-links).
709        write_rel(
710            &store,
711            "records/contacts/solo.md",
712            "---\ntype: contact\nsummary: solo\n---\n\nSee [[records/contacts/solo]].\n",
713        );
714        let s = compute(&store).expect("compute");
715        assert_eq!(
716            s.orphan_count, 1,
717            "a self-only-linking file is an orphan: {s:?}"
718        );
719    }
720
721    #[test]
722    fn a_file_with_only_an_incoming_link_is_not_an_orphan() {
723        let (_d, store) = temp_store();
724        // b has no outgoing links, but a links to it => b is NOT an orphan.
725        // a itself has an outgoing link => also not an orphan. Zero orphans.
726        write_rel(
727            &store,
728            "records/profiles/a.md",
729            "---\ntype: profile\nsummary: a\n---\n\n[[records/profiles/b]]\n",
730        );
731        write_rel(&store, "records/profiles/b.md", &doc("profile", "b"));
732
733        let s = compute(&store).expect("compute");
734        assert_eq!(s.orphan_count, 0);
735    }
736
737    #[test]
738    fn frontmatter_wiki_links_count_as_edges_for_orphans() {
739        let (_d, store) = temp_store();
740        // The link lives in a frontmatter field, not the body. It must still
741        // wire `contact` -> `company`, so neither is an orphan.
742        write_rel(
743            &store,
744            "records/contacts/sarah.md",
745            "---\ntype: contact\nsummary: s\ncompany: [[records/companies/acme]]\n---\n\nbody\n",
746        );
747        write_rel(&store, "records/companies/acme.md", &doc("company", "acme"));
748
749        let s = compute(&store).expect("compute");
750        assert_eq!(
751            s.orphan_count, 0,
752            "a frontmatter wiki-link is a real edge; neither endpoint is orphaned"
753        );
754    }
755
756    #[test]
757    fn broken_links_count_targets_that_do_not_exist() {
758        let (_d, store) = temp_store();
759        // Two links: one to an existing file, one to a missing file.
760        write_rel(
761            &store,
762            "records/profiles/a.md",
763            "---\ntype: profile\nsummary: a\n---\n\n[[records/profiles/b]] and [[records/contacts/ghost]]\n",
764        );
765        write_rel(&store, "records/profiles/b.md", &doc("profile", "b"));
766
767        let s = compute(&store).expect("compute");
768        assert_eq!(s.broken_link_count, 1, "only the ghost target is broken");
769    }
770
771    #[test]
772    fn broken_link_resolves_with_md_extension_stripped() {
773        let (_d, store) = temp_store();
774        // Link written WITH a `.md` extension still resolves to the real file
775        // (the parser accepts `.md`; validate only warns). Not broken.
776        write_rel(
777            &store,
778            "records/profiles/a.md",
779            "---\ntype: profile\nsummary: a\n---\n\n[[records/profiles/b.md]]\n",
780        );
781        write_rel(&store, "records/profiles/b.md", &doc("profile", "b"));
782
783        let s = compute(&store).expect("compute");
784        assert_eq!(
785            s.broken_link_count, 0,
786            "a `.md`-suffixed target resolves to the same node and is not broken"
787        );
788    }
789
790    #[test]
791    fn short_form_links_are_not_broken_and_do_not_wire_the_graph() {
792        let (_d, store) = temp_store();
793        // `[[b]]` is a short-form (no `/`): a validation error elsewhere, but
794        // for stats it neither counts as broken (it doesn't resolve to a node)
795        // nor wires `a` into the graph. So `a` (no other links) is an orphan.
796        write_rel(
797            &store,
798            "records/contacts/a.md",
799            "---\ntype: contact\nsummary: a\n---\n\n[[b]]\n",
800        );
801        write_rel(&store, "records/contacts/b.md", &doc("contact", "b"));
802
803        let s = compute(&store).expect("compute");
804        assert_eq!(
805            s.broken_link_count, 0,
806            "short-form links are not counted as broken by stats"
807        );
808        // a has only a short-form link (not an edge) => orphan. b has no links
809        // and no real incoming edge => orphan. Both orphaned.
810        assert_eq!(s.orphan_count, 2);
811    }
812
813    #[test]
814    fn display_alias_links_resolve_to_the_target_not_the_alias() {
815        let (_d, store) = temp_store();
816        // `[[records/profiles/b|Bob]]` targets b, displays "Bob". The alias must
817        // be stripped: the edge goes to b (exists), so it's not broken and b is
818        // not an orphan.
819        write_rel(
820            &store,
821            "records/profiles/a.md",
822            "---\ntype: profile\nsummary: a\n---\n\nmet [[records/profiles/b|Bob]] today\n",
823        );
824        write_rel(&store, "records/profiles/b.md", &doc("profile", "b"));
825
826        let s = compute(&store).expect("compute");
827        assert_eq!(s.broken_link_count, 0, "alias target resolves and exists");
828        assert_eq!(s.orphan_count, 0, "a links out, b is linked to");
829    }
830
831    #[test]
832    fn duplicate_links_in_one_file_count_broken_per_occurrence() {
833        let (_d, store) = temp_store();
834        // The same missing target twice => two broken-link occurrences.
835        write_rel(
836            &store,
837            "records/profiles/a.md",
838            "---\ntype: profile\nsummary: a\n---\n\n[[records/contacts/ghost]] [[records/contacts/ghost]]\n",
839        );
840        let s = compute(&store).expect("compute");
841        assert_eq!(
842            s.broken_link_count, 2,
843            "broken links count occurrences, not distinct targets"
844        );
845    }
846
847    #[test]
848    fn markdown_links_are_not_treated_as_wiki_links() {
849        let (_d, store) = temp_store();
850        // A standard markdown link to an external URL must not register as a
851        // wiki edge (so this file stays an orphan) nor as a broken link.
852        write_rel(
853            &store,
854            "records/profiles/a.md",
855            "---\ntype: profile\nsummary: a\n---\n\nSee [Acme](https://acme.io/path).\n",
856        );
857        let s = compute(&store).expect("compute");
858        assert_eq!(s.broken_link_count, 0, "markdown links aren't graph edges");
859        assert_eq!(s.orphan_count, 1, "the file has no wiki-links => orphan");
860    }
861
862    #[test]
863    fn regression_non_layer_multi_segment_link_is_not_broken() {
864        // Finding #20: a target like `[[contacts/sarah-chen]]` omits the layer
865        // prefix. It has a `/` but its first segment (`contacts`) is not a
866        // recognized layer, so it's a short-form error in `validate`, NOT a
867        // broken link. stats must agree: it counts neither as broken nor as an
868        // outgoing edge. Pre-fix `is_full_path` (components().count() > 1)
869        // accepted it and reported broken_link_count = 1.
870        let (_d, store) = temp_store();
871        write_rel(
872            &store,
873            "records/contacts/a.md",
874            "---\ntype: contact\nsummary: a\n---\n\nSee [[contacts/sarah-chen]].\n",
875        );
876        let s = compute(&store).expect("compute");
877        assert_eq!(
878            s.broken_link_count, 0,
879            "a non-layer multi-segment target is a short-form error, not broken"
880        );
881        // The non-layer link is not a graph edge, so `a` has no outgoing edge
882        // and is an orphan — matching how validate/graph treat it.
883        assert_eq!(
884            s.orphan_count, 1,
885            "the non-layer link does not wire `a` out of orphan status"
886        );
887    }
888
889    #[test]
890    fn regression_wiki_links_in_code_fences_are_ignored() {
891        // Finding #21: a wiki-link that appears only inside a fenced code block
892        // is illustrative syntax, not a graph edge. validate skips fenced
893        // regions; stats must too. Pre-fix the regex ran over the whole file
894        // with no fence tracking, so the fenced ghost link inflated
895        // broken_link_count to 1 and the fenced real link un-orphaned the page.
896        let (_d, store) = temp_store();
897        // A howto page whose ONLY wiki-links live inside ``` and ~~~ fences:
898        // one to a missing target, one to an existing target.
899        write_rel(
900            &store,
901            "records/synthesis/howto.md",
902            "---\ntype: synthesis\nsummary: howto\n---\n\
903             \nWrite links like this:\n\
904             \n```\n[[records/contacts/ghost]]\n```\n\
905             \nor this:\n\
906             \n~~~\n[[records/synthesis/real]]\n~~~\n",
907        );
908        write_rel(
909            &store,
910            "records/synthesis/real.md",
911            &doc("synthesis", "real"),
912        );
913        let s = compute(&store).expect("compute");
914        assert_eq!(
915            s.broken_link_count, 0,
916            "a `[[...]]` inside a code fence is not a real (broken) edge"
917        );
918        // howto has no real edges => orphan. real is not linked-to by any real
919        // edge => orphan. Both orphaned (2), proving the fenced link to `real`
920        // did not wire either file out of orphan status.
921        assert_eq!(
922            s.orphan_count, 2,
923            "fenced wiki-links do not wire files out of orphan status: {s:?}"
924        );
925    }
926
927    #[test]
928    fn a_link_to_an_existing_file_in_another_layer_resolves() {
929        let (_d, store) = temp_store();
930        // A records-layer profile links to a source file in the other layer;
931        // cross-layer full-path links resolve like any other.
932        write_rel(
933            &store,
934            "records/profiles/a.md",
935            "---\ntype: profile\nsummary: a\n---\n\nfrom [[sources/emails/2026/05/m]]\n",
936        );
937        write_rel(&store, "sources/emails/2026/05/m.md", &doc("email", "m"));
938
939        let s = compute(&store).expect("compute");
940        assert_eq!(s.broken_link_count, 0);
941        assert_eq!(s.orphan_count, 0, "both endpoints are wired");
942    }
943
944    #[test]
945    fn regression_tilde_line_inside_backtick_fence_does_not_invert_state() {
946        // Finding #44/#11: a `~~~` line inside an open ``` fence (or any inner
947        // fence of the other char / a shorter run) must NOT close the block.
948        // Pre-fix a single boolean toggled on it, inverting fence state so the
949        // fenced ghost link counted broken and the real link after the fence
950        // was dropped. With (byte, run-length) tracking the block only closes on
951        // a matching ``` fence.
952        let (_d, store) = temp_store();
953        write_rel(&store, "records/profiles/bob.md", &doc("profile", "bob"));
954        // ```text … ~~~ x (inner tilde line) … [[ghost]] … ``` then a real link.
955        write_rel(
956            &store,
957            "records/concepts/howto.md",
958            "---\ntype: concept\nsummary: howto\n---\n\
959             \n```text\n~~~ x\n[[records/profiles/ghost]]\n```\n\
960             \nReal: [[records/profiles/bob]]\n",
961        );
962
963        let s = compute(&store).expect("compute");
964        assert_eq!(
965            s.broken_link_count, 0,
966            "the fenced ghost link is inside the unbroken ``` block, not broken: {s:?}"
967        );
968        // bob is linked from howto (a real edge after the fence closes), and
969        // howto links out — neither is an orphan.
970        assert_eq!(
971            s.orphan_count, 0,
972            "the real post-fence link wires both files: {s:?}"
973        );
974    }
975
976    #[test]
977    fn regression_nested_log_directory_is_counted_not_skipped() {
978        // Finding #45: only the layer's IMMEDIATE `log/` archive is skipped. A
979        // directory named `log` nested under a type-folder is ordinary content
980        // and must be counted, matching tree/index/query. Pre-fix any `log` dir
981        // at any depth was pruned, making the whole subtree invisible to stats.
982        let (_d, store) = temp_store();
983        write_rel(
984            &store,
985            "sources/emails/log/maillog.md",
986            &doc(
987                "email",
988                "an archived mail log entry under a log subdirectory",
989            ),
990        );
991        // The layer-immediate `log/` archive is still skipped.
992        write_rel(&store, "sources/log/2026-04.md", &doc("email", "rotated"));
993
994        let s = compute(&store).expect("compute");
995        assert_eq!(
996            s.total_files, 1,
997            "the nested sources/emails/log file counts; the layer-immediate sources/log is skipped: {s:?}"
998        );
999        assert_eq!(s.files_per_layer.get(&Layer::Sources), Some(&1));
1000        assert_eq!(s.type_distribution.get("email"), Some(&1));
1001    }
1002
1003    #[test]
1004    fn regression_link_to_existing_non_md_source_is_a_live_edge() {
1005        // Finding (high): a record that wiki-links to an existing non-`.md`
1006        // source artifact (a `.eml`) must read as a LIVE edge, not broken, and
1007        // the record is not an orphan. `sources/` holds such files by design.
1008        let (_d, store) = temp_store();
1009        // A real .eml source file (not a .md content file).
1010        write_rel(
1011            &store,
1012            "sources/emails/msg.eml",
1013            "From: someone@example.com\nSubject: Renewal\n\nBody text.\n",
1014        );
1015        // A record with the SPEC-canonical bare link to that source.
1016        write_rel(
1017            &store,
1018            "records/contacts/sarah.md",
1019            "---\ntype: contact\nsummary: s\n---\n\nLinked source: [[sources/emails/msg]]\n",
1020        );
1021
1022        let s = compute(&store).expect("compute");
1023        assert_eq!(
1024            s.broken_link_count, 0,
1025            "a link to an existing .eml source is live, not broken: {s:?}"
1026        );
1027        assert_eq!(
1028            s.orphan_count, 0,
1029            "the linking record has a resolvable outgoing edge to the source: {s:?}"
1030        );
1031        // The explicit-extension form resolves the same way.
1032        write_rel(
1033            &store,
1034            "records/contacts/sarah.md",
1035            "---\ntype: contact\nsummary: s\n---\n\nLinked source: [[sources/emails/msg.eml]]\n",
1036        );
1037        let s2 = compute(&store).expect("compute");
1038        assert_eq!(s2.broken_link_count, 0, "explicit .eml target resolves too");
1039        assert_eq!(s2.orphan_count, 0);
1040    }
1041
1042    #[test]
1043    fn regression_traversal_target_is_broken_not_a_filesystem_escape() {
1044        // SECURITY regression: a `..`-laden wiki-link target must never turn a
1045        // stats probe into a read of a file OUTSIDE the store. Pre-fix
1046        // `target_resolves_on_disk` joined the raw target onto the store root and
1047        // probed `is_file` / `read_dir` with no containment check, so
1048        // `[[sources/../../outside-secret]]` reached a file above the store and
1049        // was silently counted as a LIVE edge (un-orphaning the linker and never
1050        // counted broken) — diverging from validate (which flags it
1051        // WIKI_LINK_BROKEN) and graph (which drops it). The gate now rejects any
1052        // non-`Normal` component before any join, so it counts broken.
1053        // Nested store: `store.root.parent()` is this test's private tempdir,
1054        // never the shared `$TMPDIR` (which the sibling traversal test would also
1055        // write into, racing on the same filename under `--workspace`).
1056        let (_d, store) = temp_store_nested();
1057        // Every store has a `sources/` dir; the traversal needs its first
1058        // component to be a recognized layer to pass `is_full_path`.
1059        fs::create_dir_all(store.root.join("sources/emails")).unwrap();
1060        // Plant a secret ABOVE the store root (the parent of the store dir).
1061        let outside_dir = store.root.parent().expect("store has a parent");
1062        fs::write(outside_dir.join("outside-secret.txt"), "TOP SECRET\n").unwrap();
1063
1064        // Bare-stem traversal (would hit the `read_dir` parent branch) and the
1065        // explicit-extension traversal (would hit the `is_file` literal branch).
1066        for target in [
1067            "sources/../../outside-secret",
1068            "sources/../../outside-secret.txt",
1069        ] {
1070            write_rel(
1071                &store,
1072                "records/contacts/a.md",
1073                &format!("---\ntype: contact\nsummary: s\n---\n\nEscape: [[{target}]]\n"),
1074            );
1075            let s = compute(&store).expect("compute");
1076            assert_eq!(
1077                s.broken_link_count, 1,
1078                "a `..` target escaping the store must be broken, not a live edge ({target}): {s:?}"
1079            );
1080            assert_eq!(
1081                s.orphan_count, 1,
1082                "an escaping link must NOT wire the linker out of orphan status ({target}): {s:?}"
1083            );
1084        }
1085        // The secret outside the store is untouched (we never followed the link).
1086        assert_eq!(
1087            fs::read_to_string(outside_dir.join("outside-secret.txt")).unwrap(),
1088            "TOP SECRET\n"
1089        );
1090    }
1091
1092    #[test]
1093    fn regression_target_resolves_on_disk_rejects_traversal_before_any_probe() {
1094        // SECURITY regression at the helper level: `target_resolves_on_disk`
1095        // must return `false` for any `..`-laden / absolute / prefix target
1096        // BEFORE it joins, `is_file`s, or `read_dir`s — so a wiki-link can never
1097        // turn a stats existence-probe into a read of a file OUTSIDE the store.
1098        // Pre-fix the helper joined the raw target onto the store root with no
1099        // containment gate, so a real file above the store made it return
1100        // `true`. This asserts the gate directly on the helper (the end-to-end
1101        // `compute()` path is covered separately above), exercising BOTH on-disk
1102        // branches: the literal `is_file` branch (explicit extension) and the
1103        // bare-stem `read_dir` branch.
1104        // Nested store: `store.root.parent()` is this test's private tempdir, so
1105        // the "above the store" files below never land in the shared `$TMPDIR`
1106        // and can never collide with the sibling traversal test's identically
1107        // named planted files when both run in parallel.
1108        let (_d, store) = temp_store_nested();
1109        // A real `sources/` tree exists (the literal/parent joins would have
1110        // something to land near), matching a real store.
1111        fs::create_dir_all(store.root.join("sources/emails")).unwrap();
1112        // Plant matching files ABOVE the store root: one with the exact name the
1113        // explicit-extension target points at, and one whose stem the bare-stem
1114        // target would discover via `read_dir` of the (escaped) parent dir.
1115        let outside_dir = store.root.parent().expect("store has a parent");
1116        fs::write(outside_dir.join("outside-secret.txt"), "TOP SECRET\n").unwrap();
1117        fs::write(outside_dir.join("outside-secret.eml"), "secret mail\n").unwrap();
1118
1119        // Explicit-extension traversal -> would hit the literal `is_file` branch.
1120        assert!(
1121            !target_resolves_on_disk(
1122                &store.root,
1123                &strip_md(Path::new("sources/../../outside-secret.txt"))
1124            ),
1125            "an explicit-extension `..` target escaping the store must not resolve on disk"
1126        );
1127        // Bare-stem traversal -> would hit the `read_dir(parent)` branch, where a
1128        // sibling `outside-secret.eml` (non-`.md`) sits beside the escaped parent.
1129        assert!(
1130            !target_resolves_on_disk(
1131                &store.root,
1132                &strip_md(Path::new("sources/../../outside-secret"))
1133            ),
1134            "a bare-stem `..` target escaping the store must not resolve on disk"
1135        );
1136        // A `..` that stays nominally under a layer prefix is still an escape and
1137        // is rejected before any probe.
1138        assert!(
1139            !target_resolves_on_disk(&store.root, Path::new("records/../records/secret")),
1140            "any `..` component is rejected before a probe, even one re-entering a layer"
1141        );
1142
1143        // Sanity: a legitimate in-store non-`.md` source DOES still resolve, so
1144        // the gate did not over-reject and break the finding #117 behavior.
1145        write_rel(
1146            &store,
1147            "sources/emails/msg.eml",
1148            "From: a@b.com\nSubject: x\n\nbody\n",
1149        );
1150        assert!(
1151            target_resolves_on_disk(&store.root, Path::new("sources/emails/msg")),
1152            "a legitimate in-store bare-stem source link still resolves on disk"
1153        );
1154
1155        // The secrets outside the store are untouched (we never followed a link).
1156        assert_eq!(
1157            fs::read_to_string(outside_dir.join("outside-secret.txt")).unwrap(),
1158            "TOP SECRET\n"
1159        );
1160    }
1161
1162    #[test]
1163    fn regression_link_to_truly_missing_source_is_still_broken() {
1164        // Guard the source-resolution fix doesn't over-resolve: a bare link
1165        // whose target has NO file of any extension on disk is still broken.
1166        let (_d, store) = temp_store();
1167        write_rel(
1168            &store,
1169            "records/contacts/sarah.md",
1170            "---\ntype: contact\nsummary: s\n---\n\nLinked: [[sources/emails/missing]]\n",
1171        );
1172        let s = compute(&store).expect("compute");
1173        assert_eq!(
1174            s.broken_link_count, 1,
1175            "a target with no on-disk file in any form is broken: {s:?}"
1176        );
1177    }
1178}