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 {
120                // Broken links count occurrences, not distinct targets.
121                stats.broken_link_count += 1;
122            }
123        }
124    }
125
126    // Third pass: roll the per-file facts up into the aggregate Stats. A file is
127    // an orphan iff it has neither a resolvable outgoing edge nor an incoming one.
128    for file in &facts {
129        stats.total_files += 1;
130        *stats.files_per_layer.entry(file.layer).or_insert(0) += 1;
131        stats.total_size_bytes += file.size_bytes;
132
133        if let Some(t) = &file.type_ {
134            *stats.type_distribution.entry(t.clone()).or_insert(0) += 1;
135        }
136
137        let has_outgoing = file
138            .resolvable_targets()
139            .any(|t| t != &file.node_id && existing_nodes.contains(t));
140        let has_incoming = linked_to.contains(&file.node_id);
141        if !has_outgoing && !has_incoming {
142            stats.orphan_count += 1;
143        }
144    }
145
146    stats.top_types = top_types(&stats.type_distribution, TOP_TYPES_LIMIT);
147
148    Ok(stats)
149}
150
151/// On-disk folder name for a layer. Local copy so `stats` doesn't couple to
152/// [`Layer::dir_name`].
153fn layer_dir_name(layer: Layer) -> &'static str {
154    match layer {
155        Layer::Sources => "sources",
156        Layer::Records => "records",
157        Layer::Wiki => "wiki",
158    }
159}
160
161/// Recursively collect the `.md` **content** files under one layer root,
162/// skipping hidden entries (`.git`, dotfiles), the `log/` archive tree, and the
163/// `index.md` catalog meta files. Returns absolute paths. A missing layer root
164/// yields an empty list (a store need not have all three layers).
165fn walk_layer_content_files(layer_root: &Path) -> crate::Result<Vec<PathBuf>> {
166    let mut out = Vec::new();
167    if !layer_root.is_dir() {
168        return Ok(out);
169    }
170    let walker = walkdir::WalkDir::new(layer_root)
171        .into_iter()
172        .filter_entry(|e| {
173            // Skip hidden dirs/files and any `log` directory wholesale.
174            let name = e.file_name().to_string_lossy();
175            if name.starts_with('.') {
176                return false;
177            }
178            if e.file_type().is_dir() && name == "log" {
179                return false;
180            }
181            true
182        });
183    for entry in walker {
184        let entry = entry.map_err(|e| {
185            crate::Error::Io(
186                e.into_io_error()
187                    .unwrap_or_else(|| std::io::Error::other("walk error")),
188            )
189        })?;
190        if !entry.file_type().is_file() {
191            continue;
192        }
193        let path = entry.path();
194        let name = entry.file_name().to_string_lossy();
195        // Content files are `.md`; `index.md` is a meta catalog file, not
196        // content, and `index.jsonl` / other sidecars aren't `.md` at all.
197        if !name.ends_with(".md") || name == "index.md" {
198            continue;
199        }
200        out.push(path.to_path_buf());
201    }
202    out.sort();
203    Ok(out)
204}
205
206/// The wiki-link matcher: `[[target]]` or `[[target|display]]`. Captures the
207/// target (group 1), excluding `]` and `|`. Anchored on the literal brackets so
208/// it ignores `[markdown](links)`.
209fn wiki_link_regex() -> Regex {
210    // `[^\[\]|]+` keeps the target free of brackets and the display pipe.
211    Regex::new(r"\[\[([^\[\]|]+)(?:\|[^\]]*)?\]\]").expect("static wiki-link regex is valid")
212}
213
214/// Every wiki-link target in a file's full text (frontmatter + body), trimmed,
215/// with any trailing `.md` removed. Order-preserving; not deduped.
216fn extract_link_targets(text: &str, re: &Regex) -> Vec<PathBuf> {
217    re.captures_iter(text)
218        .filter_map(|c| c.get(1))
219        .map(|m| {
220            let raw = m.as_str().trim();
221            strip_md(Path::new(raw))
222        })
223        .collect()
224}
225
226/// Drop a trailing `.md` from a path, leaving everything else intact.
227fn strip_md(path: &Path) -> PathBuf {
228    let s = path.to_string_lossy();
229    match s.strip_suffix(".md") {
230        Some(stem) => PathBuf::from(stem),
231        None => path.to_path_buf(),
232    }
233}
234
235/// True if a wiki-link target is a full store-relative path (contains a path
236/// separator). Short-form targets like `sarah-chen` are false. Doctrine: only
237/// full paths resolve to a node.
238fn is_full_path(target: &Path) -> bool {
239    target.components().count() > 1
240}
241
242/// Read the `type:` value from a file's leading YAML frontmatter block, if the
243/// file has one. Returns `None` when there's no frontmatter or no `type` key.
244/// Self-contained (does not route through the crate's parser): split on the
245/// `---` fences, parse the block as a YAML mapping, read `type` as a string.
246fn parse_type(text: &str) -> Option<String> {
247    let yaml = frontmatter_block(text)?;
248    let value: serde_norway::Value = serde_norway::from_str(&yaml).ok()?;
249    let mapping = value.as_mapping()?;
250    let type_val = mapping.get(serde_norway::Value::String("type".to_string()))?;
251    let s = type_val.as_str()?.trim();
252    if s.is_empty() {
253        None
254    } else {
255        Some(s.to_string())
256    }
257}
258
259/// Extract the raw YAML between a leading `---` fence and its closing `---`.
260/// The opening fence must be the very first line of the file (the universal
261/// frontmatter contract: frontmatter is the first thing in the file).
262fn frontmatter_block(text: &str) -> Option<String> {
263    // Normalize away a leading BOM, but require `---` as the first line.
264    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
265    let mut lines = text.lines();
266    let first = lines.next()?;
267    if first.trim_end() != "---" {
268        return None;
269    }
270    let mut body = String::new();
271    for line in lines {
272        if line.trim_end() == "---" {
273            return Some(body);
274        }
275        body.push_str(line);
276        body.push('\n');
277    }
278    // No closing fence: not a valid frontmatter block.
279    None
280}
281
282/// Sort a type distribution into the top `limit` types by count descending,
283/// ties broken by type name ascending.
284fn top_types(dist: &BTreeMap<String, usize>, limit: usize) -> Vec<(String, usize)> {
285    let mut pairs: Vec<(String, usize)> = dist.iter().map(|(k, v)| (k.clone(), *v)).collect();
286    // BTreeMap iteration is already name-ascending; a stable sort by count
287    // descending therefore yields (count desc, name asc).
288    pairs.sort_by_key(|p| std::cmp::Reverse(p.1));
289    pairs.truncate(limit);
290    pairs
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296    use crate::parser::Config;
297    use std::fs;
298    use tempfile::TempDir;
299
300    /// Build a `Store` rooted at a fresh tempdir with an empty `DB.md` marker.
301    /// Bypasses `Store::open` by constructing the struct directly —
302    /// `stats::compute` only reads `store.root`.
303    fn temp_store() -> (TempDir, Store) {
304        let dir = TempDir::new().expect("tempdir");
305        fs::write(dir.path().join("DB.md"), "---\ntype: db-md\n---\n").expect("write DB.md");
306        let store = Store {
307            root: dir.path().to_path_buf(),
308            config: Config::default(),
309        };
310        (dir, store)
311    }
312
313    /// Write a content file at a store-relative path, creating parent dirs.
314    fn write_rel(store: &Store, rel: &str, contents: &str) {
315        let abs = store.root.join(rel);
316        if let Some(parent) = abs.parent() {
317            fs::create_dir_all(parent).expect("mkdir parents");
318        }
319        fs::write(abs, contents).expect("write content file");
320    }
321
322    /// A minimal content file body: frontmatter with the given type, no links.
323    fn doc(type_: &str, summary: &str) -> String {
324        format!("---\ntype: {type_}\nsummary: \"{summary}\"\n---\n\nbody\n")
325    }
326
327    #[test]
328    fn empty_store_is_all_zeros() {
329        let (_d, store) = temp_store();
330        let s = compute(&store).expect("compute");
331        assert_eq!(s.total_files, 0);
332        assert_eq!(s.total_size_bytes, 0);
333        assert!(s.files_per_layer.is_empty());
334        assert!(s.type_distribution.is_empty());
335        assert_eq!(s.orphan_count, 0);
336        assert_eq!(s.broken_link_count, 0);
337        assert!(s.top_types.is_empty());
338    }
339
340    #[test]
341    fn counts_files_per_layer_and_total() {
342        let (_d, store) = temp_store();
343        write_rel(&store, "sources/emails/a.md", &doc("email", "a"));
344        write_rel(&store, "sources/emails/b.md", &doc("email", "b"));
345        write_rel(&store, "records/contacts/c.md", &doc("contact", "c"));
346        write_rel(&store, "wiki/people/p.md", &doc("wiki-page", "p"));
347
348        let s = compute(&store).expect("compute");
349        assert_eq!(s.total_files, 4);
350        assert_eq!(s.files_per_layer.get(&Layer::Sources), Some(&2));
351        assert_eq!(s.files_per_layer.get(&Layer::Records), Some(&1));
352        assert_eq!(s.files_per_layer.get(&Layer::Wiki), Some(&1));
353    }
354
355    #[test]
356    fn ignores_meta_files_and_non_md_and_dotdirs_and_log() {
357        let (_d, store) = temp_store();
358        // Real content.
359        write_rel(&store, "records/contacts/real.md", &doc("contact", "real"));
360        // Meta + non-content that must NOT be counted.
361        write_rel(
362            &store,
363            "records/contacts/index.md",
364            "---\ntype: index\nscope: type-folder\n---\n",
365        );
366        write_rel(&store, "records/contacts/index.jsonl", "{}\n");
367        write_rel(&store, "records/notes.txt", "not markdown\n");
368        // `log/` archive tree under a layer is skipped wholesale.
369        write_rel(&store, "sources/log/2026-04.md", &doc("email", "archived"));
370        // Hidden dir contents are skipped.
371        write_rel(
372            &store,
373            "wiki/.obsidian/cache.md",
374            &doc("wiki-page", "hidden"),
375        );
376
377        let s = compute(&store).expect("compute");
378        assert_eq!(s.total_files, 1, "only the one real content file counts");
379        assert_eq!(s.files_per_layer.get(&Layer::Records), Some(&1));
380        assert_eq!(s.files_per_layer.get(&Layer::Sources), None);
381        assert_eq!(s.files_per_layer.get(&Layer::Wiki), None);
382    }
383
384    #[test]
385    fn total_size_is_sum_of_content_file_bytes() {
386        let (_d, store) = temp_store();
387        let a = doc("email", "a");
388        let b = "---\ntype: contact\nsummary: x\n---\n\nlonger body text here\n".to_string();
389        write_rel(&store, "sources/emails/a.md", &a);
390        write_rel(&store, "records/contacts/b.md", &b);
391        // A skipped file's bytes must not be included.
392        write_rel(
393            &store,
394            "records/contacts/index.md",
395            "---\ntype: index\n---\nbig meta file padding padding\n",
396        );
397
398        let s = compute(&store).expect("compute");
399        let expected = a.len() as u64 + b.len() as u64;
400        assert_eq!(s.total_size_bytes, expected);
401    }
402
403    #[test]
404    fn type_distribution_counts_each_type_value() {
405        let (_d, store) = temp_store();
406        write_rel(&store, "sources/emails/a.md", &doc("email", "a"));
407        write_rel(&store, "sources/emails/b.md", &doc("email", "b"));
408        write_rel(&store, "sources/emails/c.md", &doc("email", "c"));
409        write_rel(&store, "records/contacts/d.md", &doc("contact", "d"));
410        write_rel(&store, "records/proposals/e.md", &doc("proposal", "e"));
411
412        let s = compute(&store).expect("compute");
413        assert_eq!(s.type_distribution.get("email"), Some(&3));
414        assert_eq!(s.type_distribution.get("contact"), Some(&1));
415        assert_eq!(s.type_distribution.get("proposal"), Some(&1));
416        assert_eq!(s.type_distribution.len(), 3);
417    }
418
419    #[test]
420    fn file_without_type_is_counted_in_totals_but_not_distribution() {
421        let (_d, store) = temp_store();
422        // A content file with frontmatter but no `type:` key.
423        write_rel(
424            &store,
425            "wiki/themes/x.md",
426            "---\nsummary: no type here\n---\n\nbody\n",
427        );
428        // A content file with no frontmatter at all.
429        write_rel(&store, "wiki/themes/y.md", "just a body, no frontmatter\n");
430
431        let s = compute(&store).expect("compute");
432        assert_eq!(s.total_files, 2, "untyped files still count toward totals");
433        assert_eq!(s.files_per_layer.get(&Layer::Wiki), Some(&2));
434        assert!(
435            s.type_distribution.is_empty(),
436            "no type key => no distribution entry, not an empty-string bucket"
437        );
438    }
439
440    #[test]
441    fn top_types_orders_by_count_desc_then_name_asc() {
442        let (_d, store) = temp_store();
443        // contact x3, email x3 (tie), decision x1.
444        write_rel(&store, "records/contacts/c1.md", &doc("contact", "1"));
445        write_rel(&store, "records/contacts/c2.md", &doc("contact", "2"));
446        write_rel(&store, "records/contacts/c3.md", &doc("contact", "3"));
447        write_rel(&store, "sources/emails/e1.md", &doc("email", "1"));
448        write_rel(&store, "sources/emails/e2.md", &doc("email", "2"));
449        write_rel(&store, "sources/emails/e3.md", &doc("email", "3"));
450        write_rel(&store, "records/decisions/d1.md", &doc("decision", "1"));
451
452        let s = compute(&store).expect("compute");
453        assert_eq!(
454            s.top_types,
455            vec![
456                ("contact".to_string(), 3),
457                ("email".to_string(), 3),
458                ("decision".to_string(), 1),
459            ],
460            "ties (contact, email both 3) break by name ascending; decision trails"
461        );
462    }
463
464    #[test]
465    fn top_types_is_capped_at_ten() {
466        let (_d, store) = temp_store();
467        // 12 distinct custom types, each one file.
468        for i in 0..12 {
469            let t = format!("type{i:02}");
470            write_rel(&store, &format!("records/{t}/f.md"), &doc(&t, "x"));
471        }
472        let s = compute(&store).expect("compute");
473        assert_eq!(s.top_types.len(), 10, "top_types caps at 10");
474        assert_eq!(
475            s.type_distribution.len(),
476            12,
477            "distribution keeps all types"
478        );
479    }
480
481    #[test]
482    fn orphans_are_files_with_no_incoming_and_no_outgoing_links() {
483        let (_d, store) = temp_store();
484        // a -> b (a has outgoing, b has incoming). c is isolated => orphan.
485        write_rel(
486            &store,
487            "records/contacts/a.md",
488            "---\ntype: contact\nsummary: a\n---\n\nSee [[records/contacts/b]].\n",
489        );
490        write_rel(&store, "records/contacts/b.md", &doc("contact", "b"));
491        write_rel(&store, "records/contacts/c.md", &doc("contact", "c"));
492
493        let s = compute(&store).expect("compute");
494        assert_eq!(s.orphan_count, 1, "only c is an orphan");
495    }
496
497    #[test]
498    fn a_file_with_only_a_self_link_is_an_orphan_matching_graph() {
499        let (_d, store) = temp_store();
500        // A file that links only to ITSELF has no real graph edge, so it must be
501        // an orphan — consistent with `graph::orphans` (which skips self-links).
502        write_rel(
503            &store,
504            "records/contacts/solo.md",
505            "---\ntype: contact\nsummary: solo\n---\n\nSee [[records/contacts/solo]].\n",
506        );
507        let s = compute(&store).expect("compute");
508        assert_eq!(
509            s.orphan_count, 1,
510            "a self-only-linking file is an orphan: {s:?}"
511        );
512    }
513
514    #[test]
515    fn a_file_with_only_an_incoming_link_is_not_an_orphan() {
516        let (_d, store) = temp_store();
517        // b has no outgoing links, but a links to it => b is NOT an orphan.
518        // a itself has an outgoing link => also not an orphan. Zero orphans.
519        write_rel(
520            &store,
521            "wiki/people/a.md",
522            "---\ntype: wiki-page\nsummary: a\n---\n\n[[wiki/people/b]]\n",
523        );
524        write_rel(&store, "wiki/people/b.md", &doc("wiki-page", "b"));
525
526        let s = compute(&store).expect("compute");
527        assert_eq!(s.orphan_count, 0);
528    }
529
530    #[test]
531    fn frontmatter_wiki_links_count_as_edges_for_orphans() {
532        let (_d, store) = temp_store();
533        // The link lives in a frontmatter field, not the body. It must still
534        // wire `contact` -> `company`, so neither is an orphan.
535        write_rel(
536            &store,
537            "records/contacts/sarah.md",
538            "---\ntype: contact\nsummary: s\ncompany: [[records/companies/acme]]\n---\n\nbody\n",
539        );
540        write_rel(&store, "records/companies/acme.md", &doc("company", "acme"));
541
542        let s = compute(&store).expect("compute");
543        assert_eq!(
544            s.orphan_count, 0,
545            "a frontmatter wiki-link is a real edge; neither endpoint is orphaned"
546        );
547    }
548
549    #[test]
550    fn broken_links_count_targets_that_do_not_exist() {
551        let (_d, store) = temp_store();
552        // Two links: one to an existing file, one to a missing file.
553        write_rel(
554            &store,
555            "wiki/people/a.md",
556            "---\ntype: wiki-page\nsummary: a\n---\n\n[[wiki/people/b]] and [[records/contacts/ghost]]\n",
557        );
558        write_rel(&store, "wiki/people/b.md", &doc("wiki-page", "b"));
559
560        let s = compute(&store).expect("compute");
561        assert_eq!(s.broken_link_count, 1, "only the ghost target is broken");
562    }
563
564    #[test]
565    fn broken_link_resolves_with_md_extension_stripped() {
566        let (_d, store) = temp_store();
567        // Link written WITH a `.md` extension still resolves to the real file
568        // (the parser accepts `.md`; validate only warns). Not broken.
569        write_rel(
570            &store,
571            "wiki/people/a.md",
572            "---\ntype: wiki-page\nsummary: a\n---\n\n[[wiki/people/b.md]]\n",
573        );
574        write_rel(&store, "wiki/people/b.md", &doc("wiki-page", "b"));
575
576        let s = compute(&store).expect("compute");
577        assert_eq!(
578            s.broken_link_count, 0,
579            "a `.md`-suffixed target resolves to the same node and is not broken"
580        );
581    }
582
583    #[test]
584    fn short_form_links_are_not_broken_and_do_not_wire_the_graph() {
585        let (_d, store) = temp_store();
586        // `[[b]]` is a short-form (no `/`): a validation error elsewhere, but
587        // for stats it neither counts as broken (it doesn't resolve to a node)
588        // nor wires `a` into the graph. So `a` (no other links) is an orphan.
589        write_rel(
590            &store,
591            "records/contacts/a.md",
592            "---\ntype: contact\nsummary: a\n---\n\n[[b]]\n",
593        );
594        write_rel(&store, "records/contacts/b.md", &doc("contact", "b"));
595
596        let s = compute(&store).expect("compute");
597        assert_eq!(
598            s.broken_link_count, 0,
599            "short-form links are not counted as broken by stats"
600        );
601        // a has only a short-form link (not an edge) => orphan. b has no links
602        // and no real incoming edge => orphan. Both orphaned.
603        assert_eq!(s.orphan_count, 2);
604    }
605
606    #[test]
607    fn display_alias_links_resolve_to_the_target_not_the_alias() {
608        let (_d, store) = temp_store();
609        // `[[wiki/people/b|Bob]]` targets b, displays "Bob". The alias must be
610        // stripped: the edge goes to b (exists), so it's not broken and b is
611        // not an orphan.
612        write_rel(
613            &store,
614            "wiki/people/a.md",
615            "---\ntype: wiki-page\nsummary: a\n---\n\nmet [[wiki/people/b|Bob]] today\n",
616        );
617        write_rel(&store, "wiki/people/b.md", &doc("wiki-page", "b"));
618
619        let s = compute(&store).expect("compute");
620        assert_eq!(s.broken_link_count, 0, "alias target resolves and exists");
621        assert_eq!(s.orphan_count, 0, "a links out, b is linked to");
622    }
623
624    #[test]
625    fn duplicate_links_in_one_file_count_broken_per_occurrence() {
626        let (_d, store) = temp_store();
627        // The same missing target twice => two broken-link occurrences.
628        write_rel(
629            &store,
630            "wiki/people/a.md",
631            "---\ntype: wiki-page\nsummary: a\n---\n\n[[records/contacts/ghost]] [[records/contacts/ghost]]\n",
632        );
633        let s = compute(&store).expect("compute");
634        assert_eq!(
635            s.broken_link_count, 2,
636            "broken links count occurrences, not distinct targets"
637        );
638    }
639
640    #[test]
641    fn markdown_links_are_not_treated_as_wiki_links() {
642        let (_d, store) = temp_store();
643        // A standard markdown link to an external URL must not register as a
644        // wiki edge (so this file stays an orphan) nor as a broken link.
645        write_rel(
646            &store,
647            "wiki/people/a.md",
648            "---\ntype: wiki-page\nsummary: a\n---\n\nSee [Acme](https://acme.io/path).\n",
649        );
650        let s = compute(&store).expect("compute");
651        assert_eq!(s.broken_link_count, 0, "markdown links aren't graph edges");
652        assert_eq!(s.orphan_count, 1, "the file has no wiki-links => orphan");
653    }
654
655    #[test]
656    fn a_link_to_an_existing_file_in_another_layer_resolves() {
657        let (_d, store) = temp_store();
658        // wiki page links to a source file in a different layer; cross-layer
659        // full-path links resolve like any other.
660        write_rel(
661            &store,
662            "wiki/people/a.md",
663            "---\ntype: wiki-page\nsummary: a\n---\n\nfrom [[sources/emails/2026/05/m]]\n",
664        );
665        write_rel(&store, "sources/emails/2026/05/m.md", &doc("email", "m"));
666
667        let s = compute(&store).expect("compute");
668        assert_eq!(s.broken_link_count, 0);
669        assert_eq!(s.orphan_count, 0, "both endpoints are wired");
670    }
671}