rumdl 0.2.60

A fast Markdown linter written in Rust (Ru(st) MarkDown Linter)
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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
//! Shared markdown file discovery semantics.
//!
//! The CLI walker (`file_processor::discovery` in the binary crate) and the
//! LSP workspace index scanner answer the same question: which files does
//! rumdl process here? The pieces of that answer that must never diverge
//! live in this module:
//!
//! - the markdown extension set and how it is matched,
//! - the final source-kind gate for each adapter's capabilities,
//! - how ignore-file handling (`.gitignore`, `.markdownlintignore`, hidden
//!   entries) is configured on a walker,
//! - how `exclude` patterns from config are expanded and matched.
//!
//! Callers still differ deliberately: the LSP skips `.git`/`node_modules`/
//! `target` outright as an editor-performance safety net, while the CLI
//! walks whatever gitignore semantics allow.

use globset::{Glob, GlobMatcher};
use std::borrow::Cow;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};

/// Glob metacharacters recognized when deciding whether an include pattern
/// names files explicitly.
const GLOB_METACHARS: &[char] = &['*', '?', '[', ']', '{', '}'];

/// The file-name glob of an `include` pattern that explicitly names files,
/// if it does.
///
/// A pattern names files explicitly when its final path component pins a
/// literal dotted suffix: a wildcard stem ending in a literal extension
/// chain (`**/*.md.jinja` yields `*.md.jinja`) or a fully literal file name
/// with an extension (`templates/NOTES.tmpl` yields `NOTES.tmpl`). Such
/// patterns widen the lintable-file filter beyond the standard markdown
/// extensions: the user has spelled out exactly which files to process.
///
/// Directory patterns (`docs/`, `docs/**`), bare wildcards (`*`, `**/*`),
/// patterns whose extension itself contains wildcards (`*.md*`,
/// `*.{md,jinja}`), and negations (`!drafts/*.md.jinja`) yield `None`; they
/// express "look here" or "not this", not "this exact kind of file", so the
/// markdown-only filter stays in force for them.
pub fn explicit_file_name_glob(pattern: &str) -> Option<&str> {
    if pattern.starts_with('!') {
        return None;
    }
    let file_name = pattern.rsplit('/').next().unwrap_or(pattern);
    if file_name.is_empty() {
        return None;
    }
    // The literal tail after the last glob metacharacter (the whole
    // component when there is none) must end in a non-empty extension.
    let literal_tail = match file_name.rfind(GLOB_METACHARS) {
        Some(idx) => &file_name[idx + 1..],
        None => file_name,
    };
    match literal_tail.rsplit_once('.') {
        Some((_, ext)) if !ext.is_empty() => Some(file_name),
        _ => None,
    }
}

/// Compiled matchers for the explicitly-named files in a set of config
/// `include` patterns (see [`explicit_file_name_glob`]).
///
/// The CLI walker consults this in two places that otherwise restrict
/// discovery to markdown extensions: the walker's file-type filter and the
/// final lintable-file filter. The type filter can only match file names,
/// so it uses the (over-inclusive) file-name globs; the final filter is
/// the precise gate and matches the full pattern against the root-relative
/// path. Without the path check, a broad sibling pattern like `docs/**`
/// would inherit the non-standard-extension allowance of an explicit
/// pattern like `templates/NOTES.tmpl` for every file sharing its name.
///
/// Path matching follows gitignore anchoring: patterns without a `/` match
/// at any depth, patterns with one are anchored to the root the relative
/// path was computed against. `*` does not cross directory separators.
///
/// Invalid globs are skipped silently; the caller's override handling
/// already warns about unparseable include patterns.
pub struct ExplicitIncludeMatchers {
    matchers: Vec<ExplicitInclude>,
}

struct ExplicitInclude {
    file_name_glob: String,
    path_matcher: GlobMatcher,
}

impl ExplicitIncludeMatchers {
    pub fn new(patterns: &[String]) -> Self {
        let matchers = patterns
            .iter()
            .filter_map(|pattern| {
                let file_name_glob = explicit_file_name_glob(pattern)?;
                let path_glob = if let Some(anchored) = pattern.strip_prefix('/') {
                    anchored.to_string()
                } else if pattern.contains('/') {
                    pattern.clone()
                } else {
                    format!("**/{pattern}")
                };
                let path_matcher = globset::GlobBuilder::new(&path_glob)
                    .literal_separator(true)
                    .build()
                    .ok()?
                    .compile_matcher();
                Some(ExplicitInclude {
                    file_name_glob: file_name_glob.to_string(),
                    path_matcher,
                })
            })
            .collect();
        Self { matchers }
    }

    pub fn is_empty(&self) -> bool {
        self.matchers.is_empty()
    }

    /// The file-name globs, e.g. for registering on a walker type filter.
    pub fn file_name_globs(&self) -> impl Iterator<Item = &str> {
        self.matchers.iter().map(|m| m.file_name_glob.as_str())
    }

    /// Whether the root-relative `path` matches any explicit include
    /// pattern in full.
    pub fn matches_relative_path(&self, path: &str) -> bool {
        self.matchers.iter().any(|m| m.path_matcher.is_match(path))
    }
}

/// Source kinds an adapter can interpret after a path passes include matching.
///
/// The CLI can extract Markdown from Rust doc comments, while the language
/// server indexes complete Markdown documents and must not parse a Rust source
/// file as if the whole file were Markdown. A CLI `--include` is stronger still:
/// it explicitly asks rumdl to process whatever the pattern selects.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LintableFileMode {
    Markdown,
    MarkdownAndRust,
    Any,
}

/// The shared final gate for files yielded by CLI and LSP discovery walks.
///
/// Include overrides decide *where* to look. This selector decides whether a
/// matching file is a source the adapter can interpret. Explicit config
/// includes can name template-like Markdown files beyond the standard
/// extensions; Rust remains capability-gated even when explicitly named.
pub struct LintablePathSelector {
    base: Option<PathBuf>,
    explicit: ExplicitIncludeMatchers,
    mode: LintableFileMode,
}

impl LintablePathSelector {
    pub fn new(base: Option<&Path>, includes: &[String], mode: LintableFileMode) -> Self {
        Self {
            base: base.map(Path::to_path_buf),
            explicit: ExplicitIncludeMatchers::new(includes),
            mode,
        }
    }

    /// Whether an included path is a source this adapter can interpret.
    pub fn keeps(&self, path: &Path) -> bool {
        if self.mode == LintableFileMode::Any {
            return true;
        }
        if has_markdown_extension(path) {
            return true;
        }

        // Rust doc-comment extraction currently dispatches on lowercase `.rs`.
        // Keep this capability gate identical to the downstream processor.
        let is_rust = path.extension().and_then(OsStr::to_str) == Some("rs");
        if is_rust {
            return self.mode == LintableFileMode::MarkdownAndRust;
        }

        match self.base.as_deref().and_then(|base| path_relative_to(path, base)) {
            Some(relative) => self.explicit.matches_relative_path(&relative),
            // Outside the pattern base only unanchored patterns can still apply;
            // matching the full path covers those.
            None => self.explicit.matches_relative_path(&path.to_string_lossy()),
        }
    }

    /// Apply the corresponding coarse file-type filter to a discovery walk.
    /// [`Self::keeps`] remains the precise final gate because type filters only
    /// see file names, not root-relative include paths.
    pub fn configure_types(&self, builder: &mut ignore::WalkBuilder) -> Result<(), ignore::Error> {
        if self.mode == LintableFileMode::Any {
            return Ok(());
        }

        let mut types = ignore::types::TypesBuilder::new();
        types.add_defaults();
        for extension in MARKDOWN_EXTENSIONS {
            types.add("markdown", &any_case_extension_glob(extension))?;
        }
        types.select("markdown");
        if self.mode == LintableFileMode::MarkdownAndRust {
            types.add("rustdoc", "*.rs")?;
            types.select("rustdoc");
        }
        for glob in self.explicit.file_name_globs() {
            types.add("configinclude", glob)?;
        }
        if !self.explicit.is_empty() {
            types.select("configinclude");
        }
        builder.types(types.build()?);
        Ok(())
    }
}

/// File extensions rumdl treats as markdown, lowercase.
pub const MARKDOWN_EXTENSIONS: &[&str] = &["md", "markdown", "mdx", "mkd", "mkdn", "mdown", "mdwn", "qmd", "rmd"];

/// Whether `ext` is a markdown extension. Matches case-insensitively so
/// conventional variants like `Rmd` (and shouting-case `MD`) qualify.
#[inline]
pub fn is_markdown_extension(ext: &OsStr) -> bool {
    ext.to_str()
        .is_some_and(|s| MARKDOWN_EXTENSIONS.iter().any(|known| s.eq_ignore_ascii_case(known)))
}

/// Whether `path` has a markdown extension.
#[inline]
pub fn has_markdown_extension(path: &Path) -> bool {
    path.extension().is_some_and(is_markdown_extension)
}

/// A glob selecting `ext` in any letter case, as `*.[mM][dD]` for `md`.
///
/// Walk type globs match case-sensitively, so a plain `*.md` hides `README.MD`
/// from a directory scan even though [`is_markdown_extension`] calls it
/// markdown and naming the file on the command line lints it. Deriving the glob
/// from the same extension keeps the walk's filter from being narrower than the
/// definition it stands in for.
pub fn any_case_extension_glob(ext: &str) -> String {
    let mut glob = String::with_capacity(2 + ext.len() * 4);
    glob.push_str("*.");
    for ch in ext.chars() {
        if ch.is_ascii_alphabetic() {
            glob.push('[');
            glob.push(ch.to_ascii_lowercase());
            glob.push(ch.to_ascii_uppercase());
            glob.push(']');
        } else {
            glob.push(ch);
        }
    }
    glob
}

/// Ignore-handling options applied to a markdown discovery walk.
#[derive(Debug, Clone)]
pub struct MarkdownWalkOptions {
    /// Honor `.gitignore`, `.ignore`, global gitignore, `.git/info/exclude`,
    /// and parent ignore files. Driven by `global.respect_gitignore`.
    pub respect_gitignore: bool,
    /// Skip `.git`, `node_modules`, and `target` directories outright, even
    /// when gitignore handling is disabled or would not cover them.
    pub skip_vendor_dirs: bool,
}

impl Default for MarkdownWalkOptions {
    fn default() -> Self {
        Self {
            respect_gitignore: true,
            skip_vendor_dirs: false,
        }
    }
}

/// Whether a walk over `roots` stops reading gitignores at the repository root.
///
/// Git reads no `.gitignore` above the repository root, so a walk that does hides
/// files `git check-ignore` reports as visible. Worse, such a file can hide a
/// whole directory, and a pruned directory is never descended into, so no include
/// pattern gets the chance to name anything inside it.
///
/// Outside a repository there is no root to stop at, and ignore files are all a
/// walk has to go on, so there they keep applying upward. One walk has one
/// setting for all of its roots, so the boundary is only applied when every root
/// has a repository to bound it.
pub fn stops_at_repository_root<P: AsRef<Path>>(roots: &[P]) -> bool {
    !roots.is_empty() && roots.iter().all(|root| in_repository(root.as_ref()))
}

/// Whether `path` sits inside a git or jujutsu repository.
///
/// A `.git` entry is a directory in an ordinary clone and a file in a worktree or
/// submodule, so existence alone is the marker. This recognizes a repository the
/// same way the walker does, which is what puts the boundary in the same place.
fn in_repository(path: &Path) -> bool {
    let Ok(absolute) = std::fs::canonicalize(path) else {
        return false;
    };
    absolute
        .ancestors()
        .any(|dir| dir.join(".git").exists() || dir.join(".jj").exists())
}

/// Apply the shared ignore-handling configuration to a walker over `roots`.
///
/// Hidden entries are always walked (a hidden `docs/.pages.md` lints the
/// same as a visible one); generated content is kept out by gitignore
/// semantics and, for callers that opt in, the vendor-directory skip.
/// `.markdownlintignore` is honored for markdownlint compatibility.
///
/// The roots decide where gitignore reading stops, so a caller passes the same
/// ones it walks.
pub fn apply_markdown_walk_options<P: AsRef<Path>>(
    builder: &mut ignore::WalkBuilder,
    roots: &[P],
    options: &MarkdownWalkOptions,
) {
    let gitignore = options.respect_gitignore;
    builder
        .ignore(gitignore)
        .git_ignore(gitignore)
        .git_global(gitignore)
        .git_exclude(gitignore)
        .parents(gitignore)
        .hidden(false)
        // This setting does double duty in the walker: it gates gitignore
        // handling on a repository being present, and it is what stops the walk
        // reading gitignores above the repository root. Inside a repository both
        // are wanted. Outside one, requiring a repository would drop `.gitignore`
        // handling entirely, and there is no root to stop at in any case.
        .require_git(stops_at_repository_root(roots))
        .add_custom_ignore_filename(".markdownlintignore");

    if options.skip_vendor_dirs {
        let roots: Vec<PathBuf> = roots.iter().map(|root| root.as_ref().to_path_buf()).collect();
        builder.filter_entry(move |entry| {
            if roots.iter().any(|root| root == entry.path()) {
                return true;
            }
            let name = entry.file_name().to_str().unwrap_or("");
            name != ".git" && name != "node_modules" && name != "target"
        });
    }
}

/// Build a walker over `root` configured with the shared options.
pub fn markdown_walk_builder(root: &Path, options: &MarkdownWalkOptions) -> ignore::WalkBuilder {
    let mut builder = ignore::WalkBuilder::new(root);
    apply_markdown_walk_options(&mut builder, &[root], options);
    builder
}

/// A complete, configured Markdown workspace scan.
///
/// This owns the selection policy shared by full scans and incremental file
/// events: standard Markdown extensions, explicit nonstandard file includes,
/// include filtering, excludes, ignore files, and optional vendor-directory
/// pruning. Adapters choose the options; they do not reconstruct the policy.
pub struct MarkdownWorkspaceScan<'a> {
    options: &'a MarkdownWalkOptions,
    includes: &'a [String],
    excludes: &'a ExcludeMatchers,
}

impl<'a> MarkdownWorkspaceScan<'a> {
    pub fn new(options: &'a MarkdownWalkOptions, includes: &'a [String], excludes: &'a ExcludeMatchers) -> Self {
        Self {
            options,
            includes,
            excludes,
        }
    }

    /// Collect all selected files under `roots`.
    pub fn collect(&self, roots: &[PathBuf]) -> Vec<PathBuf> {
        let mut files = Vec::new();
        for root in roots {
            let selection = RootSelection::new(root, self.includes);
            let mut builder = markdown_walk_builder(root, self.options);
            selection.configure_walk(&mut builder);

            for result in builder.build() {
                match result {
                    Ok(entry)
                        if entry.file_type().is_some_and(|file_type| file_type.is_file())
                            && selection.is_lintable(entry.path())
                            && !self.excluded(root, entry.path()) =>
                    {
                        files.push(entry.into_path());
                    }
                    Ok(_) => {}
                    Err(error) => log::warn!("Error scanning {}: {error}", root.display()),
                }
            }
        }
        files.sort();
        files.dedup();
        files
    }

    /// Whether an incremental file event would be absent from a full scan.
    pub fn path_is_ignored(&self, roots: &[PathBuf], path: &Path) -> bool {
        let Some(root) = roots
            .iter()
            .filter(|root| path.starts_with(root))
            .max_by_key(|root| root.components().count())
        else {
            return false;
        };

        let selection = RootSelection::new(root, self.includes);
        if !selection.selects(path) || self.excluded(root, path) {
            return true;
        }

        if self.options.skip_vendor_dirs
            && let Ok(relative) = path.strip_prefix(root)
            && relative.components().any(|component| {
                matches!(component, std::path::Component::Normal(name) if name == ".git" || name == "node_modules" || name == "target")
            })
        {
            return true;
        }

        let target = path.to_path_buf();
        let mut builder = markdown_walk_builder(root, self.options);
        selection.configure_walk(&mut builder);
        // `filter_entry` replaces the vendor filter, which was checked above.
        builder.filter_entry(move |entry| target.starts_with(entry.path()));
        !builder.build().flatten().any(|entry| entry.path() == path)
    }

    fn excluded(&self, root: &Path, path: &Path) -> bool {
        self.excludes
            .excludes_file(path_relative_to(path, root).as_deref(), path)
    }
}

struct RootSelection {
    lintable: LintablePathSelector,
    overrides: Option<ignore::overrides::Override>,
}

impl RootSelection {
    fn new(root: &Path, includes: &[String]) -> Self {
        let normalized: Vec<String> = includes
            .iter()
            .map(|pattern| normalize_pattern_for_base(pattern, Some(root)))
            .collect();
        let overrides = if normalized.is_empty() {
            None
        } else {
            let mut builder = ignore::overrides::OverrideBuilder::new(root);
            for pattern in &normalized {
                if let Err(error) = builder.add(pattern) {
                    log::warn!("Invalid include pattern '{pattern}': {error}");
                }
            }
            builder.build().ok()
        };
        Self {
            lintable: LintablePathSelector::new(Some(root), &normalized, LintableFileMode::Markdown),
            overrides,
        }
    }

    fn configure_walk(&self, builder: &mut ignore::WalkBuilder) {
        if let Err(error) = self.lintable.configure_types(builder) {
            log::warn!("Failed to configure workspace source types: {error}");
        }
        if let Some(overrides) = &self.overrides {
            builder.overrides(overrides.clone());
        }
    }

    fn selects(&self, path: &Path) -> bool {
        self.overrides
            .as_ref()
            .is_none_or(|overrides| overrides.matched(path, false).is_whitelist())
            && self.is_lintable(path)
    }

    fn is_lintable(&self, path: &Path) -> bool {
        self.lintable.keeps(path)
    }
}

/// Drop Windows' verbatim `\\?\` prefix from a canonicalized path string.
///
/// `std::fs::canonicalize` returns the verbatim form (`\\?\C:\Users\dev`) on
/// Windows. That form is useless for pattern matching: it does not compare
/// equal to the ordinary paths rumdl works with, and normalizing its
/// separators for globbing mangles it into `//?/C:/Users/dev`, which matches
/// nothing. Only a drive path (`\\?\C:\...`) and a UNC share
/// (`\\?\UNC\server\share` -> `\\server\share`) are unwrapped; any other
/// verbatim path names a device namespace that has no ordinary equivalent, so
/// it is left alone.
///
/// Pure string logic, compiled on every platform so it stays under test where
/// Windows is not available. Only the call sites are Windows-specific, and on
/// other platforms no path ever carries this prefix.
fn strip_verbatim_prefix(path: &str) -> Cow<'_, str> {
    // `\\?\UNC\server\share` -> `\\server\share`. The remainder already starts
    // with one separator, so restoring the UNC form needs one more prepended.
    if let Some(rest) = path.strip_prefix(r"\\?\UNC")
        && rest.starts_with('\\')
    {
        return Cow::Owned(format!(r"\{rest}"));
    }
    let Some(rest) = path.strip_prefix(r"\\?\") else {
        return Cow::Borrowed(path);
    };
    let is_drive_path = rest.as_bytes().get(1) == Some(&b':');
    if is_drive_path {
        Cow::Borrowed(rest)
    } else {
        Cow::Borrowed(path)
    }
}

/// Canonicalize `path` for pattern matching, or `None` when it cannot be
/// resolved (a missing or unreadable file).
///
/// Canonical form is what patterns are matched against, so a symlinked
/// location (`/home/dev` -> `/mnt/dev`, or a macOS `/var` -> `/private/var`)
/// still matches. Windows' verbatim prefix is removed (see
/// [`strip_verbatim_prefix`]).
pub fn canonicalize_for_matching(path: &Path) -> Option<PathBuf> {
    let canonical = path.canonicalize().ok()?;
    if !cfg!(windows) {
        return Some(canonical);
    }
    let as_str = canonical.to_string_lossy();
    Some(PathBuf::from(strip_verbatim_prefix(&as_str).as_ref()))
}

/// The user's home directory, or `None` when it cannot be resolved.
///
/// Canonicalized for matching (see [`canonicalize_for_matching`]), falling
/// back to the path as reported when it cannot be canonicalized.
///
/// Wasm and WASI builds have no home directory to resolve, so patterns keep
/// their `~` there (see [`expand_home_prefix`]).
fn home_dir() -> Option<PathBuf> {
    #[cfg(feature = "native")]
    {
        use etcetera::{BaseStrategy, choose_base_strategy};
        choose_base_strategy()
            .ok()
            .map(|s| canonicalize_for_matching(s.home_dir()).unwrap_or_else(|| s.home_dir().to_path_buf()))
    }
    #[cfg(not(feature = "native"))]
    {
        None
    }
}

/// Expand a leading `~` in a path pattern to the user's home directory, so a
/// user-level config (`~/.config/rumdl/rumdl.toml`) can name a home path
/// without hardcoding a username.
///
/// Only a bare `~` and a `~/` prefix expand. `~` is a legal filename character
/// everywhere else (editor backups like `notes.md~`, a literal `docs/~drafts`),
/// so it is left alone there. `~user` is not expanded either: resolving another
/// user's home needs the password database, and treating it as the current
/// user's home would silently match the wrong directory.
///
/// The expansion is a glob pattern, so separators are normalized to `/` on
/// Windows: `\` is globset's escape character, and matched paths are normalized
/// the same way (see [`path_relative_to`]).
pub fn expand_home_prefix(pattern: &str) -> Cow<'_, str> {
    // Resolve the home directory only for a pattern that references it: every
    // other pattern would otherwise pay for the lookup and its canonicalization.
    if !has_home_prefix(pattern) {
        return Cow::Borrowed(pattern);
    }
    expand_home_prefix_impl(pattern, home_dir().as_deref())
}

/// Whether `pattern` starts with a home reference (`~` or `~/`).
fn has_home_prefix(pattern: &str) -> bool {
    pattern == "~" || pattern.starts_with("~/")
}

fn expand_home_prefix_impl<'a>(pattern: &'a str, home: Option<&Path>) -> Cow<'a, str> {
    let Some(suffix) = (if pattern == "~" {
        Some("")
    } else {
        pattern.strip_prefix("~/")
    }) else {
        return Cow::Borrowed(pattern);
    };
    let Some(home) = home else {
        return Cow::Borrowed(pattern);
    };

    let home = normalize_pattern_separators(home.to_string_lossy());
    let home = home.trim_end_matches('/');
    if suffix.is_empty() {
        Cow::Owned(home.to_string())
    } else {
        Cow::Owned(format!("{home}/{suffix}"))
    }
}

/// Normalize path separators to `/` for glob matching. On Windows `\` is
/// globset's escape character, so a native path must be rewritten before it can
/// be used as - or matched against - a pattern. No-op on Unix, where `\` is a
/// legal filename character.
fn normalize_pattern_separators(path: Cow<'_, str>) -> Cow<'_, str> {
    if cfg!(windows) && path.contains('\\') {
        Cow::Owned(path.replace('\\', "/"))
    } else {
        path
    }
}

/// Normalize a config path pattern for matching against paths discovered under
/// `base`: expand a leading `~`, then rewrite an absolute pattern as one
/// relative to `base` when `base` contains it.
///
/// The rewrite is what makes an absolute pattern usable as a walker override:
/// the `ignore` crate reads a leading `/` as "anchored to the walk base", so
/// `/home/dev/docs/**` would otherwise be understood as
/// `<base>/home/dev/docs/**` and match nothing. A pattern pointing outside
/// `base` is left absolute - nothing under this walk can match it, which is the
/// correct outcome.
///
/// A pattern can also name `base`'s location through a symlink
/// (`/var/folders/…` for a base at `/private/var/folders/…`), which no strip of
/// `base` in either form removes. Its leading literal components are then
/// resolved, giving the same location in the base's own spelling. Only that
/// prefix is rewritten and the strip consumes it, so what survives is the
/// pattern as written. A pattern whose *first* component holds a wildcard or a
/// brace alternation has no such prefix and stays absolute.
pub fn normalize_pattern_for_base(pattern: &str, base: Option<&Path>) -> String {
    let expanded = expand_home_prefix(pattern);
    let Some(base) = base else {
        return expanded.into_owned();
    };
    if !is_absolute_pattern(&expanded) {
        return expanded.into_owned();
    }

    if let Some(relative) = strip_base_prefix(Path::new(expanded.as_ref()), base) {
        return normalize_pattern_separators(relative.to_string_lossy()).into_owned();
    }
    if let Some(canonical_pattern) = canonicalize_pattern_prefix(&expanded)
        && let Some(relative) = strip_base_prefix(Path::new(&canonical_pattern), base)
    {
        return normalize_pattern_separators(relative.to_string_lossy()).into_owned();
    }
    expanded.into_owned()
}

/// `pattern` with `base` removed, trying the base as given and canonicalized so
/// a symlinked or non-canonical base (macOS `/var`, a Windows 8.3 short name)
/// still strips. `None` when the pattern does not live under `base`.
fn strip_base_prefix<'a>(pattern: &'a Path, base: &Path) -> Option<&'a Path> {
    pattern.strip_prefix(base).ok().or_else(|| {
        let canonical = canonicalize_for_matching(base)?;
        pattern.strip_prefix(canonical).ok()
    })
}

/// Expands directory-style patterns to also match files within them.
/// Pattern "dir/path" becomes ["dir/path", "dir/path/**"] to match both
/// the directory itself and all contents recursively. A leading `~` is
/// expanded first (see [`expand_home_prefix`]).
///
/// The expansion is driven by the pattern's *final* component: it names a
/// directory only when it holds no wildcard. `docs/*` therefore stays as
/// written (it names direct children, and `docs/*/**` would newly exclude
/// nested contents), while `**/.cursor/plans` gains its contents-expansion
/// despite the wildcard earlier in the pattern.
pub fn expand_directory_pattern(pattern: &str) -> Vec<String> {
    let pattern = expand_home_prefix(pattern);
    let base = pattern.trim_end_matches('/');
    let final_component = base.rsplit('/').next().unwrap_or(base);

    if final_component.is_empty() || final_component.contains(['*', '?', '[']) {
        return vec![pattern.to_string()];
    }

    vec![
        base.to_string(),     // Match the directory itself
        format!("{base}/**"), // Match everything underneath
    ]
}

/// The `ignore` override rule that excludes `pattern`.
///
/// The crate spells exclusion with a leading `!`; a pattern already carrying one
/// passes through.
pub fn exclude_override_rule(pattern: &str) -> String {
    if pattern.starts_with('!') {
        pattern.to_string()
    } else {
        format!("!{pattern}")
    }
}

/// Whether every glob an `exclude` pattern turns into compiles.
///
/// An exclude pattern reaches two consumers: [`ExcludeMatchers`] compiles each
/// expansion with `globset`, and the walker adds each as an `ignore` override.
/// Both are mirrored here so a caller holding only the pattern can tell whether
/// either would reject it, which is also when either would print it.
pub fn exclude_pattern_compiles(pattern: &str) -> bool {
    expand_directory_pattern(pattern).iter().all(|expanded| {
        Glob::new(expanded).is_ok()
            && ignore::overrides::OverrideBuilder::new(Path::new("."))
                .add(&exclude_override_rule(expanded))
                .is_ok()
    })
}

/// Whether an `include` pattern compiles as a walker override.
///
/// Answers for the pattern as given, which is only the form the walker uses once
/// [`normalize_pattern_for_base`] has run: stripping a base prefix removes
/// whatever the base's own name held, and an absolute pattern under a directory
/// called `notes [2019-2021]` carries a character class over a descending range
/// until the prefix comes off. Ask this about the pattern the walker is about to
/// add, never about the one a config file spelled.
pub fn include_pattern_compiles(pattern: &str) -> bool {
    ignore::overrides::OverrideBuilder::new(Path::new("."))
        .add(&expand_home_prefix(pattern))
        .is_ok()
}

/// Compiled `exclude` patterns with directory-pattern expansion applied.
///
/// Match paths through [`matched_pattern`](Self::matched_pattern) using a
/// root-relative path (the CLI relativizes against the project root, the
/// LSP against the containing workspace root) so patterns like
/// `docs/drafts` behave identically everywhere.
pub struct ExcludeMatchers {
    matchers: Vec<(String, GlobMatcher)>,
    /// Whether any pattern is absolute, i.e. whether matching has to consider
    /// a file's absolute path at all. Keeps the common (all-relative) case
    /// from paying for the canonicalization that check needs.
    has_absolute: bool,
    /// Spellings of a file the absolute patterns reach through a symlink.
    aliases: PathAliases,
    /// Patterns that failed to compile, with their errors. Callers decide
    /// how to surface these (CLI prints to stderr, LSP logs).
    pub invalid: Vec<(String, String)>,
}

/// Whether `pattern` names an absolute location. A leading `/` counts on every
/// platform: patterns use `/` separators, so a Unix-style path stays absolute
/// when the same config is read on Windows.
pub fn is_absolute_pattern(pattern: &str) -> bool {
    pattern.starts_with('/') || Path::new(pattern).is_absolute()
}

/// Whether `pattern` names an absolute location in any of its spellings.
///
/// A brace alternation can put the absolute part past the start of the pattern
/// (`{/opt,/srv}/docs/**`), where [`is_absolute_pattern`] cannot see it. Callers
/// deciding whether to match a file's absolute path at all must ask this, or
/// such a pattern is never given an absolute path to match.
pub fn has_absolute_spelling(pattern: &str) -> bool {
    if is_absolute_pattern(pattern) {
        return true;
    }
    pattern.contains('{')
        && expand_braces(pattern)
            .iter()
            .any(|spelling| is_absolute_pattern(spelling))
}

/// How many literal spellings one pattern's brace alternations may produce.
///
/// Expansion only *discovers* directory prefixes to canonicalize (see
/// [`PathAliases`]); it never decides whether a pattern matches. Past this
/// point a pattern like `{a,b}{c,d}{e,f}…` is multiplying out work that buys
/// nothing, so the pattern is left unexpanded.
const MAX_BRACE_EXPANSIONS: usize = 64;

/// Every literal spelling of `pattern`'s brace alternations:
/// `/{var/folders,tmp}/**` yields `/var/folders/**` and `/tmp/**`.
///
/// Returns just `pattern` when it holds no alternation, when its braces are
/// unbalanced, or when expanding would exceed [`MAX_BRACE_EXPANSIONS`].
/// Character classes are opaque, so a comma inside `[...]` stays literal.
fn expand_braces(pattern: &str) -> Vec<String> {
    let mut pending = vec![pattern.to_string()];
    let mut expanded: Vec<String> = Vec::new();
    while let Some(current) = pending.pop() {
        let Some((prefix, alternatives, suffix)) = split_first_alternation(&current) else {
            expanded.push(current);
            continue;
        };
        if pending.len() + expanded.len() + alternatives.len() > MAX_BRACE_EXPANSIONS {
            return vec![pattern.to_string()];
        }
        for alternative in alternatives {
            pending.push(format!("{prefix}{alternative}{suffix}"));
        }
    }
    expanded
}

/// Split `pattern` at its first top-level brace alternation into the text
/// before it, its alternatives, and the text after it. `None` when there is no
/// alternation to split on, including an unclosed `{`.
///
/// Empty alternatives are dropped, mirroring globset: it compiles `x{,y}` to
/// `^x(?:y)$`, so `x` is not one of that pattern's spellings.
fn split_first_alternation(pattern: &str) -> Option<(&str, Vec<&str>, &str)> {
    let bytes = pattern.as_bytes();
    let mut open = None;
    let mut depth = 0usize;
    let mut in_class = false;
    let mut alternatives = Vec::new();
    let mut alternative_start = 0;
    let mut index = 0;
    while index < bytes.len() {
        match bytes[index] {
            b'\\' if !cfg!(windows) => index += 1,
            b'[' if !in_class => in_class = true,
            b']' if in_class => in_class = false,
            _ if in_class => {}
            b'{' => {
                depth += 1;
                if depth == 1 {
                    open = Some(index);
                    alternative_start = index + 1;
                }
            }
            b',' if depth == 1 => {
                alternatives.push(&pattern[alternative_start..index]);
                alternative_start = index + 1;
            }
            b'}' if depth > 0 => {
                depth -= 1;
                if depth == 0 {
                    alternatives.push(&pattern[alternative_start..index]);
                    alternatives.retain(|alternative| !alternative.is_empty());
                    if alternatives.is_empty() {
                        return None;
                    }
                    return Some((&pattern[..open?], alternatives, &pattern[index + 1..]));
                }
            }
            _ => {}
        }
        index += 1;
    }
    None
}

/// The leading run of `pattern`'s path components that hold no glob
/// metacharacter: `/var/folders/**` yields `/var/folders`, `/var/log/app*.md`
/// yields `/var/log`, and a fully literal pattern yields itself.
///
/// `None` when the run is empty or names only the filesystem root, neither of
/// which can resolve to a different location. The result is always a prefix
/// slice of `pattern`, so the remainder can be re-attached by byte offset.
///
/// An escaped metacharacter (`\*` on Unix) simply ends the run early. That
/// yields a shorter prefix, never a wrong one.
fn literal_path_prefix(pattern: &str) -> Option<&str> {
    let mut end = 0;
    let mut saw_component = false;
    for component in pattern.split('/') {
        if component.contains(GLOB_METACHARS) {
            break;
        }
        saw_component |= !component.is_empty();
        // Skip past this component and the separator that follows it.
        end += component.len() + 1;
    }
    if !saw_component {
        return None;
    }
    // The loop counted a separator after the final component; the pattern only
    // has one when the run did not reach its end. A trailing separator is
    // dropped so the remainder re-attaches with exactly one.
    let prefix = &pattern[..(end - 1).min(pattern.len())];
    Some(prefix.strip_suffix('/').unwrap_or(prefix))
}

/// `pattern` with its leading literal components resolved through symlinks, or
/// `None` when there is nothing to resolve, the prefix does not exist, or
/// resolving changes nothing.
fn canonicalize_pattern_prefix(pattern: &str) -> Option<String> {
    let prefix = literal_path_prefix(pattern)?;
    let canonical = canonicalize_for_matching(Path::new(prefix))?;
    let canonical = normalize_pattern_separators(canonical.to_string_lossy()).into_owned();
    if canonical == prefix {
        return None;
    }
    Some(format!("{canonical}{}", &pattern[prefix.len()..]))
}

/// Alternative spellings of a path, implied by the absolute patterns in a
/// configuration.
///
/// A pattern names a location the way the user wrote it (`/var/folders/**` on
/// macOS); the file it is matched against arrives canonicalized
/// (`/private/var/folders/…`), so the two never meet. Each pair recorded here
/// is one symlinked prefix some pattern reached a location through: the
/// canonical form of that pattern's leading literal components, and the
/// spelling the pattern used for them.
///
/// Rewriting the *path* rather than the pattern leaves globset the only
/// authority on what a pattern means, and cannot invent a match:
/// `canonicalize(as_written) == canonical` together with `path == canonical +
/// rest` say that `as_written + rest` names that same file. Brace alternations
/// are expanded only to find more prefixes to canonicalize, so an expansion
/// that disagrees with globset can cost a spelling, never fabricate one.
#[derive(Debug, Default)]
pub struct PathAliases {
    /// `(canonical prefix, the spelling a pattern used for it)`.
    prefixes: Vec<(PathBuf, String)>,
}

impl PathAliases {
    /// Collect the symlinked prefixes `patterns` reach locations through.
    ///
    /// Each pattern is canonicalized once here, at cache-build time, so
    /// per-file matching pays no syscall.
    pub fn new<'a>(patterns: impl IntoIterator<Item = &'a str>) -> Self {
        let mut prefixes: Vec<(PathBuf, String)> = Vec::new();
        for pattern in patterns {
            let pattern = expand_home_prefix(pattern);
            if !has_absolute_spelling(&pattern) {
                continue;
            }
            for spelling in expand_braces(&pattern) {
                let Some(as_written) = literal_path_prefix(&spelling) else {
                    continue;
                };
                if !is_absolute_pattern(as_written) {
                    continue;
                }
                let Some(canonical) = canonicalize_for_matching(Path::new(as_written)) else {
                    continue;
                };
                if canonical == Path::new(as_written) {
                    continue;
                }
                let as_written = normalize_pattern_separators(Cow::Borrowed(as_written)).into_owned();
                if !prefixes.iter().any(|(c, w)| c == &canonical && w == &as_written) {
                    prefixes.push((canonical, as_written));
                }
            }
        }
        Self { prefixes }
    }

    pub fn is_empty(&self) -> bool {
        self.prefixes.is_empty()
    }

    /// The spellings of `path` reachable through a recorded prefix, as glob
    /// match candidates. Empty when no pattern reached `path`'s location
    /// through a symlink, which is every configuration that has none.
    pub fn spellings_of(&self, path: &Path) -> Vec<String> {
        self.prefixes
            .iter()
            .filter_map(|(canonical, as_written)| {
                let rest = path.strip_prefix(canonical).ok()?;
                if rest.as_os_str().is_empty() {
                    return Some(as_written.clone());
                }
                let rest = normalize_pattern_separators(rest.to_string_lossy());
                Some(format!("{as_written}/{rest}"))
            })
            .collect()
    }
}

impl ExcludeMatchers {
    pub fn new(patterns: &[String]) -> Self {
        let mut matchers = Vec::new();
        let mut invalid = Vec::new();
        let mut has_absolute = false;
        for pattern in patterns.iter().flat_map(|p| expand_directory_pattern(p)) {
            has_absolute |= has_absolute_spelling(&pattern);
            match Glob::new(&pattern) {
                Ok(glob) => matchers.push((pattern, glob.compile_matcher())),
                Err(e) => invalid.push((pattern, e.to_string())),
            }
        }
        let aliases = PathAliases::new(matchers.iter().map(|(pattern, _)| pattern.as_str()));
        Self {
            matchers,
            has_absolute,
            aliases,
            invalid,
        }
    }

    pub fn is_empty(&self) -> bool {
        self.matchers.is_empty()
    }

    /// The first pattern matching `relative_path`, if any.
    pub fn matched_pattern(&self, relative_path: &str) -> Option<&str> {
        self.matchers
            .iter()
            .find(|(_, matcher)| matcher.is_match(relative_path))
            .map(|(pattern, _)| pattern.as_str())
    }

    pub fn is_match(&self, relative_path: &str) -> bool {
        self.matched_pattern(relative_path).is_some()
    }

    /// The first pattern matching a file, if any.
    ///
    /// Both forms of the file are tried: its `relative` form (how patterns are
    /// normally written - relative to the project or workspace root) and its
    /// absolute path, which is what an absolute pattern matches. Absolute
    /// patterns reach config either written literally or through `~` expansion,
    /// and the walker's overrides cannot apply them (the `ignore` crate anchors
    /// a leading `/` to the walk root), so this is where they take effect.
    ///
    /// Checking the absolute path cannot widen a relative pattern: globs are
    /// anchored at the start of the matched string, so `drafts/**` never
    /// matches `/home/dev/proj/drafts/note.md`.
    ///
    /// `absolute` is canonicalized before matching, since an expanded `~`
    /// resolves to a canonical location. Files that cannot be canonicalized
    /// (already deleted, unreadable) are matched as given.
    ///
    /// A pattern that named its location through a symlink (`/var/folders/**`
    /// for a macOS temp directory) never matches that canonical form, so the
    /// file's other spellings are tried too (see [`PathAliases`]).
    pub fn matched_pattern_for_file(&self, relative: Option<&str>, absolute: &Path) -> Option<&str> {
        if let Some(pattern) = relative.and_then(|rel| self.matched_pattern(rel)) {
            return Some(pattern);
        }
        if !self.has_absolute {
            return None;
        }
        let canonical = canonicalize_for_matching(absolute);
        let absolute = canonical.as_deref().unwrap_or(absolute);
        if let Some(pattern) = self.matched_pattern(&normalize_pattern_separators(absolute.to_string_lossy())) {
            return Some(pattern);
        }
        self.aliases
            .spellings_of(absolute)
            .into_iter()
            .find_map(|alias| self.matched_pattern(&alias))
    }

    /// Whether any pattern matches the file (see [`matched_pattern_for_file`](Self::matched_pattern_for_file)).
    pub fn excludes_file(&self, relative: Option<&str>, absolute: &Path) -> bool {
        self.matched_pattern_for_file(relative, absolute).is_some()
    }
}

/// Relativize `path` against `base` for exclude-pattern matching,
/// canonicalizing both sides so symlinks (e.g. macOS `/tmp`) and Windows
/// path-representation differences don't defeat the prefix strip. Returns
/// `None` when `path` is not under `base`.
///
/// Separators are normalized to `/` on Windows, following the project
/// convention for path strings; globset matches either form, but log
/// output and assertions see one canonical shape.
pub fn path_relative_to(path: &Path, base: &Path) -> Option<String> {
    let canonical_base = base.canonicalize().ok()?;
    let canonical_path = path.canonicalize().ok()?;
    canonical_path.strip_prefix(&canonical_base).ok().map(|rel| {
        let rel = rel.to_string_lossy();
        if cfg!(windows) {
            rel.replace('\\', "/")
        } else {
            rel.to_string()
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn markdown_extensions_match_case_insensitively() {
        for ext in ["md", "MD", "Rmd", "rmd", "MarkDown", "qmd", "mdx"] {
            assert!(is_markdown_extension(OsStr::new(ext)), "{ext} should match");
        }
        for ext in ["rs", "txt", "mdq", ""] {
            assert!(!is_markdown_extension(OsStr::new(ext)), "{ext} should not match");
        }
        assert!(has_markdown_extension(Path::new("a/b/README.md")));
        assert!(has_markdown_extension(Path::new("notebook.Rmd")));
        assert!(!has_markdown_extension(Path::new("no_extension")));
        assert!(!has_markdown_extension(Path::new("lib.rs")));
    }

    #[test]
    fn lintable_selector_makes_adapter_capabilities_explicit() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        fs::create_dir_all(root.join("docs")).unwrap();
        fs::create_dir_all(root.join("templates")).unwrap();
        fs::create_dir_all(root.join("src")).unwrap();
        for relative in [
            "docs/guide.md",
            "docs/notes.txt",
            "templates/page.md.jinja",
            "src/lib.rs",
            "src/upper.RS",
        ] {
            fs::write(root.join(relative), "content\n").unwrap();
        }
        let includes = vec![
            "docs/**".to_string(),
            "templates/**/*.md.jinja".to_string(),
            "src/**/*.rs".to_string(),
        ];

        let markdown = LintablePathSelector::new(Some(root), &includes, LintableFileMode::Markdown);
        assert!(markdown.keeps(&root.join("docs/guide.md")));
        assert!(markdown.keeps(&root.join("templates/page.md.jinja")));
        assert!(!markdown.keeps(&root.join("docs/notes.txt")));
        assert!(
            !markdown.keeps(&root.join("src/lib.rs")),
            "an LSP must not parse a complete Rust source file as Markdown"
        );

        let rustdoc = LintablePathSelector::new(Some(root), &includes, LintableFileMode::MarkdownAndRust);
        assert!(rustdoc.keeps(&root.join("src/lib.rs")));
        assert!(!rustdoc.keeps(&root.join("src/upper.RS")));
        assert!(!rustdoc.keeps(&root.join("docs/notes.txt")));

        let unrestricted = LintablePathSelector::new(Some(root), &includes, LintableFileMode::Any);
        assert!(unrestricted.keeps(&root.join("docs/notes.txt")));
    }

    #[test]
    fn workspace_scan_rejects_explicit_rust_includes() {
        let dir = tempdir().unwrap();
        let root = dir.path().to_path_buf();
        fs::create_dir(root.join("src")).unwrap();
        fs::write(root.join("src/lib.rs"), "/// # Not a document\n").unwrap();
        fs::write(root.join("README.md"), "# Readme\n").unwrap();

        let options = MarkdownWalkOptions {
            respect_gitignore: false,
            skip_vendor_dirs: true,
        };
        let includes = vec!["src/**/*.rs".to_string()];
        let excludes = ExcludeMatchers::new(&[]);
        let scan = MarkdownWorkspaceScan::new(&options, &includes, &excludes);

        assert!(scan.collect(std::slice::from_ref(&root)).is_empty());
        assert!(scan.path_is_ignored(std::slice::from_ref(&root), &root.join("src/lib.rs")));
    }

    #[test]
    fn workspace_scan_applies_includes_to_standard_and_explicit_files() {
        let dir = tempdir().unwrap();
        let root = dir.path().to_path_buf();
        fs::create_dir(root.join("docs")).unwrap();
        fs::create_dir(root.join("templates")).unwrap();
        fs::write(root.join("README.md"), "# Root\n").unwrap();
        fs::write(root.join("docs/guide.md"), "# Guide\n").unwrap();
        fs::write(root.join("templates/page.md.jinja"), "# Template\n").unwrap();
        fs::write(root.join("templates/page.txt"), "not markdown\n").unwrap();

        let options = MarkdownWalkOptions {
            respect_gitignore: false,
            skip_vendor_dirs: true,
        };
        let includes = vec!["docs/**".to_string(), "templates/**/*.md.jinja".to_string()];
        let excludes = ExcludeMatchers::new(&[]);
        let scan = MarkdownWorkspaceScan::new(&options, &includes, &excludes);

        // The test creates these names itself, so normalizing separators
        // unconditionally is safe and keeps one expected value for every platform.
        let names: Vec<String> = scan
            .collect(std::slice::from_ref(&root))
            .iter()
            .map(|path| path.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/"))
            .collect();
        assert_eq!(names, vec!["docs/guide.md", "templates/page.md.jinja"]);

        assert!(!scan.path_is_ignored(std::slice::from_ref(&root), &root.join("templates/page.md.jinja")));
        assert!(scan.path_is_ignored(std::slice::from_ref(&root), &root.join("README.md")));
        assert!(scan.path_is_ignored(std::slice::from_ref(&root), &root.join("templates/page.txt")));
    }

    #[test]
    fn workspace_scan_does_not_prune_a_vendor_named_root() {
        let dir = tempdir().unwrap();
        let root = dir.path().join("target");
        fs::create_dir(&root).unwrap();
        fs::write(root.join("README.md"), "# Root\n").unwrap();
        fs::create_dir(root.join("target")).unwrap();
        fs::write(root.join("target/generated.md"), "# Generated\n").unwrap();

        let options = MarkdownWalkOptions {
            respect_gitignore: false,
            skip_vendor_dirs: true,
        };
        let excludes = ExcludeMatchers::new(&[]);
        let scan = MarkdownWorkspaceScan::new(&options, &[], &excludes);

        assert_eq!(scan.collect(std::slice::from_ref(&root)), vec![root.join("README.md")]);
        assert!(!scan.path_is_ignored(std::slice::from_ref(&root), &root.join("README.md")));
        assert!(scan.path_is_ignored(std::slice::from_ref(&root), &root.join("target/generated.md")));
    }

    #[test]
    fn the_type_glob_selects_exactly_what_counts_as_markdown() {
        assert_eq!(any_case_extension_glob("md"), "*.[mM][dD]");

        // The glob stands in for `is_markdown_extension` inside a walk, so the
        // two have to agree on every spelling, not just the lowercase one.
        let mut builder = globset::GlobSetBuilder::new();
        for ext in MARKDOWN_EXTENSIONS {
            builder.add(
                globset::GlobBuilder::new(&any_case_extension_glob(ext))
                    .literal_separator(true)
                    .build()
                    .unwrap(),
            );
        }
        let globs = builder.build().unwrap();

        for ext in MARKDOWN_EXTENSIONS {
            for spelling in [ext.to_ascii_lowercase(), ext.to_ascii_uppercase(), capitalize(ext)] {
                let name = format!("README.{spelling}");
                assert!(
                    globs.is_match(&name),
                    "{name} is markdown by extension but no type glob selects it"
                );
                assert!(is_markdown_extension(OsStr::new(&spelling)), "{spelling} should match");
            }
        }

        // Control: the glob widens case, not the extension set.
        for name in ["lib.rs", "notes.txt", "README.mdq", "README.m"] {
            assert!(!globs.is_match(name), "{name} should not be selected");
        }
    }

    fn capitalize(ext: &str) -> String {
        let mut chars = ext.chars();
        match chars.next() {
            Some(first) => first.to_ascii_uppercase().to_string() + chars.as_str(),
            None => String::new(),
        }
    }

    #[test]
    fn walk_includes_hidden_files() {
        let temp = tempdir().unwrap();
        fs::create_dir_all(temp.path().join(".github")).unwrap();
        fs::write(temp.path().join(".github/PULL_REQUEST_TEMPLATE.md"), "# hi").unwrap();
        fs::write(temp.path().join("README.md"), "# hi").unwrap();

        let files: Vec<_> = markdown_walk_builder(temp.path(), &MarkdownWalkOptions::default())
            .build()
            .flatten()
            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
            .map(|e| e.path().to_path_buf())
            .collect();
        assert!(files.iter().any(|p| p.ends_with(".github/PULL_REQUEST_TEMPLATE.md")));
        assert!(files.iter().any(|p| p.ends_with("README.md")));
    }

    #[test]
    fn walk_honors_gitignore_when_enabled_only() {
        let temp = tempdir().unwrap();
        fs::write(temp.path().join(".gitignore"), "ignored.md\n").unwrap();
        fs::write(temp.path().join("ignored.md"), "# hi").unwrap();
        fs::write(temp.path().join("kept.md"), "# hi").unwrap();

        let walk = |respect: bool| -> Vec<std::path::PathBuf> {
            markdown_walk_builder(
                temp.path(),
                &MarkdownWalkOptions {
                    respect_gitignore: respect,
                    ..Default::default()
                },
            )
            .build()
            .flatten()
            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
            .map(|e| e.path().to_path_buf())
            .collect()
        };

        let respected = walk(true);
        assert!(!respected.iter().any(|p| p.ends_with("ignored.md")));
        assert!(respected.iter().any(|p| p.ends_with("kept.md")));

        let unrespected = walk(false);
        assert!(unrespected.iter().any(|p| p.ends_with("ignored.md")));
    }

    #[test]
    fn a_gitignore_above_the_repository_root_stays_outside_it() {
        let temp = tempdir().unwrap();
        fs::write(temp.path().join(".gitignore"), "*.md\n").unwrap();
        let repo = temp.path().join("repo");
        fs::create_dir_all(repo.join(".git")).unwrap();
        fs::write(repo.join("kept.md"), "# hi").unwrap();

        let walk = |root: &Path| -> Vec<std::path::PathBuf> {
            markdown_walk_builder(root, &MarkdownWalkOptions::default())
                .build()
                .flatten()
                .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
                .map(|e| e.path().to_path_buf())
                .collect()
        };

        assert!(
            walk(&repo).iter().any(|p| p.ends_with("kept.md")),
            "git reads no gitignore above the repository root, so neither does the walk"
        );

        // Control: outside a repository there is no root to stop at, and the
        // ignore files above are all the walk has to go on.
        fs::remove_dir(repo.join(".git")).unwrap();
        assert!(
            !walk(&repo).iter().any(|p| p.ends_with("kept.md")),
            "with no repository to bound it, the walk keeps reading upward"
        );
    }

    #[test]
    fn the_repository_boundary_needs_every_root_to_have_one() {
        let temp = tempdir().unwrap();
        let inside = temp.path().join("repo/docs");
        fs::create_dir_all(&inside).unwrap();
        fs::create_dir_all(temp.path().join("repo/.git")).unwrap();
        let outside = temp.path().join("plain");
        fs::create_dir_all(&outside).unwrap();

        assert!(stops_at_repository_root(&[&inside]), "a root under a repository root");
        assert!(!stops_at_repository_root(&[&outside]), "a root under no repository");

        // A walk has one setting for all of its roots. Bounding this one would
        // strip the outside root of gitignore handling altogether, which is a
        // worse answer than reading one file too many.
        assert!(!stops_at_repository_root(&[inside.as_path(), outside.as_path()]));
        assert!(!stops_at_repository_root(&[] as &[&Path]), "no root is no repository");

        // A worktree and a submodule mark their root with a `.git` file rather
        // than a directory, and both are still repository roots.
        let worktree = temp.path().join("worktree");
        fs::create_dir_all(&worktree).unwrap();
        fs::write(worktree.join(".git"), "gitdir: /elsewhere/.git/worktrees/x\n").unwrap();
        assert!(stops_at_repository_root(&[&worktree]));
    }

    #[test]
    fn walk_honors_markdownlintignore() {
        let temp = tempdir().unwrap();
        fs::write(temp.path().join(".markdownlintignore"), "legacy.md\n").unwrap();
        fs::write(temp.path().join("legacy.md"), "# hi").unwrap();
        fs::write(temp.path().join("kept.md"), "# hi").unwrap();

        let files: Vec<_> = markdown_walk_builder(temp.path(), &MarkdownWalkOptions::default())
            .build()
            .flatten()
            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
            .map(|e| e.path().to_path_buf())
            .collect();
        assert!(!files.iter().any(|p| p.ends_with("legacy.md")));
        assert!(files.iter().any(|p| p.ends_with("kept.md")));
    }

    #[test]
    fn vendor_dirs_skipped_only_when_requested() {
        let temp = tempdir().unwrap();
        for dir in ["node_modules", "target", "src"] {
            fs::create_dir_all(temp.path().join(dir)).unwrap();
            fs::write(temp.path().join(dir).join("doc.md"), "# hi").unwrap();
        }

        let walk = |skip: bool| -> Vec<std::path::PathBuf> {
            markdown_walk_builder(
                temp.path(),
                &MarkdownWalkOptions {
                    skip_vendor_dirs: skip,
                    // Disable gitignore handling so ambient .gitignore files in the
                    // temp directory's ancestry cannot mask the vendor-dir filtering
                    // this test exercises.
                    respect_gitignore: false,
                },
            )
            .build()
            .flatten()
            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
            .map(|e| e.path().to_path_buf())
            .collect()
        };

        let skipped = walk(true);
        assert!(!skipped.iter().any(|p| p.to_string_lossy().contains("node_modules")));
        assert!(!skipped.iter().any(|p| p.to_string_lossy().contains("target")));
        assert!(skipped.iter().any(|p| p.ends_with("src/doc.md")));

        let unskipped = walk(false);
        assert!(unskipped.iter().any(|p| p.to_string_lossy().contains("node_modules")));
    }

    #[test]
    fn explicit_file_name_glob_extracts_literal_extensions() {
        assert_eq!(explicit_file_name_glob("**/*.md.jinja"), Some("*.md.jinja"));
        assert_eq!(explicit_file_name_glob("*.md.jinja"), Some("*.md.jinja"));
        assert_eq!(explicit_file_name_glob("docs/*.txt"), Some("*.txt"));
        assert_eq!(explicit_file_name_glob("templates/NOTES.tmpl"), Some("NOTES.tmpl"));
        assert_eq!(explicit_file_name_glob("*.md"), Some("*.md"));
        assert_eq!(explicit_file_name_glob("a/b/c/*.md.tmpl"), Some("*.md.tmpl"));
    }

    #[test]
    fn explicit_file_name_glob_rejects_unpinned_patterns() {
        for pattern in [
            "docs/",
            "docs/**",
            "docs",
            "*",
            "**",
            "**/*",
            "*.*",
            "*.md*",
            "*.{md,jinja}",
            "*.md?",
            "data.[ch]",
            "!drafts/*.md.jinja",
            "",
            "**/Makefile",
            "*.",
        ] {
            assert_eq!(explicit_file_name_glob(pattern), None, "{pattern:?} should not qualify");
        }
    }

    #[test]
    fn explicit_include_matchers_match_full_relative_paths() {
        let matchers = ExplicitIncludeMatchers::new(&[
            "**/*.md.jinja".to_string(),
            "docs/**".to_string(),
            "templates/NOTES.tmpl".to_string(),
        ]);
        assert!(!matchers.is_empty());
        assert!(matchers.matches_relative_path("test.md.jinja"));
        assert!(matchers.matches_relative_path("a/b/test.md.jinja"));
        assert!(matchers.matches_relative_path("templates/NOTES.tmpl"));
        // The directory pattern must not widen the filter to arbitrary files.
        assert!(!matchers.matches_relative_path("docs/anything.txt"));
        assert!(!matchers.matches_relative_path("test.jinja"));
        // A broad sibling pattern must not inherit the literal pattern's
        // allowance for files that merely share its name.
        assert!(!matchers.matches_relative_path("docs/NOTES.tmpl"));
        assert!(!matchers.matches_relative_path("x/templates/NOTES.tmpl"));

        let globs: Vec<_> = matchers.file_name_globs().collect();
        assert_eq!(globs, vec!["*.md.jinja", "NOTES.tmpl"]);
    }

    #[test]
    fn explicit_include_matchers_follow_gitignore_anchoring() {
        // No slash: matches at any depth.
        let unanchored = ExplicitIncludeMatchers::new(&["*.md.jinja".to_string()]);
        assert!(unanchored.matches_relative_path("test.md.jinja"));
        assert!(unanchored.matches_relative_path("a/b/test.md.jinja"));

        // Slash: anchored to the root, and `*` does not cross separators.
        let anchored = ExplicitIncludeMatchers::new(&["docs/*.txt".to_string()]);
        assert!(anchored.matches_relative_path("docs/a.txt"));
        assert!(!anchored.matches_relative_path("docs/sub/a.txt"));
        assert!(!anchored.matches_relative_path("other/docs/a.txt"));

        // Leading slash: anchored, slash stripped for matching.
        let rooted = ExplicitIncludeMatchers::new(&["/NOTES.tmpl".to_string()]);
        assert!(rooted.matches_relative_path("NOTES.tmpl"));
        assert!(!rooted.matches_relative_path("docs/NOTES.tmpl"));
    }

    #[test]
    fn explicit_include_matchers_empty_for_directory_and_wildcard_patterns() {
        let matchers = ExplicitIncludeMatchers::new(&["docs/".to_string(), "**/*".to_string()]);
        assert!(matchers.is_empty());
        assert!(!matchers.matches_relative_path("x.md.jinja"));
    }

    #[test]
    fn explicit_include_matchers_skip_invalid_globs() {
        // The unclosed bracket pins a literal `.tmpl` suffix but fails glob
        // compilation; it must be skipped without poisoning valid patterns.
        let matchers = ExplicitIncludeMatchers::new(&["bad[.tmpl".to_string(), "**/*.md.jinja".to_string()]);
        assert!(matchers.matches_relative_path("ok.md.jinja"));
        assert_eq!(matchers.file_name_globs().collect::<Vec<_>>(), vec!["*.md.jinja"]);
    }

    #[test]
    fn exclude_matchers_expand_directory_patterns() {
        let matchers = ExcludeMatchers::new(&["drafts".to_string(), "*.tmp.md".to_string()]);
        assert!(matchers.is_match("drafts"));
        assert!(
            matchers.is_match("drafts/inner.md"),
            "directory pattern must match contents"
        );
        assert!(matchers.is_match("note.tmp.md"));
        assert!(!matchers.is_match("docs/guide.md"));
        assert_eq!(matchers.matched_pattern("drafts/inner.md"), Some("drafts/**"));
        assert!(matchers.invalid.is_empty());
    }

    #[test]
    fn expand_home_prefix_expands_only_a_leading_tilde() {
        let home = Path::new("/home/dev");
        assert_eq!(
            expand_home_prefix_impl("~/.cursor/plans", Some(home)),
            "/home/dev/.cursor/plans"
        );
        assert_eq!(expand_home_prefix_impl("~", Some(home)), "/home/dev");
        assert_eq!(expand_home_prefix_impl("~/", Some(home)), "/home/dev");
    }

    #[test]
    fn expand_home_prefix_leaves_interior_tildes_alone() {
        let home = Path::new("/home/dev");
        // `~` is a legal filename character; only a leading `~/` is a home reference.
        for pattern in ["backup.md~", "docs/~drafts/**", "~user/docs", "**/*~", "!~/secret"] {
            assert_eq!(
                expand_home_prefix_impl(pattern, Some(home)),
                pattern,
                "{pattern:?} must be left as written"
            );
        }
    }

    #[test]
    fn expand_home_prefix_without_a_home_leaves_the_pattern_as_written() {
        assert_eq!(expand_home_prefix_impl("~/.cursor/plans", None), "~/.cursor/plans");
    }

    #[test]
    fn normalize_pattern_for_base_rewrites_absolute_patterns_under_the_base() {
        let temp = tempdir().unwrap();
        // Canonicalize the way production does, so the pattern has the shape an
        // expanded `~` produces (on Windows that means no verbatim prefix).
        let base = canonicalize_for_matching(temp.path()).unwrap();
        let pattern = format!("{}/docs/**", base.to_string_lossy().replace('\\', "/"));
        assert_eq!(normalize_pattern_for_base(&pattern, Some(&base)), "docs/**");
    }

    #[test]
    fn normalize_pattern_for_base_strips_through_a_non_canonical_base() {
        // The base as handed to us (a symlinked `/var` on macOS, a Windows 8.3
        // short name) must still strip.
        let temp = tempdir().unwrap();
        let canonical = canonicalize_for_matching(temp.path()).unwrap();
        let pattern = format!("{}/docs/**", canonical.to_string_lossy().replace('\\', "/"));
        assert_eq!(normalize_pattern_for_base(&pattern, Some(temp.path())), "docs/**");
    }

    #[test]
    fn normalize_pattern_for_base_leaves_other_patterns_alone() {
        let temp = tempdir().unwrap();
        let base = canonicalize_for_matching(temp.path()).unwrap();
        // Relative patterns are already base-relative.
        assert_eq!(normalize_pattern_for_base("docs/**", Some(&base)), "docs/**");
        // An absolute pattern outside the base stays absolute: nothing under
        // this walk can match it, which is the correct outcome.
        assert_eq!(
            normalize_pattern_for_base("/somewhere/else/**", Some(&base)),
            "/somewhere/else/**"
        );
        // With no base there is nothing to rewrite against.
        assert_eq!(normalize_pattern_for_base("/abs/docs/**", None), "/abs/docs/**");
    }

    #[test]
    fn strip_verbatim_prefix_unwraps_windows_canonical_paths() {
        // The exact shape `canonicalize` returns on Windows. Left unstripped it
        // normalizes to `//?/C:/...`, which matches nothing.
        assert_eq!(
            strip_verbatim_prefix(r"\\?\C:\Users\dev\AppData\Local\Temp\x"),
            r"C:\Users\dev\AppData\Local\Temp\x"
        );
        assert_eq!(strip_verbatim_prefix(r"\\?\C:\"), r"C:\");
        // UNC shares unwrap to their ordinary `\\server\share` form.
        assert_eq!(
            strip_verbatim_prefix(r"\\?\UNC\server\share\docs"),
            r"\\server\share\docs"
        );
    }

    #[test]
    fn strip_verbatim_prefix_leaves_other_paths_alone() {
        for path in [
            "/home/dev/docs",
            r"C:\Users\dev",
            r"\\server\share",
            // A device namespace has no ordinary equivalent to unwrap to.
            r"\\?\Volume{b75e2c83-0000-0000-0000-602f00000000}\docs",
            r"\\?\",
            "",
        ] {
            assert_eq!(strip_verbatim_prefix(path), path, "{path:?} must be left as written");
        }
    }

    #[test]
    fn expand_directory_pattern_expands_a_literal_final_component() {
        // A glob earlier in the pattern must not block contents-expansion: the
        // final component names a directory, so its contents are excluded too.
        assert_eq!(
            expand_directory_pattern("**/.cursor/plans"),
            vec!["**/.cursor/plans", "**/.cursor/plans/**"]
        );
        assert_eq!(
            expand_directory_pattern("docs/**/drafts"),
            vec!["docs/**/drafts", "docs/**/drafts/**"]
        );
        // Alternation names literal directories, so it keeps its expansion.
        assert_eq!(
            expand_directory_pattern("logs/{a,b}"),
            vec!["logs/{a,b}", "logs/{a,b}/**"]
        );
    }

    #[test]
    fn expand_directory_pattern_leaves_a_wildcard_final_component_alone() {
        // `docs/*` names direct children only; expanding it to `docs/*/**` would
        // newly exclude nested contents.
        for pattern in ["docs/*", "*.tmp.md", "build/**", "data.[ch]", "notes?"] {
            assert_eq!(
                expand_directory_pattern(pattern),
                vec![pattern.to_string()],
                "{pattern:?} must not gain a contents-expansion"
            );
        }
    }

    #[test]
    fn exclude_matchers_match_an_absolute_pattern_against_an_absolute_path() {
        let matchers = ExcludeMatchers::new(&["/home/dev/.cursor/plans".to_string()]);
        let excluded = Path::new("/home/dev/.cursor/plans/plan.md");
        assert!(
            matchers.excludes_file(None, excluded),
            "an absolute pattern must match the absolute path when there is no relative form"
        );
        assert_eq!(
            matchers.matched_pattern_for_file(None, excluded),
            Some("/home/dev/.cursor/plans/**")
        );
        // A file inside a project root still has a relative form; the absolute
        // pattern must match it through the absolute path.
        assert!(matchers.excludes_file(Some(".cursor/plans/plan.md"), excluded));
        assert!(!matchers.excludes_file(Some("docs/guide.md"), Path::new("/home/dev/docs/guide.md")));
    }

    #[test]
    fn exclude_matchers_do_not_let_relative_patterns_match_absolute_paths() {
        // Relative patterns are anchored at the start of the matched string, so
        // adding the absolute-path check must not widen them into `**/drafts`.
        let matchers = ExcludeMatchers::new(&["drafts".to_string()]);
        assert!(!matchers.excludes_file(None, Path::new("/home/dev/proj/drafts/note.md")));
        assert!(matchers.excludes_file(Some("drafts/note.md"), Path::new("/home/dev/proj/drafts/note.md")));
    }

    #[test]
    fn exclude_matchers_report_invalid_patterns() {
        let matchers = ExcludeMatchers::new(&["[".to_string(), "ok.md".to_string()]);
        assert_eq!(matchers.invalid.len(), 1);
        assert_eq!(matchers.invalid[0].0, "[");
        assert!(matchers.is_match("ok.md"));
    }

    #[test]
    fn path_relative_to_strips_through_symlinked_base() {
        let temp = tempdir().unwrap();
        let base = temp.path().join("base");
        fs::create_dir_all(base.join("docs")).unwrap();
        fs::write(base.join("docs/a.md"), "# hi").unwrap();

        assert_eq!(
            path_relative_to(&base.join("docs/a.md"), &base).as_deref(),
            Some("docs/a.md")
        );
        assert_eq!(
            path_relative_to(&base.join("docs/a.md"), &base.join("docs")).as_deref(),
            Some("a.md")
        );
        assert_eq!(path_relative_to(temp.path(), &base), None, "path outside base");
    }

    fn sorted(mut patterns: Vec<String>) -> Vec<String> {
        patterns.sort();
        patterns
    }

    #[test]
    fn expand_braces_yields_every_alternative() {
        assert_eq!(
            sorted(expand_braces("/{var/folders,tmp}/**")),
            vec!["/tmp/**", "/var/folders/**"]
        );
        // Nesting expands too.
        assert_eq!(sorted(expand_braces("a{b,{c,d}}e")), vec!["abe", "ace", "ade"]);
        // An empty alternative is dropped, as globset drops it.
        assert_eq!(sorted(expand_braces("x{,y}")), vec!["xy"]);
        // Several groups multiply out.
        assert_eq!(
            sorted(expand_braces("/{a,b}/{c,d}.md")),
            vec!["/a/c.md", "/a/d.md", "/b/c.md", "/b/d.md"]
        );
    }

    #[test]
    fn expand_braces_leaves_patterns_it_cannot_split() {
        // Nothing to split.
        assert_eq!(expand_braces("/var/folders/**"), vec!["/var/folders/**"]);
        // An unclosed brace is not an alternation.
        assert_eq!(expand_braces("/var/{a,b/**"), vec!["/var/{a,b/**"]);
        // A comma inside a character class is literal.
        assert_eq!(expand_braces("/var/[a,b]/**"), vec!["/var/[a,b]/**"]);
        // An alternation of nothing but empty alternatives is not a split.
        assert_eq!(expand_braces("x{,}"), vec!["x{,}"]);
        // Past the expansion cap the pattern is left alone: 2^7 = 128 > 64.
        let wide = "/{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}/**";
        assert_eq!(expand_braces(wide), vec![wide]);
    }

    #[test]
    fn has_absolute_spelling_sees_past_a_leading_alternation() {
        assert!(has_absolute_spelling("/var/folders/**"));
        assert!(has_absolute_spelling("{/opt,/srv}/docs/**"));
        assert!(has_absolute_spelling("/{var/folders,tmp}/**"));
        assert!(!has_absolute_spelling("docs/**"));
        assert!(!has_absolute_spelling("{docs,notes}/**"));
    }

    #[test]
    fn expand_braces_agrees_with_globset() {
        // The expansion only discovers prefixes to canonicalize, but a
        // disagreement with globset would mean it is describing a different
        // pattern than the one that decides matches.
        let cases = [
            ("/{var/folders,tmp}/**", "/tmp/note.md"),
            ("/{var/folders,tmp}/**", "/var/folders/x/note.md"),
            ("/{var/folders,tmp}/**", "/opt/note.md"),
            ("/{a,b}/{c,d}.md", "/b/d.md"),
            ("/{a,b}/{c,d}.md", "/b/e.md"),
            ("x{,y}", "x"),
            ("x{,y}", "xy"),
            ("/var/[a,b]/**", "/var/a/n.md"),
            ("/var/[a,b]/**", "/var/,/n.md"),
            ("/var/folders/**", "/var/folders/n.md"),
        ];
        for (pattern, path) in cases {
            let direct = Glob::new(pattern).unwrap().compile_matcher().is_match(path);
            let expanded = expand_braces(pattern)
                .iter()
                .any(|p| Glob::new(p).unwrap().compile_matcher().is_match(path));
            assert_eq!(direct, expanded, "pattern {pattern} against {path}");
        }
    }

    #[test]
    fn literal_path_prefix_stops_at_the_first_wildcard() {
        assert_eq!(literal_path_prefix("/var/folders/**"), Some("/var/folders"));
        assert_eq!(literal_path_prefix("/var/log/app*.md"), Some("/var/log"));
        assert_eq!(literal_path_prefix("/var/note.md"), Some("/var/note.md"));
        assert_eq!(literal_path_prefix("/var/"), Some("/var"));
        assert_eq!(literal_path_prefix("docs/**"), Some("docs"));
        // Nothing literal to resolve.
        assert_eq!(literal_path_prefix("/**"), None);
        assert_eq!(literal_path_prefix("/{var,tmp}/**"), None);
        assert_eq!(literal_path_prefix("**/note.md"), None);
        // The result is always a prefix slice, so a remainder re-attaches by
        // byte offset.
        let pattern = "/var/folders/**";
        let prefix = literal_path_prefix(pattern).unwrap();
        assert_eq!(&pattern[prefix.len()..], "/**");
    }

    /// `(real directory, symlink to it)` under a fresh temp dir. The symlink is
    /// how a pattern spells the location; the real directory is where a file
    /// canonicalizes to.
    #[cfg(unix)]
    fn symlinked_dir(temp: &Path) -> (PathBuf, PathBuf) {
        let real = temp.join("real");
        fs::create_dir_all(real.join("notes")).unwrap();
        fs::write(real.join("notes/scratch.md"), "# Note\n").unwrap();
        let link = temp.join("link");
        std::os::unix::fs::symlink(&real, &link).unwrap();
        (canonicalize_for_matching(&real).unwrap(), link)
    }

    #[cfg(unix)]
    #[test]
    fn path_aliases_spell_a_path_the_way_a_pattern_named_it() {
        let temp = tempdir().unwrap();
        let (real, link) = symlinked_dir(temp.path());
        let pattern = format!("{}/notes/**", link.to_string_lossy());

        let aliases = PathAliases::new([pattern.as_str()]);
        assert!(!aliases.is_empty());
        assert_eq!(
            aliases.spellings_of(&real.join("notes/scratch.md")),
            vec![format!("{}/notes/scratch.md", link.to_string_lossy())]
        );
        // The alias is what makes the pattern match the canonical path.
        let matcher = Glob::new(&pattern).unwrap().compile_matcher();
        assert!(!matcher.is_match(real.join("notes/scratch.md")), "negative control");
        assert!(
            aliases
                .spellings_of(&real.join("notes/scratch.md"))
                .iter()
                .any(|alias| matcher.is_match(alias))
        );
        // A path outside the recorded prefix has no alias.
        assert!(aliases.spellings_of(Path::new("/somewhere/else/note.md")).is_empty());
    }

    #[cfg(unix)]
    #[test]
    fn path_aliases_reach_through_a_brace_alternation() {
        // The prefix only exists once the alternation is expanded.
        let temp = tempdir().unwrap();
        let (real, link) = symlinked_dir(temp.path());
        let pattern = format!("{{/nowhere,{}}}/notes/**", link.to_string_lossy());

        let aliases = PathAliases::new([pattern.as_str()]);
        let matcher = Glob::new(&pattern).unwrap().compile_matcher();
        let note = real.join("notes/scratch.md");
        assert!(!matcher.is_match(&note), "negative control");
        assert!(aliases.spellings_of(&note).iter().any(|alias| matcher.is_match(alias)));
    }

    #[test]
    fn path_aliases_are_empty_without_a_symlinked_prefix() {
        let temp = tempdir().unwrap();
        let canonical = canonicalize_for_matching(temp.path()).unwrap();
        let canonical = canonical.to_string_lossy().replace('\\', "/");
        // Relative patterns, absolute patterns that already name their real
        // location, and prefixes that do not exist all record nothing.
        for pattern in ["docs/**", &format!("{canonical}/docs/**"), "/nonexistent/xyz/**"] {
            assert!(
                PathAliases::new([pattern]).is_empty(),
                "pattern {pattern} should record no alias"
            );
        }
    }

    #[cfg(unix)]
    #[test]
    fn exclude_matchers_match_a_file_a_pattern_named_through_a_symlink() {
        let temp = tempdir().unwrap();
        let (real, link) = symlinked_dir(temp.path());
        let note = real.join("notes/scratch.md");

        let matchers = ExcludeMatchers::new(&[format!("{}/notes/**", link.to_string_lossy())]);
        assert!(matchers.excludes_file(None, &note));

        // Negative controls: a sibling the pattern does not name, and a pattern
        // pointing somewhere else entirely.
        fs::write(real.join("other.md"), "# Other\n").unwrap();
        assert!(!matchers.excludes_file(None, &real.join("other.md")));
        let elsewhere = ExcludeMatchers::new(&[format!("{}/elsewhere/**", link.to_string_lossy())]);
        assert!(!elsewhere.excludes_file(None, &note));
    }

    #[cfg(unix)]
    #[test]
    fn normalize_pattern_for_base_strips_a_pattern_written_through_a_symlink() {
        let temp = tempdir().unwrap();
        let (real, link) = symlinked_dir(temp.path());
        let pattern = format!("{}/notes/*.md", link.to_string_lossy());

        assert_eq!(normalize_pattern_for_base(&pattern, Some(&real)), "notes/*.md");
        // A pattern naming a different location through the same symlink is
        // still outside a narrower base, and stays absolute.
        let outside = format!("{}/elsewhere/*.md", link.to_string_lossy());
        assert_eq!(normalize_pattern_for_base(&outside, Some(&real.join("notes"))), outside);
    }
}