agnix-core 0.19.0

Core validation engine for agent configurations
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
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
//! @import and markdown link reference validation
//!
//! This module validates:
//! - CC-MEM-001: @import references point to existing files (Claude Code specific)
//! - CC-MEM-002: Circular @import detection
//! - CC-MEM-003: @import depth exceeded
//! - REF-001: @import file not found (universal)
//! - REF-002: Broken markdown links (universal)
//! - REF-003: Duplicate @import detection
//! - REF-004: Non-markdown @import detection

use crate::{
    config::LintConfig,
    diagnostics::{Diagnostic, Fix},
    fs::FileSystem,
    parsers::markdown::{extract_imports, extract_markdown_links},
    parsers::{Import, ImportCache},
    rules::{Validator, ValidatorMetadata, line_byte_range},
};
use rust_i18n::t;
use std::collections::{HashMap, HashSet};
use std::path::{Component, Path, PathBuf};

const RULE_IDS: &[&str] = &[
    "CC-MEM-001",
    "CC-MEM-002",
    "CC-MEM-003",
    "REF-001",
    "REF-002",
    "REF-003",
    "REF-004",
];

/// Infrastructure rule ID for poisoned-lock recovery diagnostics.
/// Not included in RULE_IDS because it follows the `namespace::type` convention
/// used by pipeline-level diagnostics (like `config::glob`, `file::read`),
/// not the standard `[CATEGORY]-[NUMBER]` validation rule format.
const RULE_CACHE_POISON: &str = "lint::cache-poison";

pub struct ImportsValidator;

const MAX_IMPORT_DEPTH: usize = 5;
type DiagnosticKey = (PathBuf, usize, usize, String, String);

fn push_unique_diagnostic(
    diagnostics: &mut Vec<Diagnostic>,
    seen_diagnostics: &mut HashSet<DiagnosticKey>,
    diagnostic: Diagnostic,
) {
    let key = (
        diagnostic.file.clone(),
        diagnostic.line,
        diagnostic.column,
        diagnostic.rule.clone(),
        diagnostic.message.clone(),
    );
    if seen_diagnostics.insert(key) {
        diagnostics.push(diagnostic);
    }
}

/// Check if a URL is a local file link (not external or anchor-only)
fn is_local_file_link(url: &str) -> bool {
    const EXTERNAL_PREFIXES: &[&str] = &[
        "http://", "https://", "mailto:", "tel:", "data:", "ftp://", "file://", "//",
    ];

    if EXTERNAL_PREFIXES.iter().any(|p| url.starts_with(p)) {
        return false;
    }

    !url.is_empty() && !url.starts_with('#')
}

/// Strip URL fragment (e.g., "file.md#section" -> "file.md")
fn strip_fragment(url: &str) -> &str {
    match url.find('#') {
        Some(idx) => &url[..idx],
        None => url,
    }
}

impl Validator for ImportsValidator {
    fn metadata(&self) -> ValidatorMetadata {
        ValidatorMetadata {
            name: self.name(),
            rule_ids: RULE_IDS,
        }
    }

    fn validate(&self, path: &Path, content: &str, config: &LintConfig) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        // Check both new category flag and legacy flag for backward compatibility
        if !config.rules().imports || !config.rules().import_references {
            return diagnostics;
        }

        // Detect root file type for cycle/depth rules
        let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
        let is_claude_md = matches!(filename, "CLAUDE.md" | "CLAUDE.local.md");

        let fs = config.fs();
        let project_root = resolve_project_root(path, config, fs.as_ref());
        let root_path = normalize_existing_path(path, fs.as_ref());

        // Use shared cache if available (project-level validation),
        // otherwise create a local cache (single-file validation)
        let shared_cache = config.get_import_cache();
        let mut local_cache: HashMap<PathBuf, Vec<Import>> = HashMap::new();
        let mut visited_depth: HashMap<PathBuf, usize> = HashMap::new();
        let mut stack = Vec::new();
        let mut seen_diagnostics: HashSet<DiagnosticKey> = HashSet::new();

        // Insert the root file's imports into the appropriate cache (if not already present)
        let root_imports = extract_imports(content);

        // REF-003: Duplicate @import detection
        if config.is_rule_enabled("REF-003") {
            let mut seen_paths: HashSet<String> = HashSet::new();
            for import in &root_imports {
                // Normalize: strip leading "./" for comparison
                let normalized = import
                    .path
                    .strip_prefix("./")
                    .unwrap_or(&import.path)
                    .to_string();
                if !seen_paths.insert(normalized) {
                    let mut diagnostic = Diagnostic::warning(
                        path.to_path_buf(),
                        import.line,
                        import.column,
                        "REF-003",
                        t!("rules.ref_003.message", path = import.path.as_str()),
                    )
                    .with_suggestion(t!("rules.ref_003.suggestion"));

                    if let Some((start, end)) = line_byte_range(content, import.line) {
                        diagnostic = diagnostic.with_fix(Fix::delete(
                            start,
                            end,
                            format!("Remove duplicate import '{}'", import.path),
                            false,
                        ));
                    }

                    diagnostics.push(diagnostic);
                }
            }
        }

        // REF-004: Non-markdown @import detection
        if config.is_rule_enabled("REF-004") {
            for import in &root_imports {
                let import_path = Path::new(&import.path);
                if let Some(ext) = import_path.extension().and_then(|e| e.to_str()) {
                    if !ext.eq_ignore_ascii_case("md") {
                        diagnostics.push(
                            Diagnostic::warning(
                                path.to_path_buf(),
                                import.line,
                                import.column,
                                "REF-004",
                                t!(
                                    "rules.ref_004.message",
                                    path = import.path.as_str(),
                                    ext = ext
                                ),
                            )
                            .with_suggestion(t!("rules.ref_004.suggestion")),
                        );
                    }
                }
                // Extensionless imports are allowed (might be directories)
            }
        }

        if let Some(cache) = shared_cache {
            // Write to shared cache only if not already present
            let mut guard = match cache.write() {
                Ok(guard) => guard,
                Err(poisoned) => {
                    push_unique_diagnostic(
                        &mut diagnostics,
                        &mut seen_diagnostics,
                        Diagnostic::warning(
                            path.to_path_buf(),
                            1,
                            0,
                            RULE_CACHE_POISON,
                            t!("rules.cache_poison.message"),
                        )
                        .with_suggestion(t!("rules.cache_poison.suggestion")),
                    );
                    poisoned.into_inner()
                }
            };
            guard.entry(root_path.clone()).or_insert(root_imports);
        } else {
            // Write to local cache
            local_cache.entry(root_path.clone()).or_insert(root_imports);
        }

        visit_imports(
            &root_path,
            None,
            shared_cache,
            &mut local_cache,
            &mut visited_depth,
            &mut stack,
            &mut diagnostics,
            &mut seen_diagnostics,
            config,
            is_claude_md,
            &project_root,
            fs.as_ref(),
            path,
        );

        // Validate markdown links (REF-002)
        // Only check agent config files, not generic markdown. Generic markdown
        // files (plans, research notes, etc.) commonly have broken relative links
        // that are project documentation issues, not agent configuration problems.
        let is_agent_config = matches!(
            filename,
            "CLAUDE.md"
                | "CLAUDE.local.md"
                | "AGENTS.md"
                | "AGENTS.local.md"
                | "AGENTS.override.md"
                | "SKILL.md"
                | "GEMINI.md"
                | "GEMINI.local.md"
        ) || filename.ends_with(".instructions.md")
            || filename == "copilot-instructions.md";
        if is_agent_config {
            validate_markdown_links(path, content, config, &mut diagnostics, fs.as_ref());
        }

        diagnostics
    }
}

#[allow(clippy::too_many_arguments)]
fn visit_imports(
    file_path: &PathBuf,
    content_override: Option<&str>,
    shared_cache: Option<&ImportCache>,
    local_cache: &mut HashMap<PathBuf, Vec<Import>>,
    visited_depth: &mut HashMap<PathBuf, usize>,
    stack: &mut Vec<PathBuf>,
    diagnostics: &mut Vec<Diagnostic>,
    seen_diagnostics: &mut HashSet<DiagnosticKey>,
    config: &LintConfig,
    root_is_claude_md: bool,
    project_root: &Path,
    fs: &dyn FileSystem,
    validation_root: &Path,
) {
    let depth = stack.len();
    if let Some(prev_depth) = visited_depth.get(file_path) {
        // Skip only when we have already visited this file at an equal or
        // shallower depth. If we discover a shallower path later, revisit it
        // so traversal can continue with the tighter depth budget.
        if *prev_depth <= depth {
            return;
        }
    }
    visited_depth.insert(file_path.clone(), depth);

    let imports = get_imports_for_file(
        file_path,
        content_override,
        shared_cache,
        local_cache,
        fs,
        diagnostics,
        seen_diagnostics,
        validation_root,
    );
    let Some(imports) = imports else { return };

    let base_dir = file_path.parent().unwrap_or(Path::new("."));
    let normalized_base = normalize_existing_path(base_dir, fs);
    let normalized_root = project_root;

    // Determine file type for current file to route its own diagnostics
    let filename = file_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
    let is_claude_md = matches!(filename, "CLAUDE.md" | "CLAUDE.local.md");

    // Check rules based on CURRENT file type for missing imports
    // Check rules based on ROOT file type for cycles/depth (applies to entire chain)
    let check_not_found = (is_claude_md && config.is_rule_enabled("CC-MEM-001"))
        || (!is_claude_md && config.is_rule_enabled("REF-001"));
    let check_cycle = root_is_claude_md && config.is_rule_enabled("CC-MEM-002");
    let check_depth = root_is_claude_md && config.is_rule_enabled("CC-MEM-003");

    if !(check_not_found || check_cycle || check_depth) {
        return;
    }

    let rule_not_found = if is_claude_md {
        "CC-MEM-001"
    } else {
        "REF-001"
    };
    let rule_cycle = "CC-MEM-002";
    let rule_depth = "CC-MEM-003";

    stack.push(file_path.clone());

    for import in imports {
        let resolved = resolve_import_path(&import.path, base_dir);

        // Validate path to prevent traversal attacks
        // Reject absolute paths and paths that escape the project root
        let raw_path = Path::new(&import.path);
        if raw_path.is_absolute()
            || import.path.starts_with('/')
            || import.path.starts_with('\\')
            || import.path.starts_with('~')
        {
            if check_not_found {
                push_unique_diagnostic(
                    diagnostics,
                    seen_diagnostics,
                    Diagnostic::error(
                        file_path.clone(),
                        import.line,
                        import.column,
                        rule_not_found,
                        t!("rules.cc_mem_001.absolute", path = import.path.as_str()),
                    )
                    .with_suggestion(t!("rules.cc_mem_001.absolute_suggestion")),
                );
            }
            continue;
        }

        let normalized_resolved = normalize_join(&normalized_base, &import.path);
        if !normalized_resolved.starts_with(normalized_root) {
            if check_not_found {
                push_unique_diagnostic(
                    diagnostics,
                    seen_diagnostics,
                    Diagnostic::error(
                        file_path.clone(),
                        import.line,
                        import.column,
                        rule_not_found,
                        t!("rules.cc_mem_001.escapes", path = import.path.as_str()),
                    )
                    .with_suggestion(t!("rules.cc_mem_001.escapes_suggestion")),
                );
            }
            continue;
        }

        let normalized = if fs.exists(&resolved) {
            let canonical_resolved = normalize_existing_path(&resolved, fs);
            if !canonical_resolved.starts_with(normalized_root) {
                if check_not_found {
                    push_unique_diagnostic(
                        diagnostics,
                        seen_diagnostics,
                        Diagnostic::error(
                            file_path.clone(),
                            import.line,
                            import.column,
                            rule_not_found,
                            t!("rules.cc_mem_001.escapes", path = import.path.as_str()),
                        )
                        .with_suggestion(t!("rules.cc_mem_001.escapes_suggestion")),
                    );
                }
                continue;
            }
            canonical_resolved
        } else {
            resolved
        };

        // Try file-relative resolution first, then project-root resolution.
        // Claude Code resolves @imports relative to the project root, not
        // the importing file's directory.
        let normalized = if fs.exists(&normalized) {
            normalized
        } else {
            // Fallback: try resolving relative to project root
            let root_resolved = project_root.join(&import.path);
            if fs.exists(&root_resolved) {
                root_resolved
            } else {
                normalized
            }
        };

        let import_exists = fs.exists(&normalized);

        if !import_exists {
            if check_not_found {
                push_unique_diagnostic(
                    diagnostics,
                    seen_diagnostics,
                    Diagnostic::error(
                        file_path.clone(),
                        import.line,
                        import.column,
                        rule_not_found,
                        t!("rules.cc_mem_001.not_found", path = import.path.as_str()),
                    )
                    .with_suggestion(format!(
                        "Check that the file exists: {}",
                        normalized.display()
                    )),
                );
            }
            continue;
        }

        // Always check for cycles/depth to prevent infinite recursion
        let has_cycle = stack.contains(&normalized);
        let exceeds_depth = depth + 1 > MAX_IMPORT_DEPTH;

        // Emit diagnostics if rules are enabled for this file type
        if check_cycle && has_cycle {
            let cycle = format_cycle(stack, &normalized);
            push_unique_diagnostic(
                diagnostics,
                seen_diagnostics,
                Diagnostic::error(
                    file_path.clone(),
                    import.line,
                    import.column,
                    rule_cycle,
                    t!("rules.cc_mem_002.message", chain = cycle),
                )
                .with_suggestion(t!("rules.cc_mem_002.suggestion")),
            );
            continue;
        }

        if check_depth && exceeds_depth {
            push_unique_diagnostic(
                diagnostics,
                seen_diagnostics,
                Diagnostic::error(
                    file_path.clone(),
                    import.line,
                    import.column,
                    rule_depth,
                    t!(
                        "rules.cc_mem_003.message",
                        depth = depth + 1,
                        max = MAX_IMPORT_DEPTH
                    ),
                )
                .with_suggestion(t!("rules.cc_mem_003.suggestion")),
            );
            continue;
        }

        // Only recurse if no cycle/depth issues
        if !has_cycle && !exceeds_depth {
            visit_imports(
                &normalized,
                None,
                shared_cache,
                local_cache,
                visited_depth,
                stack,
                diagnostics,
                seen_diagnostics,
                config,
                root_is_claude_md,
                project_root,
                fs,
                validation_root,
            );
        }
    }

    stack.pop();
}

/// Get imports for a file, using shared cache if available, otherwise local cache.
///
/// This function uses a read-then-write lock pattern for the shared cache:
/// 1. Try to read from cache (read lock)
/// 2. If miss, drop read lock, parse file, then write (write lock)
///
/// This avoids holding locks during file I/O and parsing.
///
/// Note: There's a small window for duplicate work where two threads could both
/// miss the cache and parse the same file. This is acceptable because:
/// - The extra work is bounded (only one extra parse per file per thread)
/// - Using entry() API prevents duplicate insertions
/// - Lock-free parsing enables better parallelism than holding locks during I/O
#[allow(clippy::too_many_arguments)]
fn get_imports_for_file(
    file_path: &Path,
    content_override: Option<&str>,
    shared_cache: Option<&ImportCache>,
    local_cache: &mut HashMap<PathBuf, Vec<Import>>,
    fs: &dyn FileSystem,
    diagnostics: &mut Vec<Diagnostic>,
    seen_diagnostics: &mut HashSet<DiagnosticKey>,
    validation_root: &Path,
) -> Option<Vec<Import>> {
    // Try shared cache first if available
    if let Some(cache) = shared_cache {
        // Read lock - check if already cached
        {
            let guard = match cache.read() {
                Ok(guard) => guard,
                Err(poisoned) => {
                    push_unique_diagnostic(
                        diagnostics,
                        seen_diagnostics,
                        Diagnostic::warning(
                            validation_root.to_path_buf(),
                            1,
                            0,
                            RULE_CACHE_POISON,
                            t!("rules.cache_poison.message"),
                        )
                        .with_suggestion(t!("rules.cache_poison.suggestion")),
                    );
                    poisoned.into_inner()
                }
            };
            if let Some(imports) = guard.get(file_path) {
                return Some(imports.clone());
            }
        }
        // Cache miss - read lock dropped here before I/O

        // Parse the file outside of any lock
        let content = match content_override {
            Some(content) => content.to_string(),
            // Silently skip files that can't be read (symlinks, too large, missing).
            // This is intentional: import chains often reference optional/external files,
            // and failing noisily on each would overwhelm the user.
            None => fs.read_to_string(file_path).ok()?,
        };
        let imports = extract_imports(&content);

        // Write lock - use entry() to handle race condition where another thread
        // may have already inserted while we were parsing
        let mut guard = match cache.write() {
            Ok(guard) => guard,
            Err(poisoned) => {
                push_unique_diagnostic(
                    diagnostics,
                    seen_diagnostics,
                    Diagnostic::warning(
                        validation_root.to_path_buf(),
                        1,
                        0,
                        RULE_CACHE_POISON,
                        t!("rules.cache_poison.message"),
                    )
                    .with_suggestion(t!("rules.cache_poison.suggestion")),
                );
                poisoned.into_inner()
            }
        };
        guard
            .entry(file_path.to_path_buf())
            .or_insert_with(|| imports.clone());
        return Some(imports);
    }

    // Fallback to local cache (single-file validation)
    if !local_cache.contains_key(file_path) {
        let content = match content_override {
            Some(content) => content.to_string(),
            None => fs.read_to_string(file_path).ok()?,
        };
        let imports = extract_imports(&content);
        local_cache.insert(file_path.to_path_buf(), imports);
    }
    local_cache.get(file_path).cloned()
}

fn resolve_import_path(import_path: &str, base_dir: &Path) -> PathBuf {
    if import_path.starts_with("~/") || import_path.starts_with("~\\") {
        #[cfg(feature = "filesystem")]
        if let Some(home) = dirs::home_dir() {
            return home.join(&import_path[2..]);
        }
    }

    let raw = PathBuf::from(import_path);
    if raw.is_absolute() {
        raw
    } else {
        base_dir.join(raw)
    }
}

fn normalize_join(base_dir: &Path, import_path: &str) -> PathBuf {
    let mut result = PathBuf::from(base_dir);
    for component in Path::new(import_path).components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                result.pop();
            }
            Component::Normal(segment) => {
                result.push(segment);
            }
            Component::RootDir | Component::Prefix(_) => {
                result = PathBuf::from(component.as_os_str());
            }
        }
    }
    result
}

fn normalize_existing_path(path: &Path, fs: &dyn FileSystem) -> PathBuf {
    fs.canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

fn resolve_project_root(path: &Path, config: &LintConfig, fs: &dyn FileSystem) -> PathBuf {
    if let Some(root) = config.get_root_dir() {
        return normalize_existing_path(root, fs);
    }

    find_repo_root(path, fs).unwrap_or_else(|| {
        let fallback = path.parent().unwrap_or(Path::new("."));
        normalize_existing_path(fallback, fs)
    })
}

fn find_repo_root(path: &Path, fs: &dyn FileSystem) -> Option<PathBuf> {
    for ancestor in path.ancestors() {
        if ancestor.as_os_str().is_empty() {
            continue;
        }
        let git_marker = ancestor.join(".git");
        if fs.is_dir(&git_marker) || fs.is_file(&git_marker) {
            return Some(ancestor.to_path_buf());
        }
    }
    None
}

fn format_cycle(stack: &[PathBuf], target: &Path) -> String {
    let mut cycle = Vec::new();
    let mut in_cycle = false;
    for path in stack {
        if path == target {
            in_cycle = true;
        }
        if in_cycle {
            cycle.push(path.display().to_string());
        }
    }
    cycle.push(target.display().to_string());
    cycle.join(" -> ")
}

/// Validate markdown links in content (REF-002)
fn validate_markdown_links(
    path: &Path,
    content: &str,
    config: &LintConfig,
    diagnostics: &mut Vec<Diagnostic>,
    fs: &dyn FileSystem,
) {
    if !config.is_rule_enabled("REF-002") {
        return;
    }

    let links = extract_markdown_links(content);
    let base_dir = path.parent().unwrap_or(Path::new("."));

    // Precompute containment boundary and its canonical form once, outside the loop.
    // Both values depend only on config.root_dir() and base_dir, which are
    // loop-invariant, so this eliminates N-1 redundant canonicalize syscalls.
    let containment_dir = config
        .root_dir()
        .cloned()
        .unwrap_or_else(|| base_dir.to_path_buf());
    let canonical_base = fs.canonicalize(&containment_dir).ok();

    for link in links {
        // Skip non-local links (external URLs, anchors, etc.)
        if !is_local_file_link(&link.url) {
            continue;
        }

        // Skip template placeholders like {url}, {repoUrl}, {brackets}
        if link.url.starts_with('{') && link.url.ends_with('}') {
            continue;
        }

        // Skip single-word "links" that don't look like file paths
        // (no extension, no directory separator) - likely wiki-style links or examples
        if !link.url.contains('/')
            && !link.url.contains('\\')
            && !link.url.contains('.')
            && !link.url.contains('#')
        {
            continue;
        }

        // Strip fragment to get the file path
        let file_path = strip_fragment(&link.url);

        // Resolve the path relative to the file's directory
        let resolved = resolve_import_path(file_path, base_dir);

        // Security: Verify resolved path stays within project root
        if let Some(ref canonical_base) = canonical_base {
            if let Ok(canonical_resolved) = fs.canonicalize(&resolved) {
                if !canonical_resolved.starts_with(canonical_base) {
                    continue;
                }
            }
        }

        // Check if file exists
        if !fs.exists(&resolved) {
            diagnostics.push(
                Diagnostic::error(
                    path.to_path_buf(),
                    link.line,
                    link.column,
                    "REF-002",
                    t!(
                        "rules.ref_002.message",
                        url = link.url.as_str(),
                        resolved = resolved.display().to_string()
                    ),
                )
                .with_suggestion(t!("rules.ref_002.suggestion")),
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::LintConfig;
    use crate::diagnostics::DiagnosticLevel;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_config_disabled_imports_category() {
        let mut config = LintConfig::default();
        config.rules_mut().imports = false;

        let content = "@nonexistent-file.md";
        let validator = ImportsValidator;
        let diagnostics = validator.validate(Path::new("test.md"), content, &config);

        assert!(diagnostics.is_empty());
    }

    #[test]
    fn test_legacy_import_references_flag() {
        let mut config = LintConfig::default();
        config.rules_mut().import_references = false;

        let content = "@nonexistent-file.md";
        let validator = ImportsValidator;
        let diagnostics = validator.validate(Path::new("test.md"), content, &config);

        assert!(diagnostics.is_empty());
    }

    #[test]
    fn test_missing_import_in_claude_md() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("CLAUDE.md");
        fs::write(&file_path, "See @missing.md").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @missing.md", &LintConfig::default());

        assert!(diagnostics.iter().any(|d| d.rule == "CC-MEM-001"));
    }

    #[test]
    fn test_cycle_detection_in_claude_md() {
        let temp = TempDir::new().unwrap();
        let a = temp.path().join("CLAUDE.md");
        let b = temp.path().join("b.md");
        fs::write(&a, "See @b.md").unwrap();
        fs::write(&b, "See @CLAUDE.md").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&a, "See @b.md", &LintConfig::default());

        assert!(diagnostics.iter().any(|d| d.rule == "CC-MEM-002"));
    }

    #[test]
    fn test_depth_exceeded_in_claude_md() {
        let temp = TempDir::new().unwrap();
        let claude_md = temp.path().join("CLAUDE.md");
        let paths: Vec<PathBuf> = (1..7)
            .map(|i| temp.path().join(format!("{}.md", i)))
            .collect();

        fs::write(&claude_md, "See @1.md").unwrap();
        for (i, path) in paths.iter().enumerate().take(5) {
            let content = format!("See @{}.md", i + 2);
            fs::write(path, content).unwrap();
        }
        fs::write(&paths[5], "End").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&claude_md, "See @1.md", &LintConfig::default());

        assert!(diagnostics.iter().any(|d| d.rule == "CC-MEM-003"));
    }

    #[test]
    fn test_missing_import_in_skill_md() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("SKILL.md");
        fs::write(&file_path, "See @missing.md").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @missing.md", &LintConfig::default());

        assert!(diagnostics.iter().any(|d| d.rule == "REF-001"));
        assert!(!diagnostics.iter().any(|d| d.rule == "CC-MEM-001"));
    }

    #[test]
    fn test_missing_import_in_agents_md() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("AGENTS.md");
        fs::write(&file_path, "See @missing.md").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @missing.md", &LintConfig::default());

        assert!(diagnostics.iter().any(|d| d.rule == "REF-001"));
        assert!(!diagnostics.iter().any(|d| d.rule == "CC-MEM-001"));
    }

    #[test]
    fn test_missing_import_in_generic_md() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("README.md");
        fs::write(&file_path, "See @missing.md").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @missing.md", &LintConfig::default());

        assert!(diagnostics.iter().any(|d| d.rule == "REF-001"));
        assert!(!diagnostics.iter().any(|d| d.rule == "CC-MEM-001"));
    }

    #[test]
    fn test_cycle_in_skill_md() {
        let temp = TempDir::new().unwrap();
        let a = temp.path().join("SKILL.md");
        let b = temp.path().join("b.md");
        fs::write(&a, "See @b.md").unwrap();
        fs::write(&b, "See @SKILL.md").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&a, "See @b.md", &LintConfig::default());

        // Non-CLAUDE files don't check cycles, so no diagnostics expected
        assert!(diagnostics.is_empty());
    }

    #[test]
    fn test_depth_exceeded_in_skill_md() {
        let temp = TempDir::new().unwrap();
        let skill_md = temp.path().join("SKILL.md");
        let paths: Vec<PathBuf> = (1..7)
            .map(|i| temp.path().join(format!("{}.md", i)))
            .collect();

        fs::write(&skill_md, "See @1.md").unwrap();
        for (i, path) in paths.iter().enumerate().take(5) {
            let content = format!("See @{}.md", i + 2);
            fs::write(path, content).unwrap();
        }
        fs::write(&paths[5], "End").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&skill_md, "See @1.md", &LintConfig::default());

        // Non-CLAUDE files don't check depth, so no diagnostics expected
        assert!(diagnostics.is_empty());
    }

    #[test]
    fn test_ref_001_disabled_suppresses_skill_md_errors() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("SKILL.md");
        fs::write(&file_path, "See @missing.md").unwrap();

        let mut config = LintConfig::default();
        config
            .rules_mut()
            .disabled_rules
            .push("REF-001".to_string());

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @missing.md", &config);

        assert!(diagnostics.is_empty());
    }

    #[test]
    fn test_cc_mem_disabled_still_allows_ref() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("SKILL.md");
        fs::write(&file_path, "See @missing.md").unwrap();

        let mut config = LintConfig::default();
        config
            .rules_mut()
            .disabled_rules
            .push("CC-MEM-001".to_string());
        config
            .rules_mut()
            .disabled_rules
            .push("CC-MEM-002".to_string());
        config
            .rules_mut()
            .disabled_rules
            .push("CC-MEM-003".to_string());

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @missing.md", &config);

        assert!(diagnostics.iter().any(|d| d.rule == "REF-001"));
    }

    #[test]
    fn test_ref_disabled_still_allows_cc_mem() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("CLAUDE.md");
        fs::write(&file_path, "See @missing.md").unwrap();

        let mut config = LintConfig::default();
        config
            .rules_mut()
            .disabled_rules
            .push("REF-001".to_string());

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @missing.md", &config);

        // CLAUDE.md should still emit CC-MEM-001 even when REF-001 is disabled
        assert!(diagnostics.iter().any(|d| d.rule == "CC-MEM-001"));
    }

    #[test]
    fn test_nested_file_type_detection() {
        // Test for critical fix: file type should be determined per-file in recursion
        let temp = TempDir::new().unwrap();
        let skill_md = temp.path().join("SKILL.md");
        let claude_md = temp.path().join("CLAUDE.md");

        // SKILL.md imports CLAUDE.md which has a missing import
        fs::write(&skill_md, "See @CLAUDE.md").unwrap();
        fs::write(&claude_md, "See @missing.md").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&skill_md, "See @CLAUDE.md", &LintConfig::default());

        // CLAUDE.md's missing import should emit CC-MEM-001, not REF-001
        assert!(
            diagnostics
                .iter()
                .any(|d| d.rule == "CC-MEM-001" && d.file.ends_with("CLAUDE.md"))
        );
        assert!(
            !diagnostics
                .iter()
                .any(|d| d.rule == "REF-001" && d.file.ends_with("CLAUDE.md"))
        );
    }

    #[test]
    fn test_absolute_path_rejection() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("CLAUDE.md");
        fs::write(&file_path, "See @/etc/passwd").unwrap();

        let validator = ImportsValidator;
        let diagnostics =
            validator.validate(&file_path, "See @/etc/passwd", &LintConfig::default());

        // Absolute paths should be rejected
        assert!(
            diagnostics
                .iter()
                .any(|d| d.message.contains("Absolute import paths not allowed"))
        );
    }

    #[test]
    fn test_path_escape_rejection() {
        let temp = TempDir::new().unwrap();
        let root = temp.path().join("root");
        let docs = root.join("docs");
        fs::create_dir_all(&docs).unwrap();
        fs::write(temp.path().join("outside.md"), "Outside content").unwrap();

        let file_path = docs.join("CLAUDE.md");
        fs::write(&file_path, "See @../../outside.md").unwrap();

        let mut config = LintConfig::default();
        config.set_root_dir(root);

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @../../outside.md", &config);

        assert!(
            diagnostics
                .iter()
                .any(|d| { d.rule == "CC-MEM-001" && d.message.contains("escapes project root") })
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_symlink_escape_rejection() {
        use std::os::unix::fs::symlink;

        let temp = TempDir::new().unwrap();
        let root = temp.path().join("root");
        let docs = root.join("docs");
        let outside = temp.path().join("outside");

        fs::create_dir_all(&docs).unwrap();
        fs::create_dir_all(&outside).unwrap();
        fs::write(outside.join("secret.md"), "Secret content").unwrap();

        let link_path = root.join("link");
        symlink(&outside, &link_path).unwrap();

        let file_path = docs.join("CLAUDE.md");
        fs::write(&file_path, "See @../link/secret.md").unwrap();

        let mut config = LintConfig::default();
        config.set_root_dir(root);

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @../link/secret.md", &config);

        assert!(
            diagnostics
                .iter()
                .any(|d| { d.rule == "CC-MEM-001" && d.message.contains("escapes project root") })
        );
    }

    // ===== Helper Function Tests =====

    #[test]
    fn test_is_local_file_link_true() {
        assert!(is_local_file_link("file.md"));
        assert!(is_local_file_link("docs/guide.md"));
        assert!(is_local_file_link("./relative.md"));
        assert!(is_local_file_link("../parent.md"));
        assert!(is_local_file_link("file.md#section"));
    }

    #[test]
    fn test_is_local_file_link_false() {
        assert!(!is_local_file_link("https://example.com"));
        assert!(!is_local_file_link("http://example.com"));
        assert!(!is_local_file_link("mailto:test@example.com"));
        assert!(!is_local_file_link("tel:+1234567890"));
        assert!(!is_local_file_link("data:text/plain,hello"));
        assert!(!is_local_file_link("ftp://files.example.com"));
        assert!(!is_local_file_link("//cdn.example.com/file.js"));
        assert!(!is_local_file_link("#section"));
        assert!(!is_local_file_link(""));
    }

    #[test]
    fn test_strip_fragment() {
        assert_eq!(strip_fragment("file.md#section"), "file.md");
        assert_eq!(strip_fragment("file.md"), "file.md");
        assert_eq!(strip_fragment("#section"), "");
        assert_eq!(strip_fragment("docs/guide.md#heading"), "docs/guide.md");
    }

    // ===== REF-001 Tests =====

    #[test]
    fn test_ref_001_missing_import() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.md");
        fs::write(&file_path, "See @missing.md").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @missing.md", &LintConfig::default());

        // Non-CLAUDE.md files emit REF-001 only (not CC-MEM-001)
        assert!(diagnostics.iter().any(|d| d.rule == "REF-001"));
        assert!(!diagnostics.iter().any(|d| d.rule == "CC-MEM-001"));
    }

    #[test]
    fn test_ref_001_existing_import() {
        let temp = TempDir::new().unwrap();
        let target = temp.path().join("exists.md");
        let file_path = temp.path().join("test.md");
        fs::write(&target, "Target content").unwrap();
        fs::write(&file_path, "See @exists.md").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @exists.md", &LintConfig::default());

        // Should not emit any not-found errors
        assert!(!diagnostics.iter().any(|d| d.rule == "REF-001"));
        assert!(!diagnostics.iter().any(|d| d.rule == "CC-MEM-001"));
    }

    #[test]
    fn test_ref_001_disabled() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.md");
        fs::write(&file_path, "See @missing.md").unwrap();

        let mut config = LintConfig::default();
        config.rules_mut().disabled_rules = vec!["REF-001".to_string()];

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @missing.md", &config);

        // Non-CLAUDE.md with REF-001 disabled emits nothing
        assert!(diagnostics.is_empty());
    }

    // ===== REF-002 Tests =====

    #[test]
    fn test_ref_002_broken_link() {
        let temp = TempDir::new().unwrap();
        // REF-002 only fires on agent config files, not generic markdown
        let file_path = temp.path().join("CLAUDE.md");
        fs::write(&file_path, "See [guide](missing.md) for more.").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(
            &file_path,
            "See [guide](missing.md) for more.",
            &LintConfig::default(),
        );

        assert!(diagnostics.iter().any(|d| d.rule == "REF-002"));
        let ref_002 = diagnostics.iter().find(|d| d.rule == "REF-002").unwrap();
        assert!(ref_002.message.contains("Broken markdown link"));
    }

    #[test]
    fn test_ref_002_valid_link() {
        let temp = TempDir::new().unwrap();
        let target = temp.path().join("exists.md");
        let file_path = temp.path().join("test.md");
        fs::write(&target, "Target content").unwrap();
        fs::write(&file_path, "See [guide](exists.md) for more.").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(
            &file_path,
            "See [guide](exists.md) for more.",
            &LintConfig::default(),
        );

        assert!(!diagnostics.iter().any(|d| d.rule == "REF-002"));
    }

    #[test]
    fn test_ref_002_skips_external_links() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.md");
        let content = "See [GitHub](https://github.com) and [mail](mailto:test@example.com).";
        fs::write(&file_path, content).unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, content, &LintConfig::default());

        // External links should not trigger REF-002
        assert!(!diagnostics.iter().any(|d| d.rule == "REF-002"));
    }

    #[test]
    fn test_ref_002_skips_anchor_links() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.md");
        let content = "See [section](#section-name) for more.";
        fs::write(&file_path, content).unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, content, &LintConfig::default());

        // Pure anchor links should not trigger REF-002
        assert!(!diagnostics.iter().any(|d| d.rule == "REF-002"));
    }

    #[test]
    fn test_ref_002_link_with_fragment() {
        let temp = TempDir::new().unwrap();
        let target = temp.path().join("exists.md");
        let file_path = temp.path().join("test.md");
        fs::write(&target, "# Section\nContent").unwrap();
        fs::write(&file_path, "See [section](exists.md#section) for more.").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(
            &file_path,
            "See [section](exists.md#section) for more.",
            &LintConfig::default(),
        );

        // File exists, fragment validation is not implemented - no error
        assert!(!diagnostics.iter().any(|d| d.rule == "REF-002"));
    }

    #[test]
    fn test_ref_002_missing_file_with_fragment() {
        let temp = TempDir::new().unwrap();
        // REF-002 only fires on agent config files, not generic markdown
        let file_path = temp.path().join("CLAUDE.md");
        fs::write(&file_path, "See [section](missing.md#section) for more.").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(
            &file_path,
            "See [section](missing.md#section) for more.",
            &LintConfig::default(),
        );

        // File doesn't exist, should error
        assert!(diagnostics.iter().any(|d| d.rule == "REF-002"));
    }

    #[test]
    fn test_ref_002_broken_image() {
        let temp = TempDir::new().unwrap();
        // REF-002 only fires on agent config files, not generic markdown
        let file_path = temp.path().join("CLAUDE.md");
        fs::write(&file_path, "![logo](images/logo.png)").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(
            &file_path,
            "![logo](images/logo.png)",
            &LintConfig::default(),
        );

        assert!(diagnostics.iter().any(|d| d.rule == "REF-002"));
        let ref_002 = diagnostics.iter().find(|d| d.rule == "REF-002").unwrap();
        assert!(ref_002.message.contains("Broken markdown link"));
    }

    #[test]
    fn test_ref_002_disabled() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.md");
        fs::write(&file_path, "See [guide](missing.md) for more.").unwrap();

        let mut config = LintConfig::default();
        config.rules_mut().disabled_rules = vec!["REF-002".to_string()];

        let validator = ImportsValidator;
        let diagnostics =
            validator.validate(&file_path, "See [guide](missing.md) for more.", &config);

        assert!(!diagnostics.iter().any(|d| d.rule == "REF-002"));
    }

    #[test]
    fn test_ref_002_imports_category_disabled() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.md");
        fs::write(&file_path, "See [guide](missing.md) for more.").unwrap();

        let mut config = LintConfig::default();
        config.rules_mut().imports = false;

        let validator = ImportsValidator;
        let diagnostics =
            validator.validate(&file_path, "See [guide](missing.md) for more.", &config);

        // When imports category is disabled, no validation happens
        assert!(diagnostics.is_empty());
    }

    #[test]
    fn test_ref_002_relative_path() {
        let temp = TempDir::new().unwrap();
        let subdir = temp.path().join("docs");
        fs::create_dir(&subdir).unwrap();
        let target = subdir.join("guide.md");
        let file_path = temp.path().join("test.md");
        fs::write(&target, "Guide content").unwrap();
        fs::write(&file_path, "See [guide](docs/guide.md) for more.").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(
            &file_path,
            "See [guide](docs/guide.md) for more.",
            &LintConfig::default(),
        );

        // Relative path should resolve correctly
        assert!(!diagnostics.iter().any(|d| d.rule == "REF-002"));
    }

    #[test]
    fn test_ref_002_path_traversal_blocked_by_root_dir() {
        let temp = TempDir::new().unwrap();

        // Create directory structure: temp/sub/CLAUDE.md and temp/outside.md
        let sub = temp.path().join("sub");
        fs::create_dir(&sub).unwrap();
        let outside = temp.path().join("outside.md");
        fs::write(&outside, "Outside content").unwrap();

        let file_path = sub.join("CLAUDE.md");
        let content =
            "See [escape](../outside.md) for more.\nSee [missing](nonexistent.md) for more.";
        fs::write(&file_path, content).unwrap();

        // Set root_dir to sub/ so ../outside.md escapes the boundary
        let mut config = LintConfig::default();
        config.set_root_dir(sub.clone());

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, content, &config);

        // The ../outside.md link should be silently skipped (path traversal blocked)
        // but nonexistent.md should still produce REF-002 (within root, but missing)
        let ref_002_diags: Vec<_> = diagnostics.iter().filter(|d| d.rule == "REF-002").collect();
        assert_eq!(
            ref_002_diags.len(),
            1,
            "Expected exactly 1 REF-002 diagnostic, but found {}: {:?}",
            ref_002_diags.len(),
            ref_002_diags
        );
        assert!(ref_002_diags[0].message.contains("nonexistent.md"));
        assert!(
            !ref_002_diags
                .iter()
                .any(|d| d.message.contains("outside.md")),
            "outside.md should be silently skipped, not reported"
        );
    }

    #[test]
    fn test_ref_002_nonexistent_root_dir_skips_traversal_check() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("CLAUDE.md");
        let content = "See [missing](nonexistent.md) for more.";
        fs::write(&file_path, content).unwrap();

        // Set root_dir to a path that does not exist - canonical_base will be None
        let mut config = LintConfig::default();
        config.set_root_dir(PathBuf::from("/nonexistent/root/path"));

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, content, &config);

        // Traversal check is skipped (canonical_base is None), but existence check still runs
        assert!(
            diagnostics.iter().any(|d| d.rule == "REF-002"),
            "Expected at least one REF-002 diagnostic, but found none in: {:?}",
            diagnostics
        );
    }

    // ===== Shared Import Cache Tests =====

    #[test]
    fn test_single_file_validation_works_without_shared_cache() {
        // Single-file validation should work without a shared cache
        let temp = TempDir::new().unwrap();
        let target = temp.path().join("target.md");
        let file_path = temp.path().join("test.md");
        fs::write(&target, "Target content").unwrap();
        fs::write(&file_path, "See @target.md").unwrap();

        let config = LintConfig::default();
        // No shared cache set - should use local cache
        assert!(config.get_import_cache().is_none());

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @target.md", &config);

        // Should succeed with no errors
        assert!(diagnostics.is_empty());
    }

    #[test]
    fn test_shared_cache_is_populated_after_first_parse() {
        use std::collections::HashMap;
        use std::sync::{Arc, RwLock};

        let temp = TempDir::new().unwrap();
        let target = temp.path().join("target.md");
        let file_path = temp.path().join("test.md");
        fs::write(&target, "Target has @nested.md import").unwrap();
        fs::write(temp.path().join("nested.md"), "Nested content").unwrap();
        fs::write(&file_path, "See @target.md").unwrap();

        // Create shared cache
        let cache: crate::parsers::ImportCache = Arc::new(RwLock::new(HashMap::new()));

        let mut config = LintConfig::default();
        config.set_import_cache(cache.clone());

        // Verify cache is empty before validation
        {
            let guard = cache.read().unwrap();
            assert!(guard.is_empty());
        }

        let validator = ImportsValidator;
        let _ = validator.validate(&file_path, "See @target.md", &config);

        // Verify cache is populated after validation
        {
            let guard = cache.read().unwrap();
            // Should have at least the root file and target file
            assert!(
                guard.len() >= 2,
                "Expected at least 2 entries, got {}",
                guard.len()
            );
        }
    }

    #[test]
    fn test_shared_cache_second_access_uses_cached_result() {
        use std::collections::HashMap;
        use std::sync::{Arc, RwLock};

        let temp = TempDir::new().unwrap();
        let target = temp.path().join("target.md");
        let file_path = temp.path().join("test.md");
        fs::write(&target, "Target content").unwrap();
        fs::write(&file_path, "See @target.md").unwrap();

        // Create shared cache
        let cache: crate::parsers::ImportCache = Arc::new(RwLock::new(HashMap::new()));

        let mut config = LintConfig::default();
        config.set_import_cache(cache.clone());

        let validator = ImportsValidator;

        // First validation - populates cache
        let _ = validator.validate(&file_path, "See @target.md", &config);
        let cache_size_after_first;
        {
            let guard = cache.read().unwrap();
            cache_size_after_first = guard.len();
        }

        // Second validation - should use cached results
        let _ = validator.validate(&file_path, "See @target.md", &config);
        let cache_size_after_second;
        {
            let guard = cache.read().unwrap();
            cache_size_after_second = guard.len();
        }

        // Cache size should be the same (entries reused, not duplicated)
        assert_eq!(cache_size_after_first, cache_size_after_second);
    }

    #[test]
    fn test_shared_cache_concurrent_access() {
        use std::collections::HashMap;
        use std::sync::{Arc, RwLock};
        use std::thread;

        let temp = TempDir::new().unwrap();

        // Create multiple files that reference each other
        for i in 0..5 {
            let content = if i < 4 {
                format!("Content with @file{}.md import", i + 1)
            } else {
                "End of chain".to_string()
            };
            fs::write(temp.path().join(format!("file{}.md", i)), content).unwrap();
        }

        // Create shared cache
        let cache: crate::parsers::ImportCache = Arc::new(RwLock::new(HashMap::new()));

        // Spawn multiple threads that validate different files with the same cache
        let handles: Vec<_> = (0..5)
            .map(|i| {
                let cache = cache.clone();
                let temp_path = temp.path().to_path_buf();
                thread::spawn(move || {
                    let mut config = LintConfig::default();
                    config.set_import_cache(cache);

                    let file_path = temp_path.join(format!("file{}.md", i));
                    let content = fs::read_to_string(&file_path).unwrap();

                    let validator = ImportsValidator;
                    validator.validate(&file_path, &content, &config)
                })
            })
            .collect();

        // All threads should complete without panic (no deadlock)
        for handle in handles {
            let result = handle.join();
            assert!(result.is_ok(), "Thread should complete without panic");
        }

        // Cache should have entries
        {
            let guard = cache.read().unwrap();
            assert!(
                !guard.is_empty(),
                "Cache should have entries after concurrent access"
            );
        }
    }

    #[test]
    fn test_shared_cache_poisoned_lock_does_not_panic() {
        use std::collections::HashMap;
        use std::sync::{Arc, RwLock};
        use std::thread;

        let temp = TempDir::new().unwrap();
        let target = temp.path().join("target.md");
        let file_path = temp.path().join("test.md");
        fs::write(&target, "Target content").unwrap();
        fs::write(&file_path, "See @target.md").unwrap();

        let cache: crate::parsers::ImportCache = Arc::new(RwLock::new(HashMap::new()));

        let cache_for_poison = cache.clone();
        let _ = thread::spawn(move || {
            let _guard = cache_for_poison.write().unwrap();
            panic!("poison import cache lock");
        })
        .join();
        assert!(cache.read().is_err(), "Cache lock should be poisoned");

        let mut config = LintConfig::default();
        config.set_import_cache(cache);

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @target.md", &config);
        let poison_diag = diagnostics.iter().find(|d| d.rule == RULE_CACHE_POISON);
        assert!(
            poison_diag.is_some(),
            "Expected lint::cache-poison warning in diagnostics"
        );
        let d = poison_diag.unwrap();
        assert_eq!(
            d.level,
            DiagnosticLevel::Warning,
            "lint::cache-poison should be a Warning, not {:?}",
            d.level
        );
        assert!(
            d.suggestion.is_some(),
            "lint::cache-poison diagnostic should include a suggestion"
        );
    }

    #[test]
    fn test_shared_cache_poisoned_lock_still_reports_missing_import() {
        use std::collections::HashMap;
        use std::sync::{Arc, RwLock};
        use std::thread;

        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.md");
        fs::write(&file_path, "See @missing.md").unwrap();

        let cache: crate::parsers::ImportCache = Arc::new(RwLock::new(HashMap::new()));

        let cache_for_poison = cache.clone();
        let _ = thread::spawn(move || {
            let _guard = cache_for_poison.write().unwrap();
            panic!("poison import cache lock");
        })
        .join();
        assert!(cache.read().is_err(), "Cache lock should be poisoned");

        let mut config = LintConfig::default();
        config.set_import_cache(cache);

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @missing.md", &config);
        assert!(
            diagnostics
                .iter()
                .any(|d| d.rule == "REF-001" && d.message.contains("@missing.md")),
            "Validation should still report missing imports with a poisoned shared cache lock"
        );
        assert!(
            diagnostics.iter().any(|d| d.rule == RULE_CACHE_POISON),
            "Expected lint::cache-poison warning alongside REF-001"
        );
    }

    #[test]
    fn test_shared_cache_poisoned_lock_warning_is_deduplicated() {
        use std::collections::HashMap;
        use std::sync::{Arc, RwLock};
        use std::thread;

        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.md");
        // Multiple imports so the validator hits the poisoned lock multiple times
        fs::write(&file_path, "See @a.md and @b.md and @c.md").unwrap();
        fs::write(temp.path().join("a.md"), "A content").unwrap();
        fs::write(temp.path().join("b.md"), "B content").unwrap();
        fs::write(temp.path().join("c.md"), "C content").unwrap();

        let cache: crate::parsers::ImportCache = Arc::new(RwLock::new(HashMap::new()));

        let cache_for_poison = cache.clone();
        let _ = thread::spawn(move || {
            let _guard = cache_for_poison.write().unwrap();
            panic!("poison import cache lock");
        })
        .join();
        assert!(cache.read().is_err(), "Cache lock should be poisoned");

        let mut config = LintConfig::default();
        config.set_import_cache(cache);

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "See @a.md and @b.md and @c.md", &config);

        let poison_count = diagnostics
            .iter()
            .filter(|d| d.rule == RULE_CACHE_POISON)
            .count();
        assert_eq!(
            poison_count, 1,
            "Expected exactly 1 lint::cache-poison diagnostic (deduplication), got {}",
            poison_count
        );
    }

    #[test]
    fn test_shared_cache_poisoned_lock_deduplication_across_recursive_tree() {
        // Verifies deduplication holds across recursive import traversal:
        // root.md -> a.md -> b.md (nested chain, not just siblings)
        use std::collections::HashMap;
        use std::sync::{Arc, RwLock};
        use std::thread;

        let temp = TempDir::new().unwrap();
        let root = temp.path().join("root.md");
        let a = temp.path().join("a.md");
        let b = temp.path().join("b.md");
        fs::write(&root, "See @a.md").unwrap();
        fs::write(&a, "See @b.md").unwrap();
        fs::write(&b, "B content").unwrap();

        let cache: crate::parsers::ImportCache = Arc::new(RwLock::new(HashMap::new()));

        let cache_for_poison = cache.clone();
        let _ = thread::spawn(move || {
            let _guard = cache_for_poison.write().unwrap();
            panic!("poison import cache lock");
        })
        .join();
        assert!(cache.read().is_err(), "Cache lock should be poisoned");

        let mut config = LintConfig::default();
        config.set_import_cache(cache);

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&root, "See @a.md", &config);

        let poison_count = diagnostics
            .iter()
            .filter(|d| d.rule == RULE_CACHE_POISON)
            .count();
        assert_eq!(
            poison_count, 1,
            "Expected exactly 1 lint::cache-poison across recursive traversal, got {}",
            poison_count
        );
    }

    #[test]
    fn test_revisits_file_when_later_seen_at_shallower_depth() {
        let temp = TempDir::new().unwrap();
        let root = temp.path().join("CLAUDE.md");
        let a = temp.path().join("a.md");
        let b = temp.path().join("b.md");
        let c = temp.path().join("c.md");
        let d = temp.path().join("d.md");
        let shared = temp.path().join("shared.md");
        let leaf = temp.path().join("leaf.md");

        fs::write(&root, "@a.md\n@shared.md").unwrap();
        fs::write(&a, "@b.md").unwrap();
        fs::write(&b, "@c.md").unwrap();
        fs::write(&c, "@d.md").unwrap();
        fs::write(&d, "@shared.md").unwrap();
        fs::write(&shared, "@leaf.md").unwrap();
        fs::write(&leaf, "@missing.md").unwrap();

        let mut config = LintConfig::default();
        config.set_root_dir(temp.path().to_path_buf());

        let validator = ImportsValidator;
        let content = fs::read_to_string(&root).unwrap();
        let diagnostics = validator.validate(&root, &content, &config);

        assert!(
            diagnostics
                .iter()
                .any(|d| d.rule == "REF-001" && d.message.contains("@missing.md")),
            "Traversal should revisit shared.md at shallower depth and report downstream missing imports"
        );
    }

    #[test]
    fn test_shallower_revisit_does_not_duplicate_missing_import_diagnostics() {
        let temp = TempDir::new().unwrap();
        let root = temp.path().join("CLAUDE.md");
        let a = temp.path().join("a.md");
        let b = temp.path().join("b.md");
        let shared = temp.path().join("shared.md");

        fs::write(&root, "@a.md\n@shared.md").unwrap();
        fs::write(&a, "@b.md").unwrap();
        fs::write(&b, "@shared.md").unwrap();
        fs::write(&shared, "@missing.md").unwrap();

        let mut config = LintConfig::default();
        config.set_root_dir(temp.path().to_path_buf());

        let validator = ImportsValidator;
        let content = fs::read_to_string(&root).unwrap();
        let diagnostics = validator.validate(&root, &content, &config);

        let missing: Vec<_> = diagnostics
            .iter()
            .filter(|d| d.rule == "REF-001" && d.message.contains("@missing.md"))
            .collect();
        assert_eq!(
            missing.len(),
            1,
            "Expected a single REF-001 diagnostic for @missing.md, got {}",
            missing.len()
        );
    }

    // ===== REF-003: Duplicate @import =====

    #[test]
    fn test_ref_003_duplicate_import() {
        let temp = TempDir::new().unwrap();
        let target = temp.path().join("target.md");
        let file_path = temp.path().join("test.md");
        fs::write(&target, "Target content").unwrap();
        fs::write(&file_path, "@target.md\n@target.md").unwrap();

        let validator = ImportsValidator;
        let diagnostics =
            validator.validate(&file_path, "@target.md\n@target.md", &LintConfig::default());

        let ref_003: Vec<_> = diagnostics.iter().filter(|d| d.rule == "REF-003").collect();
        assert_eq!(ref_003.len(), 1, "Should detect one duplicate import");
        assert!(ref_003[0].message.contains("target.md"));
    }

    #[test]
    fn test_ref_003_has_fix() {
        let temp = TempDir::new().unwrap();
        let target = temp.path().join("target.md");
        let file_path = temp.path().join("test.md");
        fs::write(&target, "Target content").unwrap();
        fs::write(&file_path, "@target.md\n@target.md").unwrap();

        let validator = ImportsValidator;
        let diagnostics =
            validator.validate(&file_path, "@target.md\n@target.md", &LintConfig::default());

        let ref_003: Vec<_> = diagnostics.iter().filter(|d| d.rule == "REF-003").collect();
        assert_eq!(ref_003.len(), 1);
        assert!(
            ref_003[0].has_fixes(),
            "REF-003 should have auto-fix to delete duplicate import"
        );
        let fix = &ref_003[0].fixes[0];
        assert!(!fix.safe, "REF-003 fix should be unsafe");
        // The fix should be a deletion (replacement is empty)
        assert!(
            fix.replacement.is_empty(),
            "Fix should delete the duplicate line"
        );
    }

    #[test]
    fn test_ref_003_no_duplicate() {
        let temp = TempDir::new().unwrap();
        let a = temp.path().join("a.md");
        let b = temp.path().join("b.md");
        let file_path = temp.path().join("test.md");
        fs::write(&a, "A content").unwrap();
        fs::write(&b, "B content").unwrap();
        fs::write(&file_path, "@a.md\n@b.md").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "@a.md\n@b.md", &LintConfig::default());

        let ref_003: Vec<_> = diagnostics.iter().filter(|d| d.rule == "REF-003").collect();
        assert!(ref_003.is_empty(), "No duplicate imports");
    }

    #[test]
    fn test_ref_003_normalized_paths() {
        let temp = TempDir::new().unwrap();
        let target = temp.path().join("target.md");
        let file_path = temp.path().join("test.md");
        fs::write(&target, "Target content").unwrap();
        fs::write(&file_path, "@target.md\n@./target.md").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(
            &file_path,
            "@target.md\n@./target.md",
            &LintConfig::default(),
        );

        let ref_003: Vec<_> = diagnostics.iter().filter(|d| d.rule == "REF-003").collect();
        assert_eq!(
            ref_003.len(),
            1,
            "Should detect ./target.md as duplicate of target.md"
        );
    }

    #[test]
    fn test_ref_003_disabled() {
        let temp = TempDir::new().unwrap();
        let target = temp.path().join("target.md");
        let file_path = temp.path().join("test.md");
        fs::write(&target, "Target content").unwrap();
        fs::write(&file_path, "@target.md\n@target.md").unwrap();

        let mut config = LintConfig::default();
        config.rules_mut().disabled_rules = vec!["REF-003".to_string()];

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "@target.md\n@target.md", &config);

        let ref_003: Vec<_> = diagnostics.iter().filter(|d| d.rule == "REF-003").collect();
        assert!(ref_003.is_empty(), "REF-003 should be disabled");
    }

    // ===== REF-004: Non-Markdown @import =====

    #[test]
    fn test_ref_004_json_import() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.md");
        fs::write(&file_path, "@config.json").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "@config.json", &LintConfig::default());

        let ref_004: Vec<_> = diagnostics.iter().filter(|d| d.rule == "REF-004").collect();
        assert_eq!(ref_004.len(), 1, "Should detect non-markdown import");
        assert!(ref_004[0].message.contains("config.json"));
        assert!(ref_004[0].message.contains("json"));
    }

    #[test]
    fn test_ref_004_python_import() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.md");
        fs::write(&file_path, "@scripts/deploy.py").unwrap();

        let validator = ImportsValidator;
        let diagnostics =
            validator.validate(&file_path, "@scripts/deploy.py", &LintConfig::default());

        let ref_004: Vec<_> = diagnostics.iter().filter(|d| d.rule == "REF-004").collect();
        assert_eq!(ref_004.len(), 1);
    }

    #[test]
    fn test_ref_004_markdown_import_ok() {
        let temp = TempDir::new().unwrap();
        let target = temp.path().join("guide.md");
        let file_path = temp.path().join("test.md");
        fs::write(&target, "Guide content").unwrap();
        fs::write(&file_path, "@guide.md").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "@guide.md", &LintConfig::default());

        let ref_004: Vec<_> = diagnostics.iter().filter(|d| d.rule == "REF-004").collect();
        assert!(ref_004.is_empty(), "Markdown imports should be OK");
    }

    #[test]
    fn test_ref_004_multiple_non_markdown() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.md");
        fs::write(&file_path, "@config.json\n@script.py\n@utils.ts").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(
            &file_path,
            "@config.json\n@script.py\n@utils.ts",
            &LintConfig::default(),
        );

        let ref_004: Vec<_> = diagnostics.iter().filter(|d| d.rule == "REF-004").collect();
        assert_eq!(ref_004.len(), 3);
    }

    #[test]
    fn test_ref_004_disabled() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.md");
        fs::write(&file_path, "@config.json").unwrap();

        let mut config = LintConfig::default();
        config.rules_mut().disabled_rules = vec!["REF-004".to_string()];

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "@config.json", &config);

        let ref_004: Vec<_> = diagnostics.iter().filter(|d| d.rule == "REF-004").collect();
        assert!(ref_004.is_empty(), "REF-004 should be disabled");
    }

    #[test]
    fn test_ref_004_extensionless_import_ok() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.md");
        fs::write(&file_path, "@utils").unwrap();

        let validator = ImportsValidator;
        let diagnostics = validator.validate(&file_path, "@utils", &LintConfig::default());

        let ref_004: Vec<_> = diagnostics.iter().filter(|d| d.rule == "REF-004").collect();
        assert!(
            ref_004.is_empty(),
            "Extensionless imports should not trigger REF-004"
        );
    }

    #[test]
    fn test_cycle_detection_three_file_chain() {
        let temp = TempDir::new().unwrap();
        let claude = temp.path().join("CLAUDE.md");
        let b = temp.path().join("b.md");
        let c = temp.path().join("c.md");

        fs::write(&claude, "@b.md").unwrap();
        fs::write(&b, "@c.md").unwrap();
        fs::write(&c, "@CLAUDE.md").unwrap();

        let validator = ImportsValidator;
        let content = fs::read_to_string(&claude).unwrap();
        let diagnostics = validator.validate(&claude, &content, &LintConfig::default());

        let cycle_diag = diagnostics.iter().find(|d| d.rule == "CC-MEM-002");
        assert!(
            cycle_diag.is_some(),
            "Three-file cycle (CLAUDE.md -> b.md -> c.md -> CLAUDE.md) should trigger CC-MEM-002"
        );
        let msg = &cycle_diag.unwrap().message;
        assert!(
            msg.contains("b.md") && msg.contains("c.md"),
            "CC-MEM-002 message should contain the full cycle path, got: {msg}"
        );
    }

    #[test]
    fn test_cycle_detection_four_file_chain() {
        let temp = TempDir::new().unwrap();
        let claude = temp.path().join("CLAUDE.md");
        let b = temp.path().join("b.md");
        let c = temp.path().join("c.md");
        let d = temp.path().join("d.md");

        fs::write(&claude, "@b.md").unwrap();
        fs::write(&b, "@c.md").unwrap();
        fs::write(&c, "@d.md").unwrap();
        fs::write(&d, "@CLAUDE.md").unwrap();

        let validator = ImportsValidator;
        let content = fs::read_to_string(&claude).unwrap();
        let diagnostics = validator.validate(&claude, &content, &LintConfig::default());

        assert!(
            diagnostics.iter().any(|d| d.rule == "CC-MEM-002"),
            "Four-file cycle should trigger CC-MEM-002"
        );
        assert!(
            !diagnostics.iter().any(|d| d.rule == "CC-MEM-003"),
            "Four-file cycle should not trigger CC-MEM-003 (cycle detection short-circuits traversal before depth is evaluated)"
        );
    }

    #[test]
    fn test_depth_below_boundary_no_trigger() {
        // 5 files, 4 hops deep. MAX_IMPORT_DEPTH = 5, check is depth+1 > 5.
        // Deepest point: depth=4, check 4+1=5 > 5 is false. Should not trigger CC-MEM-003.
        let temp = TempDir::new().unwrap();
        let claude = temp.path().join("CLAUDE.md");
        let a = temp.path().join("a.md");
        let b = temp.path().join("b.md");
        let c = temp.path().join("c.md");
        let leaf = temp.path().join("leaf.md");

        fs::write(&claude, "@a.md").unwrap();
        fs::write(&a, "@b.md").unwrap();
        fs::write(&b, "@c.md").unwrap();
        fs::write(&c, "@leaf.md").unwrap();
        fs::write(&leaf, "End of chain").unwrap();

        let validator = ImportsValidator;
        let content = fs::read_to_string(&claude).unwrap();
        let diagnostics = validator.validate(&claude, &content, &LintConfig::default());

        assert!(
            !diagnostics.iter().any(|d| d.rule == "CC-MEM-003"),
            "Chain of 5 files (4 imports deep) should not trigger CC-MEM-003"
        );
        assert!(
            !diagnostics.iter().any(|d| d.rule == "CC-MEM-002"),
            "Linear chain with no cycle should not trigger CC-MEM-002"
        );
    }

    #[test]
    fn test_depth_at_boundary_no_trigger() {
        // 6 files in a linear chain: CLAUDE -> a -> b -> c -> d -> leaf.
        // There are 5 import hops, so the deepest file (leaf) is at depth=5.
        // With MAX_IMPORT_DEPTH = 5 and the check `depth + 1 > MAX_IMPORT_DEPTH`:
        // - At depth=4 (file d), recursing into leaf uses 4+1=5 > 5 (false), so it is allowed.
        // - If leaf tried to import another file, that recursion would use 5+1=6 > 5 (true),
        //   and CC-MEM-003 would trigger.
        // This test verifies the boundary: a chain that reaches depth 5 is allowed as long as
        // the leaf file has no further imports, so CC-MEM-003 should NOT fire.
        let temp = TempDir::new().unwrap();
        let claude = temp.path().join("CLAUDE.md");
        let a = temp.path().join("a.md");
        let b = temp.path().join("b.md");
        let c = temp.path().join("c.md");
        let d = temp.path().join("d.md");
        let leaf = temp.path().join("leaf.md");

        fs::write(&claude, "@a.md").unwrap();
        fs::write(&a, "@b.md").unwrap();
        fs::write(&b, "@c.md").unwrap();
        fs::write(&c, "@d.md").unwrap();
        fs::write(&d, "@leaf.md").unwrap();
        fs::write(&leaf, "End of chain").unwrap();

        let validator = ImportsValidator;
        let content = fs::read_to_string(&claude).unwrap();
        let diagnostics = validator.validate(&claude, &content, &LintConfig::default());

        assert!(
            !diagnostics.iter().any(|d| d.rule == "CC-MEM-003"),
            "Chain of 6 files (depth reaches MAX_IMPORT_DEPTH=5) should not trigger CC-MEM-003"
        );
        assert!(
            !diagnostics.iter().any(|d| d.rule == "CC-MEM-002"),
            "Linear chain with no cycle should not trigger CC-MEM-002"
        );
    }

    #[test]
    fn test_concurrent_cycle_detection_no_deadlock() {
        use std::collections::HashMap;
        use std::sync::{Arc, RwLock, mpsc};
        use std::thread;
        use std::time::Duration;

        let temp = TempDir::new().unwrap();
        let claude = temp.path().join("CLAUDE.md");
        let b = temp.path().join("b.md");

        fs::write(&claude, "@b.md").unwrap();
        fs::write(&b, "@CLAUDE.md").unwrap();

        let cache: crate::parsers::ImportCache = Arc::new(RwLock::new(HashMap::new()));
        let (tx, rx) = mpsc::channel();

        for _ in 0..8 {
            let cache = cache.clone();
            let path = claude.clone();
            let content = fs::read_to_string(&path).unwrap();
            let tx = tx.clone();
            thread::spawn(move || {
                let mut config = LintConfig::default();
                config.set_import_cache(cache);
                config.set_root_dir(path.parent().unwrap().to_path_buf());
                let validator = ImportsValidator;
                let result = validator.validate(&path, &content, &config);
                tx.send(result).ok();
            });
        }
        drop(tx);

        for _ in 0..8 {
            let diagnostics = rx
                .recv_timeout(Duration::from_secs(10))
                .expect("Thread did not complete within 10s (possible deadlock)");
            assert!(
                diagnostics.iter().any(|d| d.rule == "CC-MEM-002"),
                "Each thread should detect CC-MEM-002 in two-file cycle"
            );
        }
    }

    #[test]
    fn test_concurrent_three_file_cycle_shared_cache() {
        use std::collections::HashMap;
        use std::sync::{Arc, RwLock};
        use std::thread;

        let temp = TempDir::new().unwrap();
        let claude = temp.path().join("CLAUDE.md");
        let b = temp.path().join("b.md");
        let c = temp.path().join("c.md");

        fs::write(&claude, "@b.md").unwrap();
        fs::write(&b, "@c.md").unwrap();
        fs::write(&c, "@CLAUDE.md").unwrap();

        let cache: crate::parsers::ImportCache = Arc::new(RwLock::new(HashMap::new()));

        let handles: Vec<_> = (0..10)
            .map(|_| {
                let cache = cache.clone();
                let path = claude.clone();
                let content = fs::read_to_string(&path).unwrap();
                thread::spawn(move || {
                    let mut config = LintConfig::default();
                    config.set_import_cache(cache);
                    config.set_root_dir(path.parent().unwrap().to_path_buf());
                    let validator = ImportsValidator;
                    validator.validate(&path, &content, &config)
                })
            })
            .collect();

        for handle in handles {
            let diagnostics = handle
                .join()
                .expect("Thread panicked during three-file cycle detection");
            assert!(
                diagnostics.iter().any(|d| d.rule == "CC-MEM-002"),
                "Each thread should detect CC-MEM-002 in three-file cycle"
            );
        }

        let guard = cache.read().unwrap();
        assert!(
            guard.len() >= 3,
            "Shared cache should contain entries for all 3 files, found {}",
            guard.len()
        );
    }

    #[test]
    fn test_concurrent_cycle_near_depth_limit() {
        use std::collections::HashMap;
        use std::sync::{Arc, RwLock};
        use std::thread;

        let temp = TempDir::new().unwrap();
        let claude = temp.path().join("CLAUDE.md");
        let a = temp.path().join("a.md");
        let b = temp.path().join("b.md");
        let c = temp.path().join("c.md");
        let d = temp.path().join("d.md");

        fs::write(&claude, "@a.md").unwrap();
        fs::write(&a, "@b.md").unwrap();
        fs::write(&b, "@c.md").unwrap();
        fs::write(&c, "@d.md").unwrap();
        fs::write(&d, "@CLAUDE.md").unwrap();

        let cache: crate::parsers::ImportCache = Arc::new(RwLock::new(HashMap::new()));

        let handles: Vec<_> = (0..5)
            .map(|_| {
                let cache = cache.clone();
                let path = claude.clone();
                let content = fs::read_to_string(&path).unwrap();
                thread::spawn(move || {
                    let mut config = LintConfig::default();
                    config.set_import_cache(cache);
                    config.set_root_dir(path.parent().unwrap().to_path_buf());
                    let validator = ImportsValidator;
                    validator.validate(&path, &content, &config)
                })
            })
            .collect();

        for handle in handles {
            let diagnostics = handle
                .join()
                .expect("Thread panicked during near-depth-limit cycle detection");
            assert!(
                diagnostics.iter().any(|d| d.rule == "CC-MEM-002"),
                "Cycle at depth 4 should trigger CC-MEM-002"
            );
            assert!(
                !diagnostics.iter().any(|d| d.rule == "CC-MEM-003"),
                "Cycle at depth 4 should not trigger CC-MEM-003"
            );
        }
    }

    #[test]
    fn test_concurrent_diamond_dependency_no_duplicate_diagnostics() {
        use std::collections::HashMap;
        use std::sync::{Arc, RwLock};
        use std::thread;

        let temp = TempDir::new().unwrap();
        let claude = temp.path().join("CLAUDE.md");
        let b = temp.path().join("b.md");
        let c = temp.path().join("c.md");
        let shared = temp.path().join("shared.md");

        fs::write(&claude, "@b.md\n@c.md").unwrap();
        fs::write(&b, "@shared.md").unwrap();
        fs::write(&c, "@shared.md").unwrap();
        fs::write(&shared, "@missing.md").unwrap();

        let cache: crate::parsers::ImportCache = Arc::new(RwLock::new(HashMap::new()));

        let handles: Vec<_> = (0..5)
            .map(|_| {
                let cache = cache.clone();
                let path = claude.clone();
                let content = fs::read_to_string(&path).unwrap();
                thread::spawn(move || {
                    let mut config = LintConfig::default();
                    config.set_import_cache(cache);
                    config.set_root_dir(path.parent().unwrap().to_path_buf());
                    let validator = ImportsValidator;
                    validator.validate(&path, &content, &config)
                })
            })
            .collect();

        for handle in handles {
            let diagnostics = handle
                .join()
                .expect("Thread panicked during diamond dependency validation");
            let missing_count = diagnostics
                .iter()
                .filter(|d| {
                    (d.rule == "CC-MEM-001" || d.rule == "REF-001")
                        && d.message.contains("@missing.md")
                })
                .count();
            assert_eq!(
                missing_count, 1,
                "Diamond dependency should produce exactly one missing-import diagnostic for @missing.md (deduplication check)"
            );
        }
    }

    #[test]
    fn test_missing_transitive_import_stops_traversal() {
        let temp = TempDir::new().unwrap();
        let claude = temp.path().join("CLAUDE.md");
        let a = temp.path().join("a.md");

        fs::write(&claude, "@a.md").unwrap();
        fs::write(&a, "@b.md").unwrap();

        let validator = ImportsValidator;
        let content = fs::read_to_string(&claude).unwrap();
        let diagnostics = validator.validate(&claude, &content, &LintConfig::default());

        assert!(
            diagnostics.iter().any(|d| {
                (d.rule == "CC-MEM-001" || d.rule == "REF-001") && d.message.contains("@b.md")
            }),
            "Should report missing import for b.md"
        );
        assert!(
            !diagnostics.iter().any(|d| d.message.contains("c.md")),
            "Should not reference c.md since b.md does not exist"
        );
    }

    #[test]
    fn test_concurrent_different_roots_shared_cache() {
        use std::collections::HashMap;
        use std::sync::{Arc, RwLock};
        use std::thread;

        let temp = TempDir::new().unwrap();
        let claude = temp.path().join("CLAUDE.md");
        let skill = temp.path().join("SKILL.md");
        let b = temp.path().join("b.md");

        fs::write(&claude, "@b.md").unwrap();
        fs::write(&skill, "@b.md").unwrap();
        fs::write(&b, "@CLAUDE.md").unwrap();

        let cache: crate::parsers::ImportCache = Arc::new(RwLock::new(HashMap::new()));

        // Interleave CLAUDE.md and SKILL.md handles in one Vec so both groups race
        // against each other and against the shared cache simultaneously.
        let handles: Vec<(bool, _)> = (0..10)
            .map(|i| {
                let cache = cache.clone();
                let is_claude = i % 2 == 0;
                let path = if is_claude {
                    claude.clone()
                } else {
                    skill.clone()
                };
                let content = fs::read_to_string(&path).unwrap();
                let handle = thread::spawn(move || {
                    let mut config = LintConfig::default();
                    config.set_import_cache(cache);
                    config.set_root_dir(path.parent().unwrap().to_path_buf());
                    let validator = ImportsValidator;
                    validator.validate(&path, &content, &config)
                });
                (is_claude, handle)
            })
            .collect();

        for (is_claude, handle) in handles {
            let diagnostics = handle.join().expect("Thread panicked");
            if is_claude {
                assert!(
                    diagnostics.iter().any(|d| d.rule == "CC-MEM-002"),
                    "CLAUDE.md threads should detect cycle (CC-MEM-002)"
                );
            } else {
                assert!(
                    !diagnostics.iter().any(|d| d.rule == "CC-MEM-002"),
                    "SKILL.md threads should not get CC-MEM-002 (cycle rules only apply to CLAUDE.md roots)"
                );
            }
        }
    }

    #[test]
    fn test_cycle_detection_three_file_chain_with_non_claude_root() {
        let temp = TempDir::new().unwrap();
        let skill = temp.path().join("SKILL.md");
        let b = temp.path().join("b.md");
        let c = temp.path().join("c.md");

        fs::write(&skill, "@b.md").unwrap();
        fs::write(&b, "@c.md").unwrap();
        fs::write(&c, "@SKILL.md").unwrap();

        let validator = ImportsValidator;
        let content = fs::read_to_string(&skill).unwrap();
        let diagnostics = validator.validate(&skill, &content, &LintConfig::default());

        assert!(
            !diagnostics.iter().any(|d| d.rule == "CC-MEM-002"),
            "SKILL.md root should not trigger CC-MEM-002 (cycle rules only apply to CLAUDE.md roots)"
        );
        assert!(
            !diagnostics.iter().any(|d| d.rule == "CC-MEM-003"),
            "SKILL.md root should not trigger CC-MEM-003 (depth rules only apply to CLAUDE.md roots)"
        );
    }
}