italic 0.2.4

A static site generator for your digital garden
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
//! The in-memory doc store threaded through every build phase. Owns all docs in
//! a `BTreeMap<PathBuf, Doc>` keyed by `id_path` — a `BTreeMap` so iteration is
//! naturally sorted by `id_path`, giving every consumer a stable order for free.
//! It is the one-stop-shop for doc iteration: phases mutate docs in parallel
//! through [`DocIndex::par_docs_mut`], read them through [`DocIndex::docs`], and
//! project the read-only [`DocMeta`] view via [`DocIndex::to_doc_metas`].
//!
//! On top of the store it caches two kinds of precomputed listings, both known
//! up front so they evaluate once and are cheap to read from templates:
//!
//! - **Collections** — a named [`Query`] result, stored as an ordered
//!   `Vec<PathBuf>` of `id_path`s. Defined from the `collections:` block in
//!   `config.yaml` (see [`DocIndex::define_collection`]).
//! - **Taxonomies** — a named classification, stored as a keyed family of
//!   collections (`BTreeMap<term, Vec<PathBuf>>`). Built-in `tags` plus any
//!   declared under `taxonomies:` in `config.yaml`; see
//!   [`DocIndex::define_taxonomies`].

use crate::backlinks::Backlinks;
use crate::doc::{Doc, DocMeta};
use crate::query::{OrderKey, Query, SortDir};
use crate::related::{LINKS, Related, idf};
use rayon::prelude::*;
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};

#[derive(Clone, Default)]
pub struct DocIndex {
    /// Keyed by `id_path`. A `BTreeMap` so `docs()`/`par_docs()` iterate in
    /// sorted `id_path` order, which keeps cached listings and outputs stable.
    docs: BTreeMap<PathBuf, Doc>,
    collections: HashMap<String, Vec<PathBuf>>,
    taxonomies: HashMap<String, BTreeMap<String, Vec<PathBuf>>>,
    /// Inverted link graph: `target id_path -> id_paths of docs that link to it`.
    /// The inverse of every doc's `links`, built once by [`define_backlinks`]
    /// after markup populates `doc.links`. Lets [`list_backlinks`] answer in O(1)
    /// instead of scanning every doc, and is the candidate source for `related`.
    backlinks: HashMap<PathBuf, Vec<PathBuf>>,
}

impl DocIndex {
    pub fn new() -> DocIndex {
        DocIndex::default()
    }

    /// Insert (or replace) a doc, keyed by its `id_path`.
    pub fn insert(&mut self, doc: Doc) {
        self.docs.insert(doc.id_path.clone(), doc);
    }

    // --- iteration ---------------------------------------------------------

    /// Sequential view of every doc. Used by `write`, generator queries, and
    /// the `backlinks` adapter.
    pub fn docs(&self) -> impl Iterator<Item = &Doc> {
        self.docs.values()
    }

    /// Parallel mutable view, for the markup and template render loops.
    pub fn par_docs_mut(&mut self) -> impl ParallelIterator<Item = &mut Doc> {
        self.docs.par_iter_mut().map(|(_, doc)| doc)
    }

    /// Read-only parallel companion to [`par_docs_mut`](Self::par_docs_mut).
    pub fn par_docs(&self) -> impl ParallelIterator<Item = &Doc> {
        self.docs.par_iter().map(|(_, doc)| doc)
    }

    /// Project the read-only [`DocMeta`] view used as the frozen snapshot for the
    /// markup/generate phases. Order-independent: wikilink resolution keys off a
    /// stem index with a lexicographic tiebreak, and URL lookups are by id.
    pub fn to_doc_metas(&self) -> Vec<DocMeta> {
        self.docs.values().map(DocMeta::from).collect()
    }

    /// O(1) lookup of a doc by `id_path`.
    pub fn doc(&self, id_path: &Path) -> Option<&Doc> {
        self.docs.get(id_path)
    }

    /// O(1) mutable lookup of a doc by `id_path`. Used by the defaults phase to
    /// fill frontmatter on a collection's members.
    pub fn doc_mut(&mut self, id_path: &Path) -> Option<&mut Doc> {
        self.docs.get_mut(id_path)
    }

    /// O(1) lookup of a doc's `output_path` by `id_path`, for the URL filters.
    pub fn output_path(&self, id_path: &Path) -> Option<&Path> {
        self.docs.get(id_path).map(|d| d.output_path.as_path())
    }

    // --- collections -------------------------------------------------------

    /// Evaluate `query` once over every doc and cache the matching `id_path`s,
    /// in query order, under `name`.
    pub fn define_collection(&mut self, name: &str, query: &Query) {
        let ids = query
            .evaluate(self.docs.values())
            .into_iter()
            .map(|d| d.id_path.clone())
            .collect();
        self.collections.insert(name.to_string(), ids);
    }

    /// Docs of the named collection, in cached order. An unknown name yields an
    /// empty iterator.
    pub fn get_collection(&self, name: &str) -> impl Iterator<Item = &Doc> {
        self.collections
            .get(name)
            .into_iter()
            .flat_map(|ids| ids.iter())
            .filter_map(|id| self.docs.get(id))
    }

    // --- taxonomies --------------------------------------------------------

    /// Build one taxonomy index per configured taxonomy: a `term slug -> docs`
    /// map keyed by the doc's `terms[name]` memberships.
    pub fn define_taxonomies(&mut self, taxonomies: &[String]) {
        for name in taxonomies {
            let key = name.clone();
            self.define_taxonomy(name, move |doc| {
                doc.terms
                    .get(&key)
                    .map(|bucket| bucket.keys().cloned().collect())
                    .unwrap_or_default()
            });
        }
    }

    /// Generic taxonomy builder. `term_fn` returns the term slugs a doc belongs
    /// under; the doc's `id_path` is pushed onto each term's collection. Each
    /// collection is then ordered deterministically (date desc, `id_path`
    /// tiebreak) to match the default query order rather than raw `id_path`
    /// order.
    fn define_taxonomy<F>(&mut self, name: &str, term_fn: F)
    where
        F: Fn(&Doc) -> Vec<String>,
    {
        let mut taxonomy: BTreeMap<String, Vec<PathBuf>> = BTreeMap::new();
        for doc in self.docs.values() {
            for term in term_fn(doc) {
                taxonomy.entry(term).or_default().push(doc.id_path.clone());
            }
        }
        for ids in taxonomy.values_mut() {
            ids.sort_by(|a, b| {
                let da = &self.docs[a];
                let db = &self.docs[b];
                db.date.cmp(&da.date).then_with(|| a.cmp(b))
            });
        }
        self.taxonomies.insert(name.to_string(), taxonomy);
    }

    /// The named taxonomy's `term -> id_path`s map, or `None` if undefined.
    pub fn get_taxonomy(&self, name: &str) -> Option<&BTreeMap<String, Vec<PathBuf>>> {
        self.taxonomies.get(name)
    }

    // --- backlinks ---------------------------------------------------------

    /// Build the inverted link graph from every doc's `links`: for each doc and
    /// each of its outbound targets, record the doc as a linker of that target.
    /// Iterating the `BTreeMap` in `id_path` order means each target's linker
    /// list comes out `id_path`-sorted and deterministic; per-query ordering is
    /// applied by [`list_backlinks`]. Must run after markup populates `doc.links`.
    pub fn define_backlinks(&mut self) {
        let mut backlinks: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();
        for doc in self.docs.values() {
            for target in &doc.links {
                backlinks
                    .entry(target.clone())
                    .or_default()
                    .push(doc.id_path.clone());
            }
        }
        self.backlinks = backlinks;
    }

    /// Docs that link to `target`, ordered and filtered per `opts`. Reads the
    /// cached inverted index ([`define_backlinks`]) — an O(1) lookup rather than
    /// a scan over every doc — then applies `omit`, `order_by`/`sort`, and
    /// `limit` at query time, the way [`get_collection`](Self::get_collection)
    /// consumers layer runtime filtering over a cached listing. An unknown
    /// `target` yields an empty `Vec`.
    pub fn list_backlinks(&self, target: &Path, opts: &Backlinks) -> Vec<&Doc> {
        let omit: std::collections::HashSet<&Path> =
            opts.omit.iter().map(PathBuf::as_path).collect();

        let mut results: Vec<&Doc> = self
            .backlinks
            .get(target)
            .into_iter()
            .flat_map(|ids| ids.iter())
            .filter(|id| !omit.contains(id.as_path()))
            .filter_map(|id| self.docs.get(id))
            .collect();

        results.sort_by(|a, b| {
            let cmp = match opts.order_by {
                OrderKey::Title => a.title.cmp(&b.title),
                OrderKey::Date => a.date.cmp(&b.date),
                OrderKey::Updated => a.updated.cmp(&b.updated),
            };
            let cmp = match opts.sort {
                SortDir::Asc => cmp,
                SortDir::Desc => cmp.reverse(),
            };
            // Stable tiebreak on `id_path` for a total order regardless of the
            // cached linker order.
            cmp.then_with(|| a.id_path.cmp(&b.id_path))
        });

        if let Some(n) = opts.limit {
            results.truncate(n);
        }

        results
    }

    // --- related -----------------------------------------------------------

    /// Docs related to `post`, scored by weighted shared-term overlap across the
    /// namespaces in `opts.weights` and ranked best-first. Each namespace is
    /// either a taxonomy (shared term slugs, via the inverted taxonomy index) or
    /// the [`LINKS`](crate::related::LINKS) graph, where overlap captures three
    /// link relationships at once (symmetric — broader than backlinks alone):
    /// - **backlink** — a doc that links to `post` (`backlinks[post]`);
    /// - **forward link** — a doc `post` links to (`post.links`);
    /// - **shared reference** — a doc that links to the same target `post` links
    ///   to (`backlinks[target]`); bibliographic coupling.
    ///
    /// Scores accumulate `weight * idf(df, n)` per shared term, where `idf`
    /// down-weights terms shared by many docs *relative to corpus size* — so a
    /// rare shared tag or co-citation outweighs a common one (see
    /// [`idf`](crate::related::idf)). The query doc is never related to itself
    /// (the guard only bites on a genuine self-link or shared own-term), and
    /// `opts.omit` drops further docs, both before `limit`. Ties break by `date`
    /// desc then `id_path` asc, matching the other listings. An unknown `post`
    /// yields an empty `Vec`.
    pub fn related(&self, post: &Path, opts: &Related) -> Vec<&Doc> {
        let Some(post_doc) = self.docs.get(post) else {
            return Vec::new();
        };

        let n = self.docs.len();
        let mut scores: HashMap<PathBuf, f64> = HashMap::new();
        for (namespace, weight) in &opts.weights {
            if namespace == LINKS {
                // Backlinks: docs that link to `post`.
                let w = weight * idf(self.link_df(post), n);
                for linker in self.linkers(post) {
                    *scores.entry(linker.clone()).or_default() += w;
                }
                for target in &post_doc.links {
                    let w = weight * idf(self.link_df(target), n);
                    // Forward link: `post` -> `target`.
                    *scores.entry(target.clone()).or_default() += w;
                    // Shared reference: other docs that also link to `target`.
                    for linker in self.linkers(target) {
                        *scores.entry(linker.clone()).or_default() += w;
                    }
                }
            } else if let Some(taxonomy) = self.taxonomies.get(namespace) {
                let Some(bucket) = post_doc.terms.get(namespace) else {
                    continue;
                };
                for term in bucket.keys() {
                    if let Some(ids) = taxonomy.get(term) {
                        let w = weight * idf(ids.len(), n);
                        for id in ids {
                            *scores.entry(id.clone()).or_default() += w;
                        }
                    }
                }
            }
        }

        // Never relate a doc to itself, then honor explicit omissions. Both run
        // before the limit truncates.
        scores.remove(post);
        for omit in &opts.omit {
            scores.remove(omit);
        }

        let mut ranked: Vec<(&Doc, f64)> = scores
            .into_iter()
            .filter_map(|(id, score)| self.docs.get(&id).map(|doc| (doc, score)))
            .collect();
        ranked.sort_by(|(a, sa), (b, sb)| {
            sb.partial_cmp(sa)
                .unwrap_or(std::cmp::Ordering::Equal) // score desc
                .then_with(|| b.date.cmp(&a.date)) // date desc
                .then_with(|| a.id_path.cmp(&b.id_path)) // id_path asc
        });

        let mut docs: Vec<&Doc> = ranked.into_iter().map(|(doc, _)| doc).collect();
        if let Some(n) = opts.limit {
            docs.truncate(n);
        }
        docs
    }

    /// Docs that link to `target` (its backlinks), or an empty slice if none.
    fn linkers(&self, target: &Path) -> &[PathBuf] {
        self.backlinks.get(target).map_or(&[], Vec::as_slice)
    }

    /// Document frequency of a link-graph term `target`: how many docs share it,
    /// i.e. those that link to it plus the target doc itself (which contributes
    /// its own id as a term). Feeds [`idf`](crate::related::idf) so that linking
    /// a widely-cited hub counts for less than a rarely-cited one.
    fn link_df(&self, target: &Path) -> usize {
        self.linkers(target).len() + usize::from(self.docs.contains_key(target))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::query::OrderKey;
    use chrono::{DateTime, NaiveDate, Utc};

    fn at(date: &str) -> DateTime<Utc> {
        NaiveDate::parse_from_str(date, "%Y-%m-%d")
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
    }

    fn doc(id_path: &str, title: &str, date: &str) -> Doc {
        Doc {
            id_path: PathBuf::from(id_path),
            output_path: PathBuf::from(id_path).with_extension("html"),
            title: title.to_string(),
            date: at(date),
            updated: at(date),
            ..Default::default()
        }
    }

    fn index(docs: Vec<Doc>) -> DocIndex {
        let mut index = DocIndex::new();
        for d in docs {
            index.insert(d);
        }
        index
    }

    #[test]
    fn define_collection_filters_and_orders() {
        let mut index = index(vec![
            doc("posts/a.md", "A", "2025-01-01"),
            doc("posts/b.md", "B", "2025-03-01"),
            doc("pages/c.md", "C", "2025-02-01"),
        ]);
        let q = Query {
            path: Some(
                globset::GlobBuilder::new("posts/*.md")
                    .literal_separator(true)
                    .build()
                    .unwrap(),
            ),
            ..Query::default()
        };
        index.define_collection("posts", &q);
        // Default order is date desc: B (Mar) before A (Jan); C is filtered out.
        let titles: Vec<&str> = index
            .get_collection("posts")
            .map(|d| d.title.as_str())
            .collect();
        assert_eq!(titles, vec!["B", "A"]);
    }

    #[test]
    fn get_collection_unknown_name_is_empty() {
        let index = index(vec![doc("a.md", "A", "2025-01-01")]);
        assert_eq!(index.get_collection("nope").count(), 0);
    }

    #[test]
    fn collection_order_is_stable_across_equal_sort_keys() {
        // Same date — the id_path tiebreak must give a deterministic order.
        let mut index = index(vec![
            doc("a.md", "A", "2025-01-01"),
            doc("b.md", "B", "2025-01-01"),
            doc("c.md", "C", "2025-01-01"),
        ]);
        let q = Query {
            order_by: OrderKey::Date,
            ..Query::default()
        };
        index.define_collection("all", &q);
        let ids: Vec<&str> = index
            .get_collection("all")
            .map(|d| d.id_path.to_str().unwrap())
            .collect();
        assert_eq!(ids, vec!["a.md", "b.md", "c.md"]);
    }

    fn with_tags(mut d: Doc, tags: &[&str]) -> Doc {
        let bucket = d.terms.entry("tags".into()).or_default();
        for t in tags {
            bucket.insert((*t).to_string(), (*t).to_string());
        }
        d
    }

    #[test]
    fn define_taxonomies_buckets_by_term_slug() {
        let a = with_tags(doc("a.md", "A", "2025-01-01"), &["rust"]);
        let b = with_tags(doc("b.md", "B", "2025-03-01"), &["rust", "go"]);
        let index = {
            let mut idx = index(vec![a, b]);
            idx.define_taxonomies(&["tags".to_string()]);
            idx
        };
        let tags = index.get_taxonomy("tags").unwrap();
        // `rust` has both, date desc → b (Mar) before a (Jan).
        assert_eq!(
            tags.get("rust").unwrap(),
            &vec![PathBuf::from("b.md"), PathBuf::from("a.md")]
        );
        assert_eq!(tags.get("go").unwrap(), &vec![PathBuf::from("b.md")]);
    }

    #[test]
    fn define_taxonomies_handles_multiple_taxonomies() {
        let mut a = doc("a.md", "A", "2025-01-01");
        a.terms
            .entry("categories".into())
            .or_default()
            .insert("tech".into(), "Tech".into());
        let index = {
            let mut idx = index(vec![a]);
            idx.define_taxonomies(&["tags".to_string(), "categories".to_string()]);
            idx
        };
        // tags taxonomy is defined but empty; categories has the doc.
        assert!(index.get_taxonomy("tags").unwrap().is_empty());
        assert_eq!(
            index
                .get_taxonomy("categories")
                .unwrap()
                .get("tech")
                .unwrap(),
            &vec![PathBuf::from("a.md")]
        );
    }

    #[test]
    fn get_taxonomy_unknown_name_is_none() {
        let index = index(vec![doc("a.md", "A", "2025-01-01")]);
        assert!(index.get_taxonomy("tags").is_none());
    }

    #[test]
    fn output_path_round_trips() {
        let index = index(vec![doc("posts/a.md", "A", "2025-01-01")]);
        assert_eq!(
            index.output_path(Path::new("posts/a.md")),
            Some(Path::new("posts/a.html"))
        );
        assert_eq!(index.output_path(Path::new("missing.md")), None);
    }

    #[test]
    fn to_doc_metas_covers_all_docs() {
        let index = index(vec![
            doc("a.md", "A", "2025-01-01"),
            doc("b.md", "B", "2025-01-02"),
        ]);
        assert_eq!(index.to_doc_metas().len(), 2);
    }

    // --- backlinks ---------------------------------------------------------

    use crate::backlinks::Backlinks;

    fn linking(id_path: &str, title: &str, date: &str, links: &[&str]) -> Doc {
        Doc {
            links: links.iter().map(PathBuf::from).collect(),
            ..doc(id_path, title, date)
        }
    }

    /// Build an index and populate its inverted link graph — the read+classify
    /// pairing for backlink queries.
    fn linked_index(docs: Vec<Doc>) -> DocIndex {
        let mut idx = index(docs);
        idx.define_backlinks();
        idx
    }

    #[test]
    fn list_backlinks_no_backlinks_returns_empty() {
        let index = linked_index(vec![linking("a.md", "A", "2025-01-01", &[])]);
        let results = index.list_backlinks(Path::new("b.md"), &Backlinks::default());
        assert!(results.is_empty());
    }

    #[test]
    fn list_backlinks_finds_single_backlink() {
        let index = linked_index(vec![
            linking("a.md", "A", "2025-01-01", &["b.md"]),
            linking("b.md", "B", "2025-01-02", &[]),
        ]);
        let results = index.list_backlinks(Path::new("b.md"), &Backlinks::default());
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].title, "A");
    }

    #[test]
    fn list_backlinks_finds_multiple_backlinks() {
        let index = linked_index(vec![
            linking("a.md", "A", "2025-01-01", &["b.md"]),
            linking("c.md", "C", "2025-01-03", &["b.md", "other.md"]),
            linking("d.md", "D", "2025-01-02", &["other.md"]),
        ]);
        let results = index.list_backlinks(Path::new("b.md"), &Backlinks::default());
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn list_backlinks_default_order_is_date_desc() {
        let index = linked_index(vec![
            linking("a.md", "A", "2025-01-01", &["target.md"]),
            linking("b.md", "B", "2025-02-01", &["target.md"]),
            linking("c.md", "C", "2025-03-01", &["target.md"]),
        ]);
        let results = index.list_backlinks(Path::new("target.md"), &Backlinks::default());
        let titles: Vec<&str> = results.iter().map(|d| d.title.as_str()).collect();
        assert_eq!(titles, vec!["C", "B", "A"]);
    }

    #[test]
    fn list_backlinks_order_by_title_asc() {
        let index = linked_index(vec![
            linking("a.md", "Charlie", "2025-01-01", &["target.md"]),
            linking("b.md", "Alpha", "2025-01-02", &["target.md"]),
            linking("c.md", "Bravo", "2025-01-03", &["target.md"]),
        ]);
        let opts = Backlinks {
            order_by: OrderKey::Title,
            sort: SortDir::Asc,
            ..Default::default()
        };
        let results = index.list_backlinks(Path::new("target.md"), &opts);
        let titles: Vec<&str> = results.iter().map(|d| d.title.as_str()).collect();
        assert_eq!(titles, vec!["Alpha", "Bravo", "Charlie"]);
    }

    #[test]
    fn list_backlinks_excludes_omitted_docs() {
        let index = linked_index(vec![
            linking("a.md", "A", "2025-01-01", &["target.md"]),
            linking("b.md", "B", "2025-02-01", &["target.md"]),
            linking("c.md", "C", "2025-03-01", &["target.md"]),
        ]);
        let opts = Backlinks {
            omit: vec![PathBuf::from("b.md")],
            ..Default::default()
        };
        let results = index.list_backlinks(Path::new("target.md"), &opts);
        let titles: Vec<&str> = results.iter().map(|d| d.title.as_str()).collect();
        assert_eq!(titles, vec!["C", "A"]);
    }

    #[test]
    fn list_backlinks_omit_self_drops_self_link() {
        // The common case: a page links to itself but should not list itself
        // among its own backlinks.
        let index = linked_index(vec![
            linking("a.md", "A", "2025-01-01", &["target.md"]),
            linking("target.md", "Target", "2025-01-02", &["target.md"]),
        ]);
        let opts = Backlinks {
            omit: vec![PathBuf::from("target.md")],
            ..Default::default()
        };
        let results = index.list_backlinks(Path::new("target.md"), &opts);
        let titles: Vec<&str> = results.iter().map(|d| d.title.as_str()).collect();
        assert_eq!(titles, vec!["A"]);
    }

    #[test]
    fn list_backlinks_applies_limit() {
        let index = linked_index(vec![
            linking("a.md", "A", "2025-01-01", &["target.md"]),
            linking("b.md", "B", "2025-02-01", &["target.md"]),
            linking("c.md", "C", "2025-03-01", &["target.md"]),
        ]);
        let opts = Backlinks {
            limit: Some(2),
            ..Default::default()
        };
        // Default order is date desc, so the newest two survive the truncate.
        let results = index.list_backlinks(Path::new("target.md"), &opts);
        let titles: Vec<&str> = results.iter().map(|d| d.title.as_str()).collect();
        assert_eq!(titles, vec!["C", "B"]);
    }

    #[test]
    fn list_backlinks_omit_then_limit_compose() {
        // omit drops a doc first, then limit truncates the remainder.
        let index = linked_index(vec![
            linking("a.md", "A", "2025-01-01", &["target.md"]),
            linking("b.md", "B", "2025-02-01", &["target.md"]),
            linking("c.md", "C", "2025-03-01", &["target.md"]),
        ]);
        let opts = Backlinks {
            omit: vec![PathBuf::from("c.md")],
            limit: Some(1),
            ..Default::default()
        };
        let results = index.list_backlinks(Path::new("target.md"), &opts);
        let titles: Vec<&str> = results.iter().map(|d| d.title.as_str()).collect();
        assert_eq!(titles, vec!["B"]);
    }

    #[test]
    fn list_backlinks_does_not_include_self_unless_self_links() {
        // Source linking to itself should still appear in its own backlinks.
        let index = linked_index(vec![linking("a.md", "A", "2025-01-01", &["a.md"])]);
        let results = index.list_backlinks(Path::new("a.md"), &Backlinks::default());
        assert_eq!(results.len(), 1);
    }

    // --- related -----------------------------------------------------------

    use crate::related::{LINKS, Related};

    /// Build an index and populate every cached listing `related` reads: the
    /// taxonomy buckets and the inverted link graph.
    fn related_index(docs: Vec<Doc>) -> DocIndex {
        let mut idx = index(docs);
        idx.define_taxonomies(&["tags".to_string()]);
        idx.define_backlinks();
        idx
    }

    fn weights(pairs: &[(&str, f64)]) -> Related {
        Related {
            weights: pairs.iter().map(|(n, w)| (n.to_string(), *w)).collect(),
            ..Default::default()
        }
    }

    fn titles(docs: &[&Doc]) -> Vec<String> {
        docs.iter().map(|d| d.title.clone()).collect()
    }

    #[test]
    fn related_ranks_by_shared_tag_overlap() {
        let index = related_index(vec![
            with_tags(doc("p.md", "P", "2025-01-01"), &["rust", "ssg"]),
            with_tags(doc("a.md", "A", "2025-01-02"), &["rust", "ssg"]), // 2 shared
            with_tags(doc("b.md", "B", "2025-01-03"), &["rust"]),        // 1 shared
        ]);
        let results = index.related(Path::new("p.md"), &weights(&[("tags", 1.0)]));
        assert_eq!(titles(&results), vec!["A", "B"]);
    }

    #[test]
    fn related_weights_reorder_namespaces() {
        // A shares a tag with P; B is a forward link from P. The heavier
        // namespace ranks its doc first.
        let docs = || {
            vec![
                with_tags(linking("p.md", "P", "2025-01-01", &["b.md"]), &["rust"]),
                with_tags(doc("a.md", "A", "2025-01-02"), &["rust"]), // tag overlap
                doc("b.md", "B", "2025-01-03"),                       // forward link
            ]
        };
        let tags_heavy = related_index(docs());
        let r = tags_heavy.related(Path::new("p.md"), &weights(&[("tags", 3.0), (LINKS, 1.0)]));
        assert_eq!(titles(&r), vec!["A", "B"]);

        let links_heavy = related_index(docs());
        let r = links_heavy.related(Path::new("p.md"), &weights(&[("tags", 1.0), (LINKS, 3.0)]));
        assert_eq!(titles(&r), vec!["B", "A"]);
    }

    #[test]
    fn related_never_includes_self() {
        // Shared tags and a self-link both point a doc at itself; neither should
        // surface it in its own list.
        let index = related_index(vec![
            with_tags(linking("p.md", "P", "2025-01-01", &["p.md"]), &["rust"]),
            with_tags(doc("a.md", "A", "2025-01-02"), &["rust"]),
        ]);
        let results = index.related(Path::new("p.md"), &weights(&[("tags", 1.0), (LINKS, 1.0)]));
        assert_eq!(titles(&results), vec!["A"]);
    }

    #[test]
    fn related_co_citation_without_shared_tags() {
        // P and B both link to C, share no tags — still related via the graph.
        let index = related_index(vec![
            linking("p.md", "P", "2025-01-01", &["c.md"]),
            linking("b.md", "B", "2025-01-02", &["c.md"]),
            doc("c.md", "C", "2025-01-03"),
        ]);
        let results = index.related(Path::new("p.md"), &weights(&[(LINKS, 1.0)]));
        // C (forward link) and B (co-citation) are both related.
        let mut got = titles(&results);
        got.sort();
        assert_eq!(got, vec!["B", "C"]);
    }

    #[test]
    fn related_forward_and_backlink_are_symmetric() {
        let index = related_index(vec![
            linking("a.md", "A", "2025-01-01", &["b.md"]),
            doc("b.md", "B", "2025-01-02"),
        ]);
        // Forward: A links B → B is related to A.
        let from_a = index.related(Path::new("a.md"), &weights(&[(LINKS, 1.0)]));
        assert_eq!(titles(&from_a), vec!["B"]);
        // Backlink: B is linked by A → A is related to B.
        let from_b = index.related(Path::new("b.md"), &weights(&[(LINKS, 1.0)]));
        assert_eq!(titles(&from_b), vec!["A"]);
    }

    #[test]
    fn related_tie_break_is_date_then_id_path() {
        // All three share the tag, so scores tie; order falls back to date desc
        // then id_path asc. b/c share a date, so id_path breaks them.
        let index = related_index(vec![
            with_tags(doc("p.md", "P", "2025-01-01"), &["rust"]),
            with_tags(doc("a.md", "A", "2025-03-01"), &["rust"]), // newest
            with_tags(doc("b.md", "B", "2025-02-01"), &["rust"]),
            with_tags(doc("c.md", "C", "2025-02-01"), &["rust"]), // same date as b
        ]);
        let results = index.related(Path::new("p.md"), &weights(&[("tags", 1.0)]));
        assert_eq!(titles(&results), vec!["A", "B", "C"]);
    }

    #[test]
    fn related_limit_truncates_and_absent_returns_all() {
        let index = related_index(vec![
            with_tags(doc("p.md", "P", "2025-01-01"), &["rust"]),
            with_tags(doc("a.md", "A", "2025-03-01"), &["rust"]),
            with_tags(doc("b.md", "B", "2025-02-01"), &["rust"]),
        ]);
        let all = index.related(Path::new("p.md"), &weights(&[("tags", 1.0)]));
        assert_eq!(all.len(), 2);

        let limited = index.related(
            Path::new("p.md"),
            &Related {
                limit: Some(1),
                ..weights(&[("tags", 1.0)])
            },
        );
        assert_eq!(titles(&limited), vec!["A"]);
    }

    #[test]
    fn related_omit_excludes_docs() {
        let index = related_index(vec![
            with_tags(doc("p.md", "P", "2025-01-01"), &["rust"]),
            with_tags(doc("a.md", "A", "2025-03-01"), &["rust"]),
            with_tags(doc("b.md", "B", "2025-02-01"), &["rust"]),
        ]);
        let results = index.related(
            Path::new("p.md"),
            &Related {
                omit: vec![PathBuf::from("a.md")],
                ..weights(&[("tags", 1.0)])
            },
        );
        assert_eq!(titles(&results), vec!["B"]);
    }

    #[test]
    fn related_empty_doc_relates_to_nothing() {
        let index = related_index(vec![
            doc("p.md", "P", "2025-01-01"),
            with_tags(doc("a.md", "A", "2025-01-02"), &["rust"]),
        ]);
        let results = index.related(Path::new("p.md"), &weights(&[("tags", 1.0), (LINKS, 1.0)]));
        assert!(results.is_empty());
    }

    #[test]
    fn related_unknown_post_is_empty() {
        let index = related_index(vec![with_tags(doc("p.md", "P", "2025-01-01"), &["rust"])]);
        let results = index.related(Path::new("missing.md"), &weights(&[("tags", 1.0)]));
        assert!(results.is_empty());
    }
}