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
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
//! Tests extracted from lib.rs during module split (task #354).
//!
//! These tests exercise the public API surface of agnix-core:
//! file type detection, single-file validation, project validation,
//! and the validator registry.

// Allow common test patterns that clippy flags but are intentional in tests
#![allow(
    clippy::field_reassign_with_default,
    clippy::len_zero,
    clippy::useless_vec
)]

use std::path::{Path, PathBuf};

use agnix_core::*;

/// Extract diagnostics from a successful `ValidationOutcome`, panicking on
/// `IoError` or `Skipped` variants.
fn expect_success(outcome: ValidationOutcome) -> Vec<Diagnostic> {
    match outcome {
        ValidationOutcome::Success(diags) => diags,
        other => panic!("expected ValidationOutcome::Success, got: {:?}", other),
    }
}

fn workspace_root() -> &'static Path {
    use std::sync::OnceLock;

    static ROOT: OnceLock<PathBuf> = OnceLock::new();
    ROOT.get_or_init(|| {
        let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        for ancestor in manifest_dir.ancestors() {
            let cargo_toml = ancestor.join("Cargo.toml");
            if let Ok(content) = std::fs::read_to_string(&cargo_toml)
                && (content.contains("[workspace]") || content.contains("[workspace."))
            {
                return ancestor.to_path_buf();
            }
        }
        panic!(
            "Failed to locate workspace root from CARGO_MANIFEST_DIR={}",
            manifest_dir.display()
        );
    })
    .as_path()
}

#[test]
fn test_detect_skill_file() {
    assert_eq!(detect_file_type(Path::new("SKILL.md")), FileType::Skill);
    assert_eq!(
        detect_file_type(Path::new(".claude/skills/my-skill/SKILL.md")),
        FileType::Skill
    );
}

#[test]
fn test_detect_claude_md() {
    assert_eq!(detect_file_type(Path::new("CLAUDE.md")), FileType::ClaudeMd);
    assert_eq!(detect_file_type(Path::new("AGENTS.md")), FileType::ClaudeMd);
    assert_eq!(
        detect_file_type(Path::new("project/CLAUDE.md")),
        FileType::ClaudeMd
    );
}

#[test]
fn test_detect_instruction_variants() {
    // CLAUDE.local.md variant
    assert_eq!(
        detect_file_type(Path::new("CLAUDE.local.md")),
        FileType::ClaudeMd
    );
    assert_eq!(
        detect_file_type(Path::new("project/CLAUDE.local.md")),
        FileType::ClaudeMd
    );

    // AGENTS.local.md variant
    assert_eq!(
        detect_file_type(Path::new("AGENTS.local.md")),
        FileType::ClaudeMd
    );
    assert_eq!(
        detect_file_type(Path::new("subdir/AGENTS.local.md")),
        FileType::ClaudeMd
    );

    // AGENTS.override.md variant
    assert_eq!(
        detect_file_type(Path::new("AGENTS.override.md")),
        FileType::ClaudeMd
    );
    assert_eq!(
        detect_file_type(Path::new("deep/nested/AGENTS.override.md")),
        FileType::ClaudeMd
    );
}

#[test]
fn test_repo_agents_md_matches_claude_md() {
    let repo_root = workspace_root();

    let claude_path = repo_root.join("CLAUDE.md");
    let claude = std::fs::read_to_string(&claude_path).unwrap_or_else(|e| {
        panic!("Failed to read CLAUDE.md at {}: {e}", claude_path.display());
    });
    let agents_path = repo_root.join("AGENTS.md");
    let agents = std::fs::read_to_string(&agents_path).unwrap_or_else(|e| {
        panic!("Failed to read AGENTS.md at {}: {e}", agents_path.display());
    });

    assert_eq!(agents, claude, "AGENTS.md must match CLAUDE.md");
}

#[test]
fn test_detect_agents() {
    assert_eq!(
        detect_file_type(Path::new("agents/my-agent.md")),
        FileType::Agent
    );
    assert_eq!(
        detect_file_type(Path::new(".claude/agents/helper.md")),
        FileType::Agent
    );
}

#[test]
fn test_detect_hooks() {
    assert_eq!(
        detect_file_type(Path::new("settings.json")),
        FileType::Hooks
    );
    assert_eq!(
        detect_file_type(Path::new(".claude/settings.local.json")),
        FileType::Hooks
    );
}

#[test]
fn test_detect_plugin() {
    // plugin.json in .claude-plugin/ directory
    assert_eq!(
        detect_file_type(Path::new("my-plugin.claude-plugin/plugin.json")),
        FileType::Plugin
    );
    // plugin.json outside .claude-plugin/ is still classified as Plugin
    // (validator checks location constraint CC-PL-001)
    assert_eq!(
        detect_file_type(Path::new("some/plugin.json")),
        FileType::Plugin
    );
    assert_eq!(detect_file_type(Path::new("plugin.json")), FileType::Plugin);
}

#[test]
fn test_detect_generic_markdown() {
    // Generic markdown in non-excluded directories
    assert_eq!(
        detect_file_type(Path::new("notes/setup.md")),
        FileType::GenericMarkdown
    );
    assert_eq!(
        detect_file_type(Path::new("plans/feature.md")),
        FileType::GenericMarkdown
    );
    assert_eq!(
        detect_file_type(Path::new("research/analysis.md")),
        FileType::GenericMarkdown
    );
}

#[test]
fn test_detect_excluded_project_files() {
    // Common project files should be Unknown, not GenericMarkdown
    assert_eq!(detect_file_type(Path::new("README.md")), FileType::Unknown);
    assert_eq!(
        detect_file_type(Path::new("CONTRIBUTING.md")),
        FileType::Unknown
    );
    assert_eq!(detect_file_type(Path::new("LICENSE.md")), FileType::Unknown);
    assert_eq!(
        detect_file_type(Path::new("CODE_OF_CONDUCT.md")),
        FileType::Unknown
    );
    assert_eq!(
        detect_file_type(Path::new("SECURITY.md")),
        FileType::Unknown
    );
    // Case insensitive
    assert_eq!(detect_file_type(Path::new("readme.md")), FileType::Unknown);
    assert_eq!(detect_file_type(Path::new("Readme.md")), FileType::Unknown);
}

#[test]
fn test_detect_excluded_documentation_directories() {
    // Files in docs/ directories should be Unknown
    assert_eq!(
        detect_file_type(Path::new("docs/guide.md")),
        FileType::Unknown
    );
    assert_eq!(detect_file_type(Path::new("doc/api.md")), FileType::Unknown);
    assert_eq!(
        detect_file_type(Path::new("documentation/setup.md")),
        FileType::Unknown
    );
    assert_eq!(
        detect_file_type(Path::new("docs/descriptors/some-linter.md")),
        FileType::Unknown
    );
    assert_eq!(
        detect_file_type(Path::new("wiki/getting-started.md")),
        FileType::Unknown
    );
    assert_eq!(
        detect_file_type(Path::new("examples/basic.md")),
        FileType::Unknown
    );
}

#[test]
fn test_agent_directory_takes_precedence_over_filename_exclusion() {
    // agents/README.md should be detected as Agent, not Unknown
    assert_eq!(
        detect_file_type(Path::new("agents/README.md")),
        FileType::Agent,
        "agents/README.md should be Agent, not excluded as README"
    );
    assert_eq!(
        detect_file_type(Path::new(".claude/agents/README.md")),
        FileType::Agent,
        ".claude/agents/README.md should be Agent"
    );
    assert_eq!(
        detect_file_type(Path::new("agents/CONTRIBUTING.md")),
        FileType::Agent,
        "agents/CONTRIBUTING.md should be Agent"
    );
}

#[test]
fn test_detect_mcp() {
    assert_eq!(detect_file_type(Path::new("mcp.json")), FileType::Mcp);
    assert_eq!(detect_file_type(Path::new("tools.mcp.json")), FileType::Mcp);
    assert_eq!(
        detect_file_type(Path::new("my-server.mcp.json")),
        FileType::Mcp
    );
    assert_eq!(detect_file_type(Path::new("mcp-tools.json")), FileType::Mcp);
    assert_eq!(
        detect_file_type(Path::new("mcp-servers.json")),
        FileType::Mcp
    );
    assert_eq!(
        detect_file_type(Path::new(".claude/mcp.json")),
        FileType::Mcp
    );
}

#[test]
fn test_detect_codex() {
    assert_eq!(
        detect_file_type(Path::new(".codex/config.toml")),
        FileType::CodexConfig
    );
    assert_eq!(
        detect_file_type(Path::new("project/.codex/config.toml")),
        FileType::CodexConfig
    );
    // config.toml outside .codex should be Unknown
    assert_eq!(
        detect_file_type(Path::new("config.toml")),
        FileType::Unknown
    );
    assert_eq!(
        detect_file_type(Path::new("other/config.toml")),
        FileType::Unknown
    );
}

#[test]
fn test_detect_unknown() {
    assert_eq!(detect_file_type(Path::new("main.rs")), FileType::Unknown);
    assert_eq!(
        detect_file_type(Path::new("package.json")),
        FileType::Unknown
    );
}

#[test]
fn test_detect_gemini_md() {
    assert_eq!(detect_file_type(Path::new("GEMINI.md")), FileType::GeminiMd);
    assert_eq!(
        detect_file_type(Path::new("GEMINI.local.md")),
        FileType::GeminiMd
    );
    assert_eq!(
        detect_file_type(Path::new("project/GEMINI.md")),
        FileType::GeminiMd
    );
    assert_eq!(
        detect_file_type(Path::new("subdir/GEMINI.local.md")),
        FileType::GeminiMd
    );
}

#[test]
fn test_validators_for_gemini_md() {
    let registry = ValidatorRegistry::with_defaults();
    let validators = registry.validators_for(FileType::GeminiMd);
    assert_eq!(validators.len(), 5);
}

#[test]
fn test_validators_for_gemini_settings() {
    let registry = ValidatorRegistry::with_defaults();
    let validators = registry.validators_for(FileType::GeminiSettings);
    assert_eq!(validators.len(), 1);
    assert_eq!(validators[0].name(), "GeminiSettingsValidator");
}

#[test]
fn test_validators_for_gemini_extension() {
    let registry = ValidatorRegistry::with_defaults();
    let validators = registry.validators_for(FileType::GeminiExtension);
    assert_eq!(validators.len(), 1);
    assert_eq!(validators[0].name(), "GeminiExtensionValidator");
}

#[test]
fn test_validators_for_gemini_ignore() {
    let registry = ValidatorRegistry::with_defaults();
    let validators = registry.validators_for(FileType::GeminiIgnore);
    assert_eq!(validators.len(), 1);
    assert_eq!(validators[0].name(), "GeminiIgnoreValidator");
}

#[test]
fn test_validators_for_skill() {
    let registry = ValidatorRegistry::with_defaults();
    let validators = registry.validators_for(FileType::Skill);
    assert_eq!(validators.len(), 4);
}

#[test]
fn test_validators_for_claude_md() {
    let registry = ValidatorRegistry::with_defaults();
    let validators = registry.validators_for(FileType::ClaudeMd);
    assert_eq!(validators.len(), 8);
    assert!(validators.iter().any(|v| v.name() == "AmpValidator"));
}

#[test]
fn test_validators_for_amp_check() {
    let registry = ValidatorRegistry::with_defaults();
    let validators = registry.validators_for(FileType::AmpCheck);
    assert!(!validators.is_empty());
    assert!(validators.iter().any(|v| v.name() == "AmpValidator"));
}

#[test]
fn test_validators_for_amp_settings() {
    let registry = ValidatorRegistry::with_defaults();
    let validators = registry.validators_for(FileType::AmpSettings);
    assert!(!validators.is_empty());
    assert!(validators.iter().any(|v| v.name() == "AmpValidator"));
}

#[test]
fn test_validators_for_mcp() {
    let registry = ValidatorRegistry::with_defaults();
    let validators = registry.validators_for(FileType::Mcp);
    assert_eq!(validators.len(), 1);
}

#[test]
fn test_validators_for_unknown() {
    let registry = ValidatorRegistry::with_defaults();
    let validators = registry.validators_for(FileType::Unknown);
    assert_eq!(validators.len(), 0);
}

#[test]
fn test_validate_file_with_custom_registry() {
    struct DummyValidator;

    impl Validator for DummyValidator {
        fn validate(&self, path: &Path, _content: &str, _config: &LintConfig) -> Vec<Diagnostic> {
            vec![Diagnostic::error(
                path.to_path_buf(),
                1,
                1,
                "TEST-001",
                "Registry override".to_string(),
            )]
        }
    }

    let temp = tempfile::TempDir::new().unwrap();
    let skill_path = temp.path().join("SKILL.md");
    std::fs::write(&skill_path, "---\nname: test\n---\nBody").unwrap();

    let mut registry = ValidatorRegistry::new();
    registry.register(FileType::Skill, || Box::new(DummyValidator));

    let diagnostics = expect_success(
        validate_file_with_registry(&skill_path, &LintConfig::default(), &registry).unwrap(),
    );

    assert_eq!(diagnostics.len(), 1);
    assert_eq!(diagnostics[0].rule, "TEST-001");
}

#[test]
fn test_validate_file_unknown_type() {
    let temp = tempfile::TempDir::new().unwrap();
    let unknown_path = temp.path().join("test.rs");
    std::fs::write(&unknown_path, "fn main() {}").unwrap();

    let config = LintConfig::default();
    let outcome = validate_file(&unknown_path, &config).unwrap();
    assert!(
        outcome.is_skipped(),
        "Unknown file type should return ValidationOutcome::Skipped, got: {:?}",
        outcome
    );
}

#[test]
fn test_validate_file_skill() {
    let temp = tempfile::TempDir::new().unwrap();
    let skill_dir = temp.path().join("test-skill");
    std::fs::create_dir_all(&skill_dir).unwrap();
    let skill_path = skill_dir.join("SKILL.md");
    std::fs::write(
        &skill_path,
        "---\nname: test-skill\ndescription: Use when testing\n---\nBody",
    )
    .unwrap();

    let config = LintConfig::default();
    let diagnostics = expect_success(validate_file(&skill_path, &config).unwrap());

    assert!(diagnostics.is_empty());
}

#[test]
fn test_validate_file_invalid_skill() {
    let temp = tempfile::TempDir::new().unwrap();
    let skill_path = temp.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        "---\nname: deploy-prod\ndescription: Deploys\n---\nBody",
    )
    .unwrap();

    let config = LintConfig::default();
    let diagnostics = expect_success(validate_file(&skill_path, &config).unwrap());

    assert!(!diagnostics.is_empty());
    assert!(diagnostics.iter().any(|d| d.rule == "CC-SK-006"));
}

#[test]
fn test_validate_project_finds_issues() {
    let temp = tempfile::TempDir::new().unwrap();
    let skill_dir = temp.path().join("skills").join("deploy");
    std::fs::create_dir_all(&skill_dir).unwrap();
    std::fs::write(
        skill_dir.join("SKILL.md"),
        "---\nname: deploy-prod\ndescription: Deploys\n---\nBody",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    assert!(!result.diagnostics.is_empty());
}

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

    // Disable VER-001 since we're testing an empty project
    let mut config = LintConfig::default();
    config.rules_mut().disabled_rules = vec!["VER-001".to_string()];
    let result = validate_project(temp.path(), &config).unwrap();

    assert!(result.diagnostics.is_empty());
}

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

    let skill_dir = temp.path().join("skill1");
    std::fs::create_dir_all(&skill_dir).unwrap();
    std::fs::write(
        skill_dir.join("SKILL.md"),
        "---\nname: deploy-prod\ndescription: Deploys\n---\nBody",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    for i in 1..result.diagnostics.len() {
        assert!(result.diagnostics[i - 1].level <= result.diagnostics[i].level);
    }
}

#[test]
fn test_validate_invalid_skill_triggers_both_rules() {
    let temp = tempfile::TempDir::new().unwrap();
    let skill_path = temp.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        "---\nname: deploy-prod\ndescription: Deploys\nallowed-tools: Bash Read Write\n---\nBody",
    )
    .unwrap();

    let config = LintConfig::default();
    let diagnostics = expect_success(validate_file(&skill_path, &config).unwrap());

    assert!(diagnostics.iter().any(|d| d.rule == "CC-SK-006"));
    assert!(diagnostics.iter().any(|d| d.rule == "CC-SK-007"));
}

#[test]
fn test_validate_valid_skill_produces_no_errors() {
    let temp = tempfile::TempDir::new().unwrap();
    let skill_dir = temp.path().join("code-review");
    std::fs::create_dir_all(&skill_dir).unwrap();
    let skill_path = skill_dir.join("SKILL.md");
    std::fs::write(
        &skill_path,
        "---\nname: code-review\ndescription: Use when reviewing code\n---\nBody",
    )
    .unwrap();

    let config = LintConfig::default();
    let diagnostics = expect_success(validate_file(&skill_path, &config).unwrap());

    let errors: Vec<_> = diagnostics
        .iter()
        .filter(|d| d.level == DiagnosticLevel::Error)
        .collect();
    assert!(errors.is_empty());
}

#[test]
fn test_parallel_validation_deterministic_output() {
    // Create a project structure with multiple files that will generate diagnostics
    let temp = tempfile::TempDir::new().unwrap();

    // Create multiple skill files with issues to ensure non-trivial parallel work
    for i in 0..5 {
        let skill_dir = temp.path().join(format!("skill-{}", i));
        std::fs::create_dir_all(&skill_dir).unwrap();
        std::fs::write(
            skill_dir.join("SKILL.md"),
            format!(
                "---\nname: deploy-prod-{}\ndescription: Deploys things\n---\nBody",
                i
            ),
        )
        .unwrap();
    }

    // Create some CLAUDE.md files too
    for i in 0..3 {
        let dir = temp.path().join(format!("project-{}", i));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("CLAUDE.md"),
            "# Project\n\nBe helpful and concise.\n",
        )
        .unwrap();
    }

    let config = LintConfig::default();

    // Run validation multiple times and verify identical output
    let first_result = validate_project(temp.path(), &config).unwrap();

    for run in 1..=10 {
        let result = validate_project(temp.path(), &config).unwrap();

        assert_eq!(
            first_result.diagnostics.len(),
            result.diagnostics.len(),
            "Run {} produced different number of diagnostics",
            run
        );

        for (i, (a, b)) in first_result
            .diagnostics
            .iter()
            .zip(result.diagnostics.iter())
            .enumerate()
        {
            assert_eq!(
                a.file, b.file,
                "Run {} diagnostic {} has different file",
                run, i
            );
            assert_eq!(
                a.rule, b.rule,
                "Run {} diagnostic {} has different rule",
                run, i
            );
            assert_eq!(
                a.level, b.level,
                "Run {} diagnostic {} has different level",
                run, i
            );
        }
    }

    // Verify we actually got some diagnostics (the dangerous name rule should fire)
    assert!(
        !first_result.diagnostics.is_empty(),
        "Expected diagnostics for deploy-prod-* skill names"
    );
}

#[test]
fn test_parallel_validation_single_file() {
    // Edge case: verify parallel code works correctly with just one file
    let temp = tempfile::TempDir::new().unwrap();
    std::fs::write(
        temp.path().join("SKILL.md"),
        "---\nname: deploy-prod\ndescription: Deploys\n---\nBody",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // Should have at least one diagnostic for the dangerous name (CC-SK-006)
    assert!(
        result.diagnostics.iter().any(|d| d.rule == "CC-SK-006"),
        "Expected CC-SK-006 diagnostic for dangerous deploy-prod name"
    );
}

#[test]
fn test_parallel_validation_mixed_results() {
    // Test mix of valid and invalid files processed in parallel
    let temp = tempfile::TempDir::new().unwrap();

    // Valid skill (no diagnostics expected)
    let valid_dir = temp.path().join("valid");
    std::fs::create_dir_all(&valid_dir).unwrap();
    std::fs::write(
        valid_dir.join("SKILL.md"),
        "---\nname: valid\ndescription: Use when reviewing code\n---\nBody",
    )
    .unwrap();

    // Invalid skill (diagnostics expected)
    let invalid_dir = temp.path().join("invalid");
    std::fs::create_dir_all(&invalid_dir).unwrap();
    std::fs::write(
        invalid_dir.join("SKILL.md"),
        "---\nname: deploy-prod\ndescription: Deploys\n---\nBody",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // Should have diagnostics only from the invalid skill
    let error_diagnostics: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.level == DiagnosticLevel::Error)
        .collect();

    assert!(
        error_diagnostics
            .iter()
            .all(|d| d.file.to_string_lossy().contains("invalid")),
        "Errors should only come from the invalid skill"
    );
}

#[test]
fn test_validate_project_agents_md_collection() {
    // Verify that validation correctly collects AGENTS.md paths for AGM-006
    let temp = tempfile::TempDir::new().unwrap();

    // Create multiple AGENTS.md files in different directories
    std::fs::write(temp.path().join("AGENTS.md"), "# Root agents").unwrap();

    let subdir = temp.path().join("subproject");
    std::fs::create_dir_all(&subdir).unwrap();
    std::fs::write(subdir.join("AGENTS.md"), "# Subproject agents").unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // Should have AGM-006 warnings for both AGENTS.md files
    let agm006_diagnostics: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "AGM-006")
        .collect();

    assert_eq!(
        agm006_diagnostics.len(),
        2,
        "Expected AGM-006 diagnostic for each AGENTS.md file, got: {:?}",
        agm006_diagnostics
    );
}

#[test]
fn test_validate_project_files_checked_count() {
    // Verify that validation correctly counts recognized file types
    let temp = tempfile::TempDir::new().unwrap();

    // Create recognized file types
    std::fs::write(
        temp.path().join("SKILL.md"),
        "---\nname: test-skill\ndescription: Test skill\n---\nBody",
    )
    .unwrap();
    std::fs::write(temp.path().join("CLAUDE.md"), "# Project memory").unwrap();

    // Create unrecognized file types (should not be counted)
    // Note: .md files are GenericMarkdown (recognized), so use non-markdown extensions
    std::fs::write(temp.path().join("notes.txt"), "Some notes").unwrap();
    std::fs::write(temp.path().join("data.json"), "{}").unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // files_checked should only count recognized types (SKILL.md + CLAUDE.md = 2)
    // .txt and .json (not matching MCP patterns) are FileType::Unknown
    assert_eq!(
        result.files_checked, 2,
        "files_checked should count only recognized file types, got {}",
        result.files_checked
    );
}

#[test]
fn test_validate_project_plugin_detection() {
    let temp = tempfile::TempDir::new().unwrap();
    let plugin_dir = temp.path().join("my-plugin.claude-plugin");
    std::fs::create_dir_all(&plugin_dir).unwrap();

    // Create plugin.json with a validation issue (missing recommended description - CC-PL-004 warning)
    std::fs::write(
        plugin_dir.join("plugin.json"),
        r#"{"name": "test-plugin", "version": "1.0.0"}"#,
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // Should detect the plugin.json and report CC-PL-004 warning for missing description
    let plugin_diagnostics: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("CC-PL-"))
        .collect();

    assert!(
        !plugin_diagnostics.is_empty(),
        "validate_project() should detect and validate plugin.json files"
    );

    assert!(
        plugin_diagnostics.iter().any(|d| d.rule == "CC-PL-004"),
        "Should report CC-PL-004 for missing recommended description field"
    );

    assert!(
        plugin_diagnostics.iter().any(|d| d.rule == "CC-PL-004"
            && d.level == agnix_core::diagnostics::DiagnosticLevel::Warning),
        "CC-PL-004 for missing description should be a warning, not an error"
    );
}

// ===== MCP Validation Integration Tests =====

#[test]
fn test_validate_file_mcp() {
    let temp = tempfile::TempDir::new().unwrap();
    let mcp_path = temp.path().join("tools.mcp.json");
    std::fs::write(
        &mcp_path,
        r#"{"name": "test-tool", "description": "A test tool for testing purposes", "inputSchema": {"type": "object"}}"#,
    )
    .unwrap();

    let config = LintConfig::default();
    let diagnostics = expect_success(validate_file(&mcp_path, &config).unwrap());

    // Tool without consent field should trigger MCP-005 warning
    assert!(diagnostics.iter().any(|d| d.rule == "MCP-005"));
}

#[test]
fn test_validate_file_mcp_invalid_schema() {
    let temp = tempfile::TempDir::new().unwrap();
    let mcp_path = temp.path().join("mcp.json");
    std::fs::write(
        &mcp_path,
        r#"{"name": "test-tool", "description": "A test tool for testing purposes", "inputSchema": "not an object"}"#,
    )
    .unwrap();

    let config = LintConfig::default();
    let diagnostics = expect_success(validate_file(&mcp_path, &config).unwrap());

    // Invalid schema should trigger MCP-003
    assert!(diagnostics.iter().any(|d| d.rule == "MCP-003"));
}

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

    // Create an MCP file with issues
    std::fs::write(
        temp.path().join("tools.mcp.json"),
        r#"{"name": "", "description": "Short", "inputSchema": {"type": "object"}}"#,
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // Should detect the MCP file and report issues
    let mcp_diagnostics: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("MCP-"))
        .collect();

    assert!(
        !mcp_diagnostics.is_empty(),
        "validate_project() should detect and validate MCP files"
    );

    // Empty name should trigger MCP-002
    assert!(
        mcp_diagnostics.iter().any(|d| d.rule == "MCP-002"),
        "Should report MCP-002 for empty name"
    );
}

// ===== Cross-Platform Validation Integration Tests =====

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

    // Create AGENTS.md with Claude-specific features
    std::fs::write(
        temp.path().join("AGENTS.md"),
        r#"# Agent Config
- type: PreToolExecution
  command: echo "test"
"#,
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // Should detect XP-001 error for Claude-specific hooks in AGENTS.md
    let xp_001: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-001")
        .collect();
    assert!(
        !xp_001.is_empty(),
        "Expected XP-001 error for hooks in AGENTS.md"
    );
}

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

    // Create AGENTS.md with context: fork
    std::fs::write(
        temp.path().join("AGENTS.md"),
        r#"---
name: test
context: fork
agent: Explore
---
# Test Agent
"#,
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // Should detect XP-001 errors for Claude-specific features
    let xp_001: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-001")
        .collect();
    assert!(
        !xp_001.is_empty(),
        "Expected XP-001 errors for context:fork and agent in AGENTS.md"
    );
}

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

    // Create AGENTS.md with no headers
    std::fs::write(
        temp.path().join("AGENTS.md"),
        "Just plain text without any markdown headers.",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // Should detect XP-002 warning for missing headers
    let xp_002: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-002")
        .collect();
    assert!(
        !xp_002.is_empty(),
        "Expected XP-002 warning for missing headers in AGENTS.md"
    );
}

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

    // Create AGENTS.md with hard-coded platform paths
    std::fs::write(
        temp.path().join("AGENTS.md"),
        r#"# Config
Check .claude/settings.json and .cursor/rules/ for configuration.
"#,
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // Should detect XP-003 warnings for hard-coded paths
    let xp_003: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-003")
        .collect();
    assert_eq!(
        xp_003.len(),
        2,
        "Expected 2 XP-003 warnings for hard-coded paths"
    );
}

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

    // Create valid AGENTS.md without any issues
    std::fs::write(
        temp.path().join("AGENTS.md"),
        r#"# Project Guidelines

Follow the coding style guide.

## Commands
- npm run build
- npm run test
"#,
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // Should have no XP-* diagnostics
    let xp_rules: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("XP-"))
        .collect();
    assert!(
        xp_rules.is_empty(),
        "Valid AGENTS.md should have no XP-* diagnostics"
    );
}

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

    // Create CLAUDE.md with Claude-specific features (allowed)
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        r#"---
name: test
context: fork
agent: Explore
allowed-tools: Read Write
---
# Claude Agent
"#,
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // XP-001 should NOT fire for CLAUDE.md (Claude features are allowed there)
    let xp_001: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-001")
        .collect();
    assert!(
        xp_001.is_empty(),
        "CLAUDE.md should be allowed to have Claude-specific features"
    );
}

// ===== AGM-006: Multiple AGENTS.md Tests =====

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

    // Create nested AGENTS.md files
    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nThis project does something.",
    )
    .unwrap();

    let subdir = temp.path().join("subdir");
    std::fs::create_dir_all(&subdir).unwrap();
    std::fs::write(
        subdir.join("AGENTS.md"),
        "# Subproject\n\nThis is a nested AGENTS.md.",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // Should detect AGM-006 for both AGENTS.md files
    let agm_006: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "AGM-006")
        .collect();
    assert_eq!(
        agm_006.len(),
        2,
        "Should detect both AGENTS.md files, got {:?}",
        agm_006
    );
    assert!(
        agm_006
            .iter()
            .any(|d| d.file.to_string_lossy().contains("subdir"))
    );
    assert!(
        agm_006
            .iter()
            .any(|d| d.message.contains("Nested AGENTS.md"))
    );
    assert!(
        agm_006
            .iter()
            .any(|d| d.message.contains("Multiple AGENTS.md files"))
    );
}

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

    // Create single AGENTS.md file
    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nThis project does something.",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // Should not detect AGM-006 for a single AGENTS.md
    let agm_006: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "AGM-006")
        .collect();
    assert!(
        agm_006.is_empty(),
        "Single AGENTS.md should not trigger AGM-006"
    );
}

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

    let app_a = temp.path().join("app-a");
    let app_b = temp.path().join("app-b");
    std::fs::create_dir_all(&app_a).unwrap();
    std::fs::create_dir_all(&app_b).unwrap();

    std::fs::write(
        app_a.join("AGENTS.md"),
        "# App A\n\nThis project does something.",
    )
    .unwrap();
    std::fs::write(
        app_b.join("AGENTS.md"),
        "# App B\n\nThis project does something.",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let agm_006: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "AGM-006")
        .collect();
    assert_eq!(
        agm_006.len(),
        2,
        "Should detect both AGENTS.md files, got {:?}",
        agm_006
    );
    assert!(
        agm_006
            .iter()
            .all(|d| d.message.contains("Multiple AGENTS.md files"))
    );
}

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

    // Create nested AGENTS.md files
    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nThis project does something.",
    )
    .unwrap();

    let subdir = temp.path().join("subdir");
    std::fs::create_dir_all(&subdir).unwrap();
    std::fs::write(
        subdir.join("AGENTS.md"),
        "# Subproject\n\nThis is a nested AGENTS.md.",
    )
    .unwrap();

    let mut config = LintConfig::default();
    config.rules_mut().disabled_rules = vec!["AGM-006".to_string()];
    let result = validate_project(temp.path(), &config).unwrap();

    // Should not detect AGM-006 when disabled
    let agm_006: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "AGM-006")
        .collect();
    assert!(agm_006.is_empty(), "AGM-006 should not fire when disabled");
}

// ===== XP-004: Conflicting Build Commands =====

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

    // CLAUDE.md uses npm
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nUse `npm install` for dependencies.",
    )
    .unwrap();

    // AGENTS.md uses pnpm
    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nUse `pnpm install` for dependencies.",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let xp_004: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-004")
        .collect();
    assert!(
        !xp_004.is_empty(),
        "Should detect conflicting package managers"
    );
    assert!(xp_004.iter().any(|d| d.message.contains("npm")));
    assert!(xp_004.iter().any(|d| d.message.contains("pnpm")));
}

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

    // Both files use npm
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nUse `npm install` for dependencies.",
    )
    .unwrap();

    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nUse `npm run build` for building.",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let xp_004: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-004")
        .collect();
    assert!(
        xp_004.is_empty(),
        "Should not detect conflict when same package manager is used"
    );
}

// ===== XP-005: Conflicting Tool Constraints =====

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

    // CLAUDE.md allows Bash
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nallowed-tools: Read Write Bash",
    )
    .unwrap();

    // AGENTS.md disallows Bash
    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nNever use Bash for operations.",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let xp_005: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-005")
        .collect();
    assert!(
        !xp_005.is_empty(),
        "Should detect conflicting tool constraints"
    );
    assert!(xp_005.iter().any(|d| d.message.contains("Bash")));
}

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

    // Both files allow Read
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nallowed-tools: Read Write",
    )
    .unwrap();

    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nYou can use Read for file access.",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let xp_005: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-005")
        .collect();
    assert!(
        xp_005.is_empty(),
        "Should not detect conflict when constraints are consistent"
    );
}

// ===== XP-006: Layer Precedence =====

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

    // Both files exist but neither documents precedence
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nThis is Claude.md.",
    )
    .unwrap();

    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nThis is Agents.md.",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let xp_006: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-006")
        .collect();
    assert!(
        !xp_006.is_empty(),
        "Should detect missing precedence documentation"
    );
}

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

    // CLAUDE.md documents precedence
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nCLAUDE.md takes precedence over AGENTS.md.",
    )
    .unwrap();

    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nThis is Agents.md.",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let xp_006: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-006")
        .collect();
    assert!(
        xp_006.is_empty(),
        "Should not trigger XP-006 when precedence is documented"
    );
}

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

    // Only CLAUDE.md exists
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nThis is Claude.md.",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let xp_006: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-006")
        .collect();
    assert!(
        xp_006.is_empty(),
        "Should not trigger XP-006 with single instruction layer"
    );
}

// ===== XP-004/005/006 Edge Case Tests (review findings) =====

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

    // CLAUDE.md uses npm
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nUse `npm install` for dependencies.",
    )
    .unwrap();

    // AGENTS.md uses pnpm
    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nUse `pnpm install` for dependencies.",
    )
    .unwrap();

    // Add .cursor rules directory with yarn
    let cursor_dir = temp.path().join(".cursor").join("rules");
    std::fs::create_dir_all(&cursor_dir).unwrap();
    std::fs::write(
        cursor_dir.join("dev.mdc"),
        "# Rules\n\nUse `yarn install` for dependencies.",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let xp_004: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-004")
        .collect();

    // Should detect conflicts between all three different package managers
    assert!(
        xp_004.len() >= 2,
        "Should detect multiple conflicts with 3 different package managers, got {}",
        xp_004.len()
    );
}

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

    // CLAUDE.md uses npm
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nUse `npm install` for dependencies.",
    )
    .unwrap();

    // AGENTS.md uses pnpm
    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nUse `pnpm install` for dependencies.",
    )
    .unwrap();

    let mut config = LintConfig::default();
    config.rules_mut().disabled_rules = vec!["XP-004".to_string()];
    let result = validate_project(temp.path(), &config).unwrap();

    let xp_004: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-004")
        .collect();
    assert!(xp_004.is_empty(), "XP-004 should not fire when disabled");
}

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

    // CLAUDE.md allows Bash
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nallowed-tools: Read Write Bash",
    )
    .unwrap();

    // AGENTS.md disallows Bash
    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nNever use Bash for operations.",
    )
    .unwrap();

    let mut config = LintConfig::default();
    config.rules_mut().disabled_rules = vec!["XP-005".to_string()];
    let result = validate_project(temp.path(), &config).unwrap();

    let xp_005: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-005")
        .collect();
    assert!(xp_005.is_empty(), "XP-005 should not fire when disabled");
}

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

    // Both files exist but neither documents precedence
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nThis is Claude.md.",
    )
    .unwrap();

    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nThis is Agents.md.",
    )
    .unwrap();

    let mut config = LintConfig::default();
    config.rules_mut().disabled_rules = vec!["XP-006".to_string()];
    let result = validate_project(temp.path(), &config).unwrap();

    let xp_006: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-006")
        .collect();
    assert!(xp_006.is_empty(), "XP-006 should not fire when disabled");
}

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

    // Create empty CLAUDE.md and AGENTS.md
    std::fs::write(temp.path().join("CLAUDE.md"), "").unwrap();
    std::fs::write(temp.path().join("AGENTS.md"), "").unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // XP-004 should not fire for empty files (no commands)
    let xp_004: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-004")
        .collect();
    assert!(xp_004.is_empty(), "Empty files should not trigger XP-004");

    // XP-005 should not fire for empty files (no constraints)
    let xp_005: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-005")
        .collect();
    assert!(xp_005.is_empty(), "Empty files should not trigger XP-005");
}

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

    // CLAUDE.md allows BASH (uppercase)
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nallowed-tools: Read Write BASH",
    )
    .unwrap();

    // AGENTS.md disallows bash (lowercase)
    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nNever use bash for operations.",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let xp_005: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-005")
        .collect();
    assert!(
        !xp_005.is_empty(),
        "Should detect conflict between BASH and bash (case-insensitive)"
    );
}

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

    // CLAUDE.md allows Bash
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nallowed-tools: Read Write Bash",
    )
    .unwrap();

    // AGENTS.md mentions "subash" (not "Bash")
    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nNever use subash command.",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let xp_005: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XP-005")
        .collect();
    assert!(
        xp_005.is_empty(),
        "Should NOT detect conflict - 'subash' is not 'Bash'"
    );
}

// ===== VER-001 Version Awareness Tests =====

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

    // Create minimal project
    std::fs::write(temp.path().join("CLAUDE.md"), "# Project\n\nInstructions.").unwrap();

    // Default config has no versions pinned
    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let ver_001: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "VER-001")
        .collect();
    assert!(
        !ver_001.is_empty(),
        "Should warn when no tool/spec versions are pinned"
    );
    // Should be Info level
    assert_eq!(ver_001[0].level, DiagnosticLevel::Info);
}

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

    std::fs::write(temp.path().join("CLAUDE.md"), "# Project\n\nInstructions.").unwrap();

    let mut config = LintConfig::default();
    config.tool_versions_mut().claude_code = Some("2.1.3".to_string());
    let result = validate_project(temp.path(), &config).unwrap();

    let ver_001: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "VER-001")
        .collect();
    assert!(
        ver_001.is_empty(),
        "Should NOT warn when a tool version is pinned"
    );
}

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

    std::fs::write(temp.path().join("CLAUDE.md"), "# Project\n\nInstructions.").unwrap();

    let mut config = LintConfig::default();
    config.spec_revisions_mut().mcp_protocol = Some("2025-11-25".to_string());
    let result = validate_project(temp.path(), &config).unwrap();

    let ver_001: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "VER-001")
        .collect();
    assert!(
        ver_001.is_empty(),
        "Should NOT warn when a spec revision is pinned"
    );
}

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

    std::fs::write(temp.path().join("CLAUDE.md"), "# Project\n\nInstructions.").unwrap();

    let mut config = LintConfig::default();
    config.rules_mut().disabled_rules = vec!["VER-001".to_string()];
    let result = validate_project(temp.path(), &config).unwrap();

    let ver_001: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "VER-001")
        .collect();
    assert!(ver_001.is_empty(), "VER-001 should not fire when disabled");
}

// ===== AGM Validation Integration Tests =====

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

    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\n```rust\nfn main() {}",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let agm_001: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "AGM-001")
        .collect();
    assert!(!agm_001.is_empty(), "Should detect unclosed code block");
}

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

    let content = format!("# Project\n\n{}", "x".repeat(13000));
    std::fs::write(temp.path().join("AGENTS.md"), content).unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let agm_003: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "AGM-003")
        .collect();
    assert!(
        !agm_003.is_empty(),
        "Should detect character limit exceeded"
    );
}

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

    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\n- type: PreToolExecution\n  command: echo test",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let agm_005: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "AGM-005")
        .collect();
    assert!(
        !agm_005.is_empty(),
        "Should detect unguarded platform features"
    );
}

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

    std::fs::write(
        temp.path().join("AGENTS.md"),
        r#"# Project

This project is a linter for agent configurations.

## Build Commands

Run npm install and npm build.

## Claude Code Specific

- type: PreToolExecution
  command: echo "test"
"#,
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    let agm_errors: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("AGM-") && d.level == DiagnosticLevel::Error)
        .collect();
    assert!(
        agm_errors.is_empty(),
        "Valid AGENTS.md should have no AGM-* errors, got: {:?}",
        agm_errors
    );
}
// ===== Fixture Directory Regression Tests =====

/// Helper to locate the fixtures directory for testing
fn get_fixtures_dir() -> PathBuf {
    workspace_root().join("tests").join("fixtures")
}

#[test]
fn test_validate_fixtures_directory() {
    // Run validate_project() over tests/fixtures/ to verify detect_file_type() works
    // This is a regression guard for fixture layout (issue #74)
    let fixtures_dir = get_fixtures_dir();

    let config = LintConfig::default();
    let result = validate_project(&fixtures_dir, &config).unwrap();

    // Verify skill fixtures trigger expected AS-* rules
    let skill_diagnostics: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("AS-"))
        .collect();

    // deep-reference/SKILL.md should trigger AS-013 (reference too deep)
    assert!(
        skill_diagnostics
            .iter()
            .any(|d| d.rule == "AS-013" && d.file.to_string_lossy().contains("deep-reference")),
        "Expected AS-013 from deep-reference/SKILL.md fixture"
    );

    // missing-frontmatter/SKILL.md should trigger AS-001 (missing frontmatter)
    assert!(
        skill_diagnostics
            .iter()
            .any(|d| d.rule == "AS-001"
                && d.file.to_string_lossy().contains("missing-frontmatter")),
        "Expected AS-001 from missing-frontmatter/SKILL.md fixture"
    );

    // windows-path/SKILL.md should trigger AS-014 (windows path separator)
    assert!(
        skill_diagnostics
            .iter()
            .any(|d| d.rule == "AS-014" && d.file.to_string_lossy().contains("windows-path")),
        "Expected AS-014 from windows-path/SKILL.md fixture"
    );

    // Verify MCP fixtures trigger expected MCP-* rules
    let mcp_diagnostics: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("MCP-"))
        .collect();

    // At least some MCP diagnostics should be present
    assert!(
        !mcp_diagnostics.is_empty(),
        "Expected MCP diagnostics from tests/fixtures/mcp/*.mcp.json files"
    );

    // missing-required-fields.mcp.json should trigger MCP-002 (missing description)
    assert!(
        mcp_diagnostics
            .iter()
            .any(|d| d.rule == "MCP-002"
                && d.file.to_string_lossy().contains("missing-required-fields")),
        "Expected MCP-002 from missing-required-fields.mcp.json fixture"
    );

    // empty-description.mcp.json should trigger MCP-004 (short description)
    assert!(
        mcp_diagnostics
            .iter()
            .any(|d| d.rule == "MCP-004" && d.file.to_string_lossy().contains("empty-description")),
        "Expected MCP-004 from empty-description.mcp.json fixture"
    );

    // invalid-input-schema.mcp.json should trigger MCP-003 (invalid schema)
    assert!(
        mcp_diagnostics
            .iter()
            .any(|d| d.rule == "MCP-003"
                && d.file.to_string_lossy().contains("invalid-input-schema")),
        "Expected MCP-003 from invalid-input-schema.mcp.json fixture"
    );

    // invalid-jsonrpc-version.mcp.json should trigger MCP-001 (invalid jsonrpc)
    assert!(
        mcp_diagnostics
            .iter()
            .any(|d| d.rule == "MCP-001"
                && d.file.to_string_lossy().contains("invalid-jsonrpc-version")),
        "Expected MCP-001 from invalid-jsonrpc-version.mcp.json fixture"
    );

    // missing-consent.mcp.json should trigger MCP-005 (missing consent)
    assert!(
        mcp_diagnostics
            .iter()
            .any(|d| d.rule == "MCP-005" && d.file.to_string_lossy().contains("missing-consent")),
        "Expected MCP-005 from missing-consent.mcp.json fixture"
    );

    // untrusted-annotations.mcp.json should trigger MCP-006 (untrusted annotations)
    assert!(
        mcp_diagnostics
            .iter()
            .any(|d| d.rule == "MCP-006"
                && d.file.to_string_lossy().contains("untrusted-annotations")),
        "Expected MCP-006 from untrusted-annotations.mcp.json fixture"
    );

    // New MCP expansion fixtures (MCP-013..MCP-024)
    let new_mcp_expectations = [
        ("MCP-013", "invalid-tool-name"),
        ("MCP-014", "invalid-output-schema"),
        ("MCP-015", "missing-resource-required-fields"),
        ("MCP-016", "missing-prompt-name"),
        ("MCP-017", "insecure-http-server"),
        ("MCP-018", "plaintext-env-secret"),
        ("MCP-019", "dangerous-stdio-command"),
        ("MCP-020", "invalid-capability-key"),
        ("MCP-021", "wildcard-http-binding"),
        ("MCP-022", "invalid-args-type"),
        ("MCP-023", "duplicate-server-names"),
        ("MCP-024", "empty-server-config"),
    ];

    for (rule, file_part) in new_mcp_expectations {
        assert!(
            mcp_diagnostics
                .iter()
                .any(|d| d.rule == rule && d.file.to_string_lossy().contains(file_part)),
            "Expected {} from {}.mcp.json fixture",
            rule,
            file_part
        );
    }

    // Verify AGM, XP, REF, and XML fixtures trigger expected rules
    let expectations = [
        (
            "AGM-002",
            "no-headers",
            "Expected AGM-002 from agents_md/no-headers/AGENTS.md fixture",
        ),
        (
            "XP-003",
            "hard-coded",
            "Expected XP-003 from cross_platform/hard-coded/AGENTS.md fixture",
        ),
        (
            "REF-001",
            "missing-import",
            "Expected REF-001 from refs/missing-import.md fixture",
        ),
        (
            "REF-002",
            "broken-link",
            "Expected REF-002 from refs/broken-link.md fixture",
        ),
        (
            "XML-001",
            "xml-001-unclosed",
            "Expected XML-001 from xml/xml-001-unclosed.md fixture",
        ),
        (
            "XML-002",
            "xml-002-mismatch",
            "Expected XML-002 from xml/xml-002-mismatch.md fixture",
        ),
        (
            "XML-003",
            "xml-003-unmatched",
            "Expected XML-003 from xml/xml-003-unmatched.md fixture",
        ),
    ];

    for (rule, file_part, message) in expectations {
        assert!(
            result
                .diagnostics
                .iter()
                .any(|d| { d.rule == rule && d.file.to_string_lossy().contains(file_part) }),
            "{}",
            message
        );
    }

    let amp_diagnostics: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("AMP-"))
        .collect();
    assert!(
        amp_diagnostics.iter().any(|d| {
            d.rule == "AMP-001"
                && d.file
                    .to_string_lossy()
                    .replace('\\', "/")
                    .contains("amp-checks/.agents/checks/missing-name.md")
        }),
        "Expected AMP-001 from amp-checks/.agents/checks/missing-name.md fixture"
    );
    assert!(
        amp_diagnostics.iter().any(|d| {
            d.rule == "AMP-002"
                && d.file
                    .to_string_lossy()
                    .replace('\\', "/")
                    .contains("amp-checks/.agents/checks/invalid-severity.md")
        }),
        "Expected AMP-002 from amp-checks/.agents/checks/invalid-severity.md fixture"
    );
    assert!(
        amp_diagnostics.iter().any(|d| {
            d.rule == "AMP-003"
                && d.file
                    .to_string_lossy()
                    .replace('\\', "/")
                    .contains("amp-checks/AGENTS.md")
        }),
        "Expected AMP-003 from amp-checks/AGENTS.md fixture"
    );
    assert!(
        amp_diagnostics.iter().any(|d| {
            d.rule == "AMP-004"
                && d.file
                    .to_string_lossy()
                    .replace('\\', "/")
                    .contains("amp-checks/.amp/settings.json")
        }),
        "Expected AMP-004 from amp-checks/.amp/settings.json fixture"
    );
    assert!(
        !amp_diagnostics.iter().any(|d| {
            d.file
                .to_string_lossy()
                .replace('\\', "/")
                .contains("amp-checks/.agents/checks/valid.md")
        }),
        "Expected no AMP diagnostics for amp-checks/.agents/checks/valid.md fixture"
    );
}

#[test]
fn test_fixture_positive_cases_by_family() {
    let fixtures_dir = get_fixtures_dir();
    let config = LintConfig::default();

    let temp = tempfile::TempDir::new().unwrap();
    let pe_source = fixtures_dir.join("valid/pe/prompt-complete-valid.md");
    let pe_content = std::fs::read_to_string(&pe_source)
        .unwrap_or_else(|_| panic!("Failed to read {}", pe_source.display()));
    let pe_path = temp.path().join("CLAUDE.md");
    std::fs::write(&pe_path, pe_content).unwrap();

    let mut cases = vec![
        ("AGM-", fixtures_dir.join("agents_md/valid/AGENTS.md")),
        ("XP-", fixtures_dir.join("cross_platform/valid/AGENTS.md")),
        ("MCP-", fixtures_dir.join("mcp/valid-tool.mcp.json")),
        ("REF-", fixtures_dir.join("refs/valid-links.md")),
        ("XML-", fixtures_dir.join("xml/xml-valid.md")),
        (
            "AMP-",
            fixtures_dir.join("amp-checks/.agents/checks/valid.md"),
        ),
    ];
    cases.push(("PE-", pe_path));

    for (prefix, path) in cases {
        let diagnostics = expect_success(validate_file(&path, &config).unwrap());
        let family_diagnostics: Vec<_> = diagnostics
            .iter()
            .filter(|d| d.rule.starts_with(prefix))
            .collect();

        assert!(
            family_diagnostics.is_empty(),
            "Expected no {} diagnostics for fixture {}",
            prefix,
            path.display()
        );
    }
}

#[test]
fn test_fixture_file_type_detection() {
    // Verify that fixture files are detected as correct FileType
    let fixtures_dir = get_fixtures_dir();

    // Skill fixtures should be detected as FileType::Skill
    assert_eq!(
        detect_file_type(&fixtures_dir.join("skills/deep-reference/SKILL.md")),
        FileType::Skill,
        "deep-reference/SKILL.md should be detected as Skill"
    );
    assert_eq!(
        detect_file_type(&fixtures_dir.join("skills/missing-frontmatter/SKILL.md")),
        FileType::Skill,
        "missing-frontmatter/SKILL.md should be detected as Skill"
    );
    assert_eq!(
        detect_file_type(&fixtures_dir.join("skills/windows-path/SKILL.md")),
        FileType::Skill,
        "windows-path/SKILL.md should be detected as Skill"
    );

    // MCP fixtures should be detected as FileType::Mcp
    assert_eq!(
        detect_file_type(&fixtures_dir.join("mcp/valid-tool.mcp.json")),
        FileType::Mcp,
        "valid-tool.mcp.json should be detected as Mcp"
    );
    assert_eq!(
        detect_file_type(&fixtures_dir.join("mcp/empty-description.mcp.json")),
        FileType::Mcp,
        "empty-description.mcp.json should be detected as Mcp"
    );

    // Copilot fixtures should be detected as FileType::Copilot or CopilotScoped
    assert_eq!(
        detect_file_type(&fixtures_dir.join("copilot/.github/copilot-instructions.md")),
        FileType::Copilot,
        "copilot-instructions.md should be detected as Copilot"
    );
    assert_eq!(
        detect_file_type(
            &fixtures_dir.join("copilot/.github/instructions/typescript.instructions.md")
        ),
        FileType::CopilotScoped,
        "typescript.instructions.md should be detected as CopilotScoped"
    );

    // Cline .txt fixtures should be detected as FileType::ClineRulesFolder
    assert_eq!(
        detect_file_type(&fixtures_dir.join("cline/.clinerules/03-python.txt")),
        FileType::ClineRulesFolder,
        "03-python.txt should be detected as ClineRulesFolder"
    );
    assert_eq!(
        detect_file_type(&fixtures_dir.join("cline-invalid/.clinerules/bad-glob.txt")),
        FileType::ClineRulesFolder,
        "bad-glob.txt should be detected as ClineRulesFolder"
    );
    assert_eq!(
        detect_file_type(&fixtures_dir.join("cline-invalid/.clinerules/scalar-paths.txt")),
        FileType::ClineRulesFolder,
        "scalar-paths.txt should be detected as ClineRulesFolder"
    );
    assert_eq!(
        detect_file_type(&fixtures_dir.join("cline-invalid/.clinerules/unknown-keys.txt")),
        FileType::ClineRulesFolder,
        "unknown-keys.txt should be detected as ClineRulesFolder"
    );
}

// ===== Cline Validation Integration Tests =====

#[test]
fn test_validate_cline_fixtures() {
    let fixtures_dir = get_fixtures_dir();
    let config = LintConfig::default();

    // Valid .txt file should produce no CLN-* diagnostics
    let valid_txt = fixtures_dir.join("cline/.clinerules/03-python.txt");
    let diagnostics = expect_success(validate_file(&valid_txt, &config).unwrap());
    let cln_diagnostics: Vec<_> = diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("CLN-"))
        .collect();
    assert!(
        cln_diagnostics.is_empty(),
        "Expected no CLN-* diagnostics for valid 03-python.txt, got: {:?}",
        cln_diagnostics
    );
}

#[test]
fn test_validate_cline_invalid_bad_glob_txt() {
    let fixtures_dir = get_fixtures_dir();
    let config = LintConfig::default();
    let bad_glob = fixtures_dir.join("cline-invalid/.clinerules/bad-glob.txt");
    let diagnostics = expect_success(validate_file(&bad_glob, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "CLN-002"),
        "Expected CLN-002 from bad-glob.txt fixture"
    );
}

#[test]
fn test_validate_cline_invalid_scalar_paths_txt() {
    let fixtures_dir = get_fixtures_dir();
    let config = LintConfig::default();
    let scalar_paths = fixtures_dir.join("cline-invalid/.clinerules/scalar-paths.txt");
    let diagnostics = expect_success(validate_file(&scalar_paths, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "CLN-004"),
        "Expected CLN-004 from scalar-paths.txt fixture"
    );
}

#[test]
fn test_validate_cline_invalid_unknown_keys_txt() {
    let fixtures_dir = get_fixtures_dir();
    let config = LintConfig::default();
    let unknown_keys = fixtures_dir.join("cline-invalid/.clinerules/unknown-keys.txt");
    let diagnostics = expect_success(validate_file(&unknown_keys, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "CLN-003"),
        "Expected CLN-003 from unknown-keys.txt fixture"
    );
}

// ===== GitHub Copilot Validation Integration Tests =====

#[test]
fn test_detect_copilot_global() {
    assert_eq!(
        detect_file_type(Path::new(".github/copilot-instructions.md")),
        FileType::Copilot
    );
    assert_eq!(
        detect_file_type(Path::new("project/.github/copilot-instructions.md")),
        FileType::Copilot
    );
}

#[test]
fn test_detect_copilot_scoped() {
    assert_eq!(
        detect_file_type(Path::new(".github/instructions/typescript.instructions.md")),
        FileType::CopilotScoped
    );
    assert_eq!(
        detect_file_type(Path::new(
            "project/.github/instructions/rust.instructions.md"
        )),
        FileType::CopilotScoped
    );
}

#[test]
fn test_copilot_not_detected_outside_github() {
    // Files outside .github/ should not be detected as Copilot
    assert_ne!(
        detect_file_type(Path::new("copilot-instructions.md")),
        FileType::Copilot
    );
    assert_ne!(
        detect_file_type(Path::new("instructions/typescript.instructions.md")),
        FileType::CopilotScoped
    );
}

#[test]
fn test_validators_for_copilot() {
    let registry = ValidatorRegistry::with_defaults();

    let copilot_validators = registry.validators_for(FileType::Copilot);
    assert_eq!(copilot_validators.len(), 2); // copilot + xml

    let scoped_validators = registry.validators_for(FileType::CopilotScoped);
    assert_eq!(scoped_validators.len(), 2); // copilot + xml
}

#[test]
fn test_validate_copilot_fixtures() {
    // Use validate_file directly since .github is a hidden directory
    // that ignore::WalkBuilder skips by default
    let fixtures_dir = get_fixtures_dir();
    let copilot_dir = fixtures_dir.join("copilot");

    let config = LintConfig::default();

    // Validate global instructions
    let global_path = copilot_dir.join(".github/copilot-instructions.md");
    let diagnostics = expect_success(validate_file(&global_path, &config).unwrap());
    let cop_errors: Vec<_> = diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("COP-") && d.level == DiagnosticLevel::Error)
        .collect();
    assert!(
        cop_errors.is_empty(),
        "Valid global file should have no COP errors, got: {:?}",
        cop_errors
    );

    // Validate scoped instructions
    let scoped_path = copilot_dir.join(".github/instructions/typescript.instructions.md");
    let diagnostics = expect_success(validate_file(&scoped_path, &config).unwrap());
    let cop_errors: Vec<_> = diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("COP-") && d.level == DiagnosticLevel::Error)
        .collect();
    assert!(
        cop_errors.is_empty(),
        "Valid scoped file should have no COP errors, got: {:?}",
        cop_errors
    );

    // Validate custom agent
    let agent_path = copilot_dir.join(".github/agents/reviewer.agent.md");
    let diagnostics = expect_success(validate_file(&agent_path, &config).unwrap());
    let cop_errors: Vec<_> = diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("COP-") && d.level == DiagnosticLevel::Error)
        .collect();
    assert!(
        cop_errors.is_empty(),
        "Valid custom agent file should have no COP errors, got: {:?}",
        cop_errors
    );
    assert!(
        diagnostics.iter().all(|d| d.rule != "COP-010"),
        "Valid custom agent should not trigger COP-010 warnings, got: {:?}",
        diagnostics
            .iter()
            .filter(|d| d.rule == "COP-010")
            .collect::<Vec<_>>()
    );

    // Validate reusable prompt
    let prompt_path = copilot_dir.join(".github/prompts/refactor.prompt.md");
    let diagnostics = expect_success(validate_file(&prompt_path, &config).unwrap());
    let cop_errors: Vec<_> = diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("COP-") && d.level == DiagnosticLevel::Error)
        .collect();
    assert!(
        cop_errors.is_empty(),
        "Valid prompt file should have no COP errors, got: {:?}",
        cop_errors
    );

    // Validate hooks.json
    let hooks_path = copilot_dir.join(".github/hooks/hooks.json");
    let diagnostics = expect_success(validate_file(&hooks_path, &config).unwrap());
    assert!(
        diagnostics.iter().all(|d| d.rule != "COP-017"),
        "Valid hooks.json should not trigger COP-017, got: {:?}",
        diagnostics.iter().map(|d| &d.rule).collect::<Vec<_>>()
    );

    // Validate setup workflow
    let setup_steps_path = copilot_dir.join(".github/workflows/copilot-setup-steps.yml");
    let diagnostics = expect_success(validate_file(&setup_steps_path, &config).unwrap());
    assert!(
        diagnostics.iter().all(|d| d.rule != "COP-018"),
        "Valid setup workflow should not trigger COP-018, got: {:?}",
        diagnostics.iter().map(|d| &d.rule).collect::<Vec<_>>()
    );
}

#[test]
fn test_validate_copilot_invalid_fixtures() {
    // Use validate_file directly since .github is a hidden directory
    let fixtures_dir = get_fixtures_dir();
    let copilot_invalid_dir = fixtures_dir.join("copilot-invalid");
    let config = LintConfig::default();

    // COP-001: Empty global file
    let empty_global = copilot_invalid_dir.join(".github/copilot-instructions.md");
    let diagnostics = expect_success(validate_file(&empty_global, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-001"),
        "Expected COP-001 from empty copilot-instructions.md fixture"
    );

    // COP-002: Invalid YAML in bad-frontmatter
    let bad_frontmatter =
        copilot_invalid_dir.join(".github/instructions/bad-frontmatter.instructions.md");
    let diagnostics = expect_success(validate_file(&bad_frontmatter, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-002"),
        "Expected COP-002 from bad-frontmatter.instructions.md fixture"
    );

    // COP-003: Invalid glob in bad-glob
    let bad_glob = copilot_invalid_dir.join(".github/instructions/bad-glob.instructions.md");
    let diagnostics = expect_success(validate_file(&bad_glob, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-003"),
        "Expected COP-003 from bad-glob.instructions.md fixture"
    );

    // COP-004: Unknown keys in unknown-keys
    let unknown_keys =
        copilot_invalid_dir.join(".github/instructions/unknown-keys.instructions.md");
    let diagnostics = expect_success(validate_file(&unknown_keys, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-004"),
        "Expected COP-004 from unknown-keys.instructions.md fixture"
    );

    // COP-005: Invalid excludeAgent value
    let bad_exclude_agent =
        copilot_invalid_dir.join(".github/instructions/bad-exclude-agent.instructions.md");
    let diagnostics = expect_success(validate_file(&bad_exclude_agent, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-005"),
        "Expected COP-005 from bad-exclude-agent.instructions.md fixture"
    );

    // COP-007: Custom agent missing description
    let missing_description =
        copilot_invalid_dir.join(".github/agents/missing-description.agent.md");
    let diagnostics = expect_success(validate_file(&missing_description, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-007"),
        "Expected COP-007 from missing-description.agent.md fixture"
    );

    // COP-008: Unknown custom-agent field
    let unknown_agent_field = copilot_invalid_dir.join(".github/agents/unknown-field.agent.md");
    let diagnostics = expect_success(validate_file(&unknown_agent_field, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-008"),
        "Expected COP-008 from unknown-field.agent.md fixture"
    );

    // COP-009: Invalid custom-agent target
    let invalid_target = copilot_invalid_dir.join(".github/agents/invalid-target.agent.md");
    let diagnostics = expect_success(validate_file(&invalid_target, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-009"),
        "Expected COP-009 from invalid-target.agent.md fixture"
    );

    // COP-010: Invalid infer type
    let invalid_infer = copilot_invalid_dir.join(".github/agents/invalid-infer-type.agent.md");
    let diagnostics = expect_success(validate_file(&invalid_infer, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-010"),
        "Expected COP-010 from invalid-infer-type.agent.md fixture"
    );

    let invalid_infer_null = copilot_invalid_dir.join(".github/agents/invalid-infer-null.agent.md");
    let diagnostics = expect_success(validate_file(&invalid_infer_null, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-010"),
        "Expected COP-010 from invalid-infer-null.agent.md fixture"
    );

    // COP-012: Unsupported GitHub.com fields
    let unsupported_fields = copilot_invalid_dir.join(".github/agents/unsupported-fields.agent.md");
    let diagnostics = expect_success(validate_file(&unsupported_fields, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-012"),
        "Expected COP-012 from unsupported-fields.agent.md fixture"
    );

    // COP-013: Empty prompt body
    let empty_prompt = copilot_invalid_dir.join(".github/prompts/empty.prompt.md");
    let diagnostics = expect_success(validate_file(&empty_prompt, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-013"),
        "Expected COP-013 from empty.prompt.md fixture"
    );

    // COP-014: Unknown prompt field
    let unknown_prompt_field = copilot_invalid_dir.join(".github/prompts/unknown-field.prompt.md");
    let diagnostics = expect_success(validate_file(&unknown_prompt_field, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-014"),
        "Expected COP-014 from unknown-field.prompt.md fixture"
    );

    // COP-015: Invalid prompt agent mode
    let invalid_prompt_agent = copilot_invalid_dir.join(".github/prompts/invalid-agent.prompt.md");
    let diagnostics = expect_success(validate_file(&invalid_prompt_agent, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-015"),
        "Expected COP-015 from invalid-agent.prompt.md fixture"
    );

    // COP-017: Hooks schema violations
    let invalid_hooks = copilot_invalid_dir.join(".github/hooks/hooks.json");
    let diagnostics = expect_success(validate_file(&invalid_hooks, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-017"),
        "Expected COP-017 from hooks.json fixture"
    );

    // COP-018: Missing jobs.copilot-setup-steps in workflow
    let invalid_setup_workflow =
        copilot_invalid_dir.join(".github/workflows/copilot-setup-steps.yml");
    let diagnostics = expect_success(validate_file(&invalid_setup_workflow, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-018"),
        "Expected COP-018 from copilot-setup-steps.yml fixture"
    );
}

#[test]
fn test_validate_copilot_006_too_long() {
    let fixtures_dir = get_fixtures_dir();
    let copilot_too_long_dir = fixtures_dir.join("copilot-too-long");
    let config = LintConfig::default();

    let long_global = copilot_too_long_dir.join(".github/copilot-instructions.md");
    let diagnostics = expect_success(validate_file(&long_global, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-006"),
        "Expected COP-006 from copilot-too-long fixture, got: {:?}",
        diagnostics.iter().map(|d| &d.rule).collect::<Vec<_>>()
    );

    let long_agent = copilot_too_long_dir.join(".github/agents/too-long.agent.md");
    let diagnostics = expect_success(validate_file(&long_agent, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "COP-011"),
        "Expected COP-011 from too-long.agent.md fixture, got: {:?}",
        diagnostics.iter().map(|d| &d.rule).collect::<Vec<_>>()
    );
}

#[test]
fn test_validate_copilot_file_empty() {
    // Test validate_file directly (not validate_project which skips hidden dirs)
    let temp = tempfile::TempDir::new().unwrap();
    let github_dir = temp.path().join(".github");
    std::fs::create_dir_all(&github_dir).unwrap();
    let file_path = github_dir.join("copilot-instructions.md");
    std::fs::write(&file_path, "").unwrap();

    let config = LintConfig::default();
    let diagnostics = expect_success(validate_file(&file_path, &config).unwrap());

    let cop_001: Vec<_> = diagnostics.iter().filter(|d| d.rule == "COP-001").collect();
    assert_eq!(cop_001.len(), 1, "Expected COP-001 for empty file");
}

#[test]
fn test_validate_copilot_scoped_missing_frontmatter() {
    // Test validate_file directly
    let temp = tempfile::TempDir::new().unwrap();
    let instructions_dir = temp.path().join(".github").join("instructions");
    std::fs::create_dir_all(&instructions_dir).unwrap();
    let file_path = instructions_dir.join("test.instructions.md");
    std::fs::write(&file_path, "# Instructions without frontmatter").unwrap();

    let config = LintConfig::default();
    let diagnostics = expect_success(validate_file(&file_path, &config).unwrap());

    let cop_002: Vec<_> = diagnostics.iter().filter(|d| d.rule == "COP-002").collect();
    assert_eq!(cop_002.len(), 1, "Expected COP-002 for missing frontmatter");
}

#[test]
fn test_validate_copilot_valid_scoped() {
    // Test validate_file directly
    let temp = tempfile::TempDir::new().unwrap();
    let instructions_dir = temp.path().join(".github").join("instructions");
    std::fs::create_dir_all(&instructions_dir).unwrap();
    let file_path = instructions_dir.join("rust.instructions.md");
    std::fs::write(
        &file_path,
        r#"---
applyTo: "**/*.rs"
---
# Rust Instructions

Use idiomatic Rust patterns.
"#,
    )
    .unwrap();

    let config = LintConfig::default();
    let diagnostics = expect_success(validate_file(&file_path, &config).unwrap());

    let cop_errors: Vec<_> = diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("COP-") && d.level == DiagnosticLevel::Error)
        .collect();
    assert!(
        cop_errors.is_empty(),
        "Valid scoped file should have no COP errors"
    );
}

#[test]
fn test_validate_project_finds_github_hidden_dir() {
    // Test validate_project walks .github directory (not just validate_file)
    let temp = tempfile::TempDir::new().unwrap();
    let github_dir = temp.path().join(".github");
    std::fs::create_dir_all(&github_dir).unwrap();

    // Create an empty copilot-instructions.md file (should trigger COP-001)
    let file_path = github_dir.join("copilot-instructions.md");
    std::fs::write(&file_path, "").unwrap();

    let config = LintConfig::default();
    // Use validate_project (directory walk) instead of validate_file
    let result = validate_project(temp.path(), &config).unwrap();

    assert!(
        result.diagnostics.iter().any(|d| d.rule == "COP-001"),
        "validate_project should find .github/copilot-instructions.md and report COP-001. Found: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );
}

#[test]
fn test_validate_project_finds_codex_hidden_dir() {
    // Test validate_project walks .codex directory (hidden dot-directory)
    let temp = tempfile::TempDir::new().unwrap();
    let codex_dir = temp.path().join(".codex");
    std::fs::create_dir_all(&codex_dir).unwrap();

    // Create config.toml with invalid approvalMode (should trigger CDX-001)
    let file_path = codex_dir.join("config.toml");
    std::fs::write(&file_path, "approvalMode = \"yolo\"").unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    assert!(
        result.diagnostics.iter().any(|d| d.rule == "CDX-001"),
        "validate_project should find .codex/config.toml and report CDX-001. Found: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );
}

#[test]
fn test_validate_project_finds_codex_invalid_fixtures() {
    // Test validate_project on the actual codex-invalid fixture directory
    let fixtures_dir = get_fixtures_dir();
    let codex_invalid_dir = fixtures_dir.join("codex-invalid");

    let config = LintConfig::default();
    let result = validate_project(&codex_invalid_dir, &config).unwrap();

    // Should find CDX-001 and CDX-002 from .codex/config.toml
    assert!(
        result.diagnostics.iter().any(|d| d.rule == "CDX-001"),
        "Should report CDX-001 from .codex/config.toml. Rules found: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );
    assert!(
        result.diagnostics.iter().any(|d| d.rule == "CDX-002"),
        "Should report CDX-002 from .codex/config.toml. Rules found: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );
    // Should find CDX-003 from AGENTS.override.md
    assert!(
        result.diagnostics.iter().any(|d| d.rule == "CDX-003"),
        "Should report CDX-003 from AGENTS.override.md. Rules found: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );
}

#[test]
fn test_validate_project_finds_copilot_invalid_fixtures() {
    // Test validate_project on the actual fixture directory
    let fixtures_dir = get_fixtures_dir();
    let copilot_invalid_dir = fixtures_dir.join("copilot-invalid");

    let config = LintConfig::default();
    let result = validate_project(&copilot_invalid_dir, &config).unwrap();

    // Should find COP-001 from empty copilot-instructions.md
    assert!(
        result.diagnostics.iter().any(|d| d.rule == "COP-001"),
        "validate_project should find COP-001 in copilot-invalid fixtures. Found rules: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );

    // Should find COP-002 from bad-frontmatter.instructions.md
    assert!(
        result.diagnostics.iter().any(|d| d.rule == "COP-002"),
        "validate_project should find COP-002 in copilot-invalid fixtures. Found rules: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );
}

// ===== Cursor Project Rules Validation Integration Tests =====

#[test]
fn test_detect_cursor_rule() {
    assert_eq!(
        detect_file_type(Path::new(".cursor/rules/typescript.mdc")),
        FileType::CursorRule
    );
    assert_eq!(
        detect_file_type(Path::new(".cursor/rules/typescript.md")),
        FileType::CursorRule
    );
    assert_eq!(
        detect_file_type(Path::new("project/.cursor/rules/rust.mdc")),
        FileType::CursorRule
    );
    assert_eq!(
        detect_file_type(Path::new("project/.cursor/rules/frontend/rust.md")),
        FileType::CursorRule
    );
}

#[test]
fn test_detect_cursor_hooks_agent_environment() {
    assert_eq!(
        detect_file_type(Path::new(".cursor/hooks.json")),
        FileType::CursorHooks
    );
    assert_eq!(
        detect_file_type(Path::new(".cursor/environment.json")),
        FileType::CursorEnvironment
    );
    assert_eq!(
        detect_file_type(Path::new(".cursor/agents/reviewer.md")),
        FileType::CursorAgent
    );
    assert_eq!(
        detect_file_type(Path::new("project/.cursor/agents/nested/reviewer.md")),
        FileType::CursorAgent
    );
    assert_eq!(
        detect_file_type(Path::new("project/.cursor/agents/AGENTS.md")),
        FileType::CursorAgent
    );
    assert_eq!(
        detect_file_type(Path::new("project/.cursor/agents/CLAUDE.md")),
        FileType::CursorAgent
    );
}

#[test]
fn test_detect_cursor_legacy() {
    assert_eq!(
        detect_file_type(Path::new(".cursorrules")),
        FileType::CursorRulesLegacy
    );
    assert_eq!(
        detect_file_type(Path::new("project/.cursorrules")),
        FileType::CursorRulesLegacy
    );
    // Also test .cursorrules.md variant
    assert_eq!(
        detect_file_type(Path::new(".cursorrules.md")),
        FileType::CursorRulesLegacy
    );
    assert_eq!(
        detect_file_type(Path::new("project/.cursorrules.md")),
        FileType::CursorRulesLegacy
    );
}

#[test]
fn test_cursor_not_detected_outside_cursor_dir() {
    // .md/.mdc files outside .cursor/rules/ should not be detected as CursorRule
    assert_ne!(
        detect_file_type(Path::new("rules/typescript.mdc")),
        FileType::CursorRule
    );
    assert_ne!(
        detect_file_type(Path::new("rules/typescript.md")),
        FileType::CursorRule
    );
    assert_ne!(
        detect_file_type(Path::new(".cursor/typescript.mdc")),
        FileType::CursorRule
    );
    assert_ne!(
        detect_file_type(Path::new(".cursor/notes.md")),
        FileType::CursorRule
    );
}

#[test]
fn test_validators_for_cursor() {
    let registry = ValidatorRegistry::with_defaults();

    let cursor_validators = registry.validators_for(FileType::CursorRule);
    assert_eq!(cursor_validators.len(), 3); // cursor + prompt + claude_md

    let hooks_validators = registry.validators_for(FileType::CursorHooks);
    assert_eq!(hooks_validators.len(), 1); // cursor
    assert_eq!(hooks_validators[0].name(), "CursorValidator");

    let agent_validators = registry.validators_for(FileType::CursorAgent);
    assert_eq!(agent_validators.len(), 1); // cursor
    assert_eq!(agent_validators[0].name(), "CursorValidator");

    let environment_validators = registry.validators_for(FileType::CursorEnvironment);
    assert_eq!(environment_validators.len(), 1); // cursor
    assert_eq!(environment_validators[0].name(), "CursorValidator");

    let legacy_validators = registry.validators_for(FileType::CursorRulesLegacy);
    assert_eq!(legacy_validators.len(), 3); // cursor + prompt + claude_md
}

#[test]
fn test_validate_cursor_fixtures() {
    // Use validate_file directly since .cursor is a hidden directory
    let fixtures_dir = get_fixtures_dir();
    let cursor_dir = fixtures_dir.join("cursor");

    let config = LintConfig::default();

    // Validate valid .mdc file
    let valid_path = cursor_dir.join(".cursor/rules/valid.mdc");
    let diagnostics = expect_success(validate_file(&valid_path, &config).unwrap());
    let cur_errors: Vec<_> = diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("CUR-") && d.level == DiagnosticLevel::Error)
        .collect();
    assert!(
        cur_errors.is_empty(),
        "Valid .mdc file should have no CUR errors, got: {:?}",
        cur_errors
    );

    // Validate .mdc file with multiple globs
    let multiple_globs_path = cursor_dir.join(".cursor/rules/multiple-globs.mdc");
    let diagnostics = expect_success(validate_file(&multiple_globs_path, &config).unwrap());
    let cur_errors: Vec<_> = diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("CUR-") && d.level == DiagnosticLevel::Error)
        .collect();
    assert!(
        cur_errors.is_empty(),
        "Valid .mdc file with multiple globs should have no CUR errors, got: {:?}",
        cur_errors
    );

    let hooks_path = cursor_dir.join(".cursor/hooks.json");
    let diagnostics = expect_success(validate_file(&hooks_path, &config).unwrap());
    assert!(
        diagnostics.iter().all(|d| !matches!(
            d.rule.as_str(),
            "CUR-010" | "CUR-011" | "CUR-012" | "CUR-013"
        )),
        "Valid hooks fixture should have no CUR-010..CUR-013 diagnostics, got: {:?}",
        diagnostics
            .iter()
            .map(|d| (&d.rule, &d.message))
            .collect::<Vec<_>>()
    );

    let agent_path = cursor_dir.join(".cursor/agents/reviewer.md");
    let diagnostics = expect_success(validate_file(&agent_path, &config).unwrap());
    assert!(
        diagnostics
            .iter()
            .all(|d| !matches!(d.rule.as_str(), "CUR-014" | "CUR-015")),
        "Valid agent fixture should have no CUR-014/CUR-015 diagnostics, got: {:?}",
        diagnostics
            .iter()
            .map(|d| (&d.rule, &d.message))
            .collect::<Vec<_>>()
    );

    let environment_path = cursor_dir.join(".cursor/environment.json");
    let diagnostics = expect_success(validate_file(&environment_path, &config).unwrap());
    assert!(
        diagnostics.iter().all(|d| d.rule != "CUR-016"),
        "Valid environment fixture should have no CUR-016 diagnostics, got: {:?}",
        diagnostics
            .iter()
            .map(|d| (&d.rule, &d.message))
            .collect::<Vec<_>>()
    );
}

#[test]
fn test_validate_cursor_invalid_fixtures() {
    // Use validate_file directly since .cursor is a hidden directory
    let fixtures_dir = get_fixtures_dir();
    let cursor_invalid_dir = fixtures_dir.join("cursor-invalid");
    let config = LintConfig::default();

    // CUR-001: Empty .mdc file
    let empty_mdc = cursor_invalid_dir.join(".cursor/rules/empty.mdc");
    let diagnostics = expect_success(validate_file(&empty_mdc, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "CUR-001"),
        "Expected CUR-001 from empty.mdc fixture"
    );

    // CUR-002: Missing frontmatter
    let no_frontmatter = cursor_invalid_dir.join(".cursor/rules/no-frontmatter.mdc");
    let diagnostics = expect_success(validate_file(&no_frontmatter, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "CUR-002"),
        "Expected CUR-002 from no-frontmatter.mdc fixture"
    );

    // CUR-003: Invalid YAML
    let bad_yaml = cursor_invalid_dir.join(".cursor/rules/bad-yaml.mdc");
    let diagnostics = expect_success(validate_file(&bad_yaml, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "CUR-003"),
        "Expected CUR-003 from bad-yaml.mdc fixture"
    );

    // CUR-004: Invalid glob pattern
    let bad_glob = cursor_invalid_dir.join(".cursor/rules/bad-glob.mdc");
    let diagnostics = expect_success(validate_file(&bad_glob, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "CUR-004"),
        "Expected CUR-004 from bad-glob.mdc fixture"
    );

    // CUR-005: Unknown keys
    let unknown_keys = cursor_invalid_dir.join(".cursor/rules/unknown-keys.mdc");
    let diagnostics = expect_success(validate_file(&unknown_keys, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "CUR-005"),
        "Expected CUR-005 from unknown-keys.mdc fixture"
    );

    // CUR-010: Invalid hooks schema
    let cur_010_hooks = cursor_invalid_dir.join("hooks-cur010/.cursor/hooks.json");
    let diagnostics = expect_success(validate_file(&cur_010_hooks, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "CUR-010"),
        "Expected CUR-010 from hooks-cur010 fixture"
    );

    // CUR-011/CUR-012/CUR-013 from malformed hook entry
    let cur_011_to_013 = cursor_invalid_dir.join("hooks-cur011-013/.cursor/hooks.json");
    let diagnostics = expect_success(validate_file(&cur_011_to_013, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "CUR-011"),
        "Expected CUR-011 from hooks-cur011-013 fixture"
    );
    assert!(
        diagnostics.iter().any(|d| d.rule == "CUR-012"),
        "Expected CUR-012 from hooks-cur011-013 fixture"
    );
    assert!(
        diagnostics.iter().any(|d| d.rule == "CUR-013"),
        "Expected CUR-013 from hooks-cur011-013 fixture"
    );

    // CUR-014: Invalid Cursor agent frontmatter
    let cur_014_agent = cursor_invalid_dir.join("agent-cur014/.cursor/agents/reviewer.md");
    let diagnostics = expect_success(validate_file(&cur_014_agent, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "CUR-014"),
        "Expected CUR-014 from agent-cur014 fixture"
    );

    // CUR-015: Empty Cursor agent body
    let cur_015_agent = cursor_invalid_dir.join("agent-cur015/.cursor/agents/reviewer.md");
    let diagnostics = expect_success(validate_file(&cur_015_agent, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "CUR-015"),
        "Expected CUR-015 from agent-cur015 fixture"
    );

    // CUR-016: Invalid environment schema
    let cur_016_environment =
        cursor_invalid_dir.join("environment-cur016/.cursor/environment.json");
    let diagnostics = expect_success(validate_file(&cur_016_environment, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "CUR-016"),
        "Expected CUR-016 from environment-cur016 fixture"
    );
}

#[test]
fn test_validate_cursor_legacy_fixture() {
    let fixtures_dir = get_fixtures_dir();
    let legacy_path = fixtures_dir.join("cursor-legacy/.cursorrules");
    let config = LintConfig::default();

    let diagnostics = expect_success(validate_file(&legacy_path, &config).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "CUR-006"),
        "Expected CUR-006 from .cursorrules fixture"
    );
}

#[test]
fn test_validate_cursor_file_empty() {
    let temp = tempfile::TempDir::new().unwrap();
    let cursor_dir = temp.path().join(".cursor").join("rules");
    std::fs::create_dir_all(&cursor_dir).unwrap();
    let file_path = cursor_dir.join("empty.mdc");
    std::fs::write(&file_path, "").unwrap();

    let config = LintConfig::default();
    let diagnostics = expect_success(validate_file(&file_path, &config).unwrap());

    let cur_001: Vec<_> = diagnostics.iter().filter(|d| d.rule == "CUR-001").collect();
    assert_eq!(cur_001.len(), 1, "Expected CUR-001 for empty file");
}

#[test]
fn test_validate_cursor_mdc_missing_frontmatter() {
    let temp = tempfile::TempDir::new().unwrap();
    let cursor_dir = temp.path().join(".cursor").join("rules");
    std::fs::create_dir_all(&cursor_dir).unwrap();
    let file_path = cursor_dir.join("test.mdc");
    std::fs::write(&file_path, "# Rules without frontmatter").unwrap();

    let config = LintConfig::default();
    let diagnostics = expect_success(validate_file(&file_path, &config).unwrap());

    let cur_002: Vec<_> = diagnostics.iter().filter(|d| d.rule == "CUR-002").collect();
    assert_eq!(cur_002.len(), 1, "Expected CUR-002 for missing frontmatter");
}

#[test]
fn test_validate_cursor_valid_mdc() {
    let temp = tempfile::TempDir::new().unwrap();
    let cursor_dir = temp.path().join(".cursor").join("rules");
    std::fs::create_dir_all(&cursor_dir).unwrap();
    let file_path = cursor_dir.join("rust.mdc");
    std::fs::write(
        &file_path,
        r#"---
description: Rust rules
globs: "**/*.rs"
---
# Rust Rules

Use idiomatic Rust patterns.
"#,
    )
    .unwrap();

    let config = LintConfig::default();
    let diagnostics = expect_success(validate_file(&file_path, &config).unwrap());

    let cur_errors: Vec<_> = diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("CUR-") && d.level == DiagnosticLevel::Error)
        .collect();
    assert!(
        cur_errors.is_empty(),
        "Valid .mdc file should have no CUR errors"
    );
}

#[test]
fn test_validate_project_finds_cursor_hidden_dir() {
    // Test validate_project walks .cursor directory
    let temp = tempfile::TempDir::new().unwrap();
    let cursor_dir = temp.path().join(".cursor").join("rules");
    std::fs::create_dir_all(&cursor_dir).unwrap();

    // Create an empty .mdc file (should trigger CUR-001)
    let file_path = cursor_dir.join("empty.mdc");
    std::fs::write(&file_path, "").unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    assert!(
        result.diagnostics.iter().any(|d| d.rule == "CUR-001"),
        "validate_project should find .cursor/rules/empty.mdc and report CUR-001. Found: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );
}

#[test]
fn test_validate_project_finds_cursor_invalid_fixtures() {
    // Test validate_project on the actual fixture directory
    let fixtures_dir = get_fixtures_dir();
    let cursor_invalid_dir = fixtures_dir.join("cursor-invalid");

    let config = LintConfig::default();
    let result = validate_project(&cursor_invalid_dir, &config).unwrap();

    // Should find CUR-001 from empty.mdc
    assert!(
        result.diagnostics.iter().any(|d| d.rule == "CUR-001"),
        "validate_project should find CUR-001 in cursor-invalid fixtures. Found rules: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );

    // Should find CUR-002 from no-frontmatter.mdc
    assert!(
        result.diagnostics.iter().any(|d| d.rule == "CUR-002"),
        "validate_project should find CUR-002 in cursor-invalid fixtures. Found rules: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );
}

// ===== PE Rules Dispatch Integration Tests =====

#[test]
fn test_pe_rules_dispatched() {
    // Verify PE-* rules are dispatched when validating ClaudeMd file type.
    // Per SPEC.md, PE rules apply to CLAUDE.md and AGENTS.md only (not SKILL.md).
    let fixtures_dir = get_fixtures_dir().join("prompt");
    let config = LintConfig::default();
    let registry = ValidatorRegistry::with_defaults();
    let temp = tempfile::TempDir::new().unwrap();
    let claude_path = temp.path().join("CLAUDE.md");

    // Test cases: (fixture_file, expected_rule)
    let test_cases = [
        ("pe-001-critical-in-middle.md", "PE-001"),
        ("pe-002-cot-on-simple.md", "PE-002"),
        ("pe-003-weak-language.md", "PE-003"),
        ("pe-004-ambiguous.md", "PE-004"),
    ];

    for (fixture, expected_rule) in test_cases {
        let content = std::fs::read_to_string(fixtures_dir.join(fixture))
            .unwrap_or_else(|_| panic!("Failed to read fixture: {}", fixture));
        std::fs::write(&claude_path, &content).unwrap();
        let diagnostics =
            expect_success(validate_file_with_registry(&claude_path, &config, &registry).unwrap());
        assert!(
            diagnostics.iter().any(|d| d.rule == expected_rule),
            "Expected {} from {} content",
            expected_rule,
            fixture
        );
    }

    // Also verify PE rules dispatch on AGENTS.md file type
    let agents_path = temp.path().join("AGENTS.md");
    let pe_003_content =
        std::fs::read_to_string(fixtures_dir.join("pe-003-weak-language.md")).unwrap();
    std::fs::write(&agents_path, &pe_003_content).unwrap();
    let diagnostics =
        expect_success(validate_file_with_registry(&agents_path, &config, &registry).unwrap());
    assert!(
        diagnostics.iter().any(|d| d.rule == "PE-003"),
        "Expected PE-003 from AGENTS.md with weak language content"
    );
}

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

    // Create a structure that should be partially excluded
    let target_dir = temp.path().join("target");
    std::fs::create_dir_all(&target_dir).unwrap();
    std::fs::write(
        target_dir.join("SKILL.md"),
        "---\nname: build-artifact\ndescription: Should be excluded\n---\nBody",
    )
    .unwrap();

    // Create a file that should NOT be excluded
    std::fs::write(
        temp.path().join("SKILL.md"),
        "---\nname: valid-skill\ndescription: Should be validated\n---\nBody",
    )
    .unwrap();

    let mut config = LintConfig::default();
    config.set_exclude(vec!["target/**".to_string()]);

    // Use absolute path (canonicalize returns absolute path)
    let abs_path = std::fs::canonicalize(temp.path()).unwrap();
    let result = validate_project(&abs_path, &config).unwrap();

    // Should NOT have diagnostics from target/SKILL.md (excluded)
    let target_diags: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.file.to_string_lossy().contains("target"))
        .collect();
    assert!(
        target_diags.is_empty(),
        "Files in target/ should be excluded when using absolute path, got: {:?}",
        target_diags
    );
}

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

    // Create a structure that should be partially excluded
    let node_modules = temp.path().join("node_modules");
    std::fs::create_dir_all(&node_modules).unwrap();
    std::fs::write(
        node_modules.join("SKILL.md"),
        "---\nname: npm-artifact\ndescription: Should be excluded\n---\nBody",
    )
    .unwrap();

    // Create a file that should NOT be excluded
    std::fs::write(
        temp.path().join("AGENTS.md"),
        "# Project\n\nThis should be validated.",
    )
    .unwrap();

    let mut config = LintConfig::default();
    config.set_exclude(vec!["node_modules/**".to_string()]);

    // Use temp.path() directly to validate exclude pattern handling
    let result = validate_project(temp.path(), &config).unwrap();

    // Should NOT have diagnostics from node_modules/
    let nm_diags: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.file.to_string_lossy().contains("node_modules"))
        .collect();
    assert!(
        nm_diags.is_empty(),
        "Files in node_modules/ should be excluded, got: {:?}",
        nm_diags
    );
}

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

    // Create deeply nested target directory
    let deep_target = temp.path().join("subproject").join("target").join("debug");
    std::fs::create_dir_all(&deep_target).unwrap();
    std::fs::write(
        deep_target.join("SKILL.md"),
        "---\nname: deep-artifact\ndescription: Deep exclude test\n---\nBody",
    )
    .unwrap();

    let mut config = LintConfig::default();
    // Use ** prefix to match at any level
    config.set_exclude(vec!["**/target/**".to_string()]);

    let abs_path = std::fs::canonicalize(temp.path()).unwrap();
    let result = validate_project(&abs_path, &config).unwrap();

    let target_diags: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.file.to_string_lossy().contains("target"))
        .collect();
    assert!(
        target_diags.is_empty(),
        "Deeply nested target/ files should be excluded, got: {:?}",
        target_diags
    );
}

// ===== ValidationResult files_checked Tests =====

#[test]
fn test_files_checked_with_no_diagnostics() {
    // Test that files_checked is accurate even when there are no diagnostics
    let temp = tempfile::TempDir::new().unwrap();

    // Create valid skill files that produce no diagnostics
    let skill_dir = temp.path().join("skills").join("code-review");
    std::fs::create_dir_all(&skill_dir).unwrap();
    std::fs::write(
        skill_dir.join("SKILL.md"),
        "---\nname: code-review\ndescription: Use when reviewing code\n---\nBody",
    )
    .unwrap();

    // Create another valid skill
    let skill_dir2 = temp.path().join("skills").join("test-runner");
    std::fs::create_dir_all(&skill_dir2).unwrap();
    std::fs::write(
        skill_dir2.join("SKILL.md"),
        "---\nname: test-runner\ndescription: Use when running tests\n---\nBody",
    )
    .unwrap();

    // Disable VER-001 since we're testing for zero diagnostics on valid files
    let mut config = LintConfig::default();
    config.rules_mut().disabled_rules = vec!["VER-001".to_string()];
    let result = validate_project(temp.path(), &config).unwrap();

    // Should have counted exactly the two valid skill files
    assert_eq!(
        result.files_checked, 2,
        "files_checked should count exactly the validated skill files, got {}",
        result.files_checked
    );
    assert!(
        result.diagnostics.is_empty(),
        "Valid skill files should have no diagnostics"
    );
}

#[test]
fn test_files_checked_excludes_unknown_file_types() {
    // Test that files_checked only counts recognized file types
    let temp = tempfile::TempDir::new().unwrap();

    // Create files of unknown type
    std::fs::write(temp.path().join("main.rs"), "fn main() {}").unwrap();
    std::fs::write(temp.path().join("package.json"), "{}").unwrap();

    // Create one recognized file
    std::fs::write(
        temp.path().join("SKILL.md"),
        "---\nname: code-review\ndescription: Use when reviewing code\n---\nBody",
    )
    .unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    // Should only count the SKILL.md file, not .rs or package.json
    assert_eq!(
        result.files_checked, 1,
        "files_checked should only count recognized file types"
    );
}

// ===== Concurrent Access Tests =====

#[test]
fn test_validator_registry_concurrent_access() {
    use std::sync::Arc;
    use std::thread;

    let registry = Arc::new(ValidatorRegistry::with_defaults());

    let handles: Vec<_> = (0..10)
        .map(|_| {
            let registry = Arc::clone(&registry);
            thread::spawn(move || {
                // Multiple threads accessing validators_for concurrently
                for _ in 0..100 {
                    let _ = registry.validators_for(FileType::Skill);
                    let _ = registry.validators_for(FileType::ClaudeMd);
                    let _ = registry.validators_for(FileType::Mcp);
                }
            })
        })
        .collect();

    for handle in handles {
        handle.join().expect("Thread panicked");
    }
}

#[test]
fn test_concurrent_file_validation() {
    use std::sync::Arc;
    use std::thread;
    let temp = tempfile::TempDir::new().unwrap();

    // Create multiple files
    for i in 0..5 {
        let skill_dir = temp.path().join(format!("skill-{}", i));
        std::fs::create_dir_all(&skill_dir).unwrap();
        std::fs::write(
            skill_dir.join("SKILL.md"),
            format!(
                "---\nname: skill-{}\ndescription: Skill number {}\n---\nBody",
                i, i
            ),
        )
        .unwrap();
    }

    let config = Arc::new(LintConfig::default());
    let registry = Arc::new(ValidatorRegistry::with_defaults());
    let temp_path = temp.path().to_path_buf();

    let handles: Vec<_> = (0..5)
        .map(|i| {
            let config = Arc::clone(&config);
            let registry = Arc::clone(&registry);
            let path = temp_path.join(format!("skill-{}", i)).join("SKILL.md");
            thread::spawn(move || validate_file_with_registry(&path, &config, &registry))
        })
        .collect();

    for handle in handles {
        let result = handle.join().expect("Thread panicked");
        assert!(result.is_ok(), "Concurrent validation should succeed");
    }
}

#[test]
fn test_concurrent_project_validation() {
    use std::sync::Arc;
    use std::thread;
    let temp = tempfile::TempDir::new().unwrap();

    // Create a project structure
    std::fs::write(
        temp.path().join("SKILL.md"),
        "---\nname: test-skill\ndescription: Test description\n---\nBody",
    )
    .unwrap();
    std::fs::write(temp.path().join("CLAUDE.md"), "# Project memory").unwrap();

    let config = Arc::new(LintConfig::default());
    let temp_path = temp.path().to_path_buf();

    // Run multiple validate_project calls concurrently
    let handles: Vec<_> = (0..5)
        .map(|_| {
            let config = Arc::clone(&config);
            let path = temp_path.clone();
            thread::spawn(move || validate_project(&path, &config))
        })
        .collect();

    let mut results: Vec<_> = handles
        .into_iter()
        .map(|h| {
            h.join()
                .expect("Thread panicked")
                .expect("Validation failed")
        })
        .collect();

    // All results should be identical
    let first = results.pop().unwrap();
    for result in results {
        assert_eq!(
            first.diagnostics.len(),
            result.diagnostics.len(),
            "Concurrent validations should produce identical results"
        );
    }
}

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

    let temp = tempfile::TempDir::new().unwrap();
    std::fs::write(temp.path().join("notes.md"), "See @missing.md").unwrap();

    // Pre-poison the shared cache before validation starts
    let cache: agnix_core::__internal::ImportCache = Arc::new(RwLock::new(HashMap::new()));
    let cache_for_poison = cache.clone();
    let _ = std::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 result = validate_project(temp.path(), &config);
    assert!(
        result.is_ok(),
        "Project validation should continue with a poisoned import cache lock"
    );
    let outcome = result.unwrap();
    assert!(
        outcome
            .diagnostics
            .iter()
            .any(|d| d.rule == "REF-001" && d.message.contains("@missing.md")),
        "Imports validation should still run and report missing imports after cache poisoning"
    );
    assert!(
        outcome
            .diagnostics
            .iter()
            .any(|d| d.rule == "lint::cache-poison"),
        "Expected lint::cache-poison warning to surface through validation pipeline"
    );
}

// ===== Security: File Count Limit Tests =====

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

    // Create 15 markdown files
    for i in 0..15 {
        std::fs::write(temp.path().join(format!("file{}.md", i)), "# Content").unwrap();
    }

    // Set a limit of 10 files
    let mut config = LintConfig::default();
    config.set_max_files_to_validate(Some(10));

    let result = validate_project(temp.path(), &config);

    // Should return TooManyFiles error
    assert!(result.is_err(), "Should error when file limit exceeded");
    match result.unwrap_err() {
        CoreError::Validation(ValidationError::TooManyFiles { count, limit }) => {
            assert!(count > 10, "Count should exceed limit");
            assert_eq!(limit, 10);
        }
        e => panic!("Expected TooManyFiles error, got: {:?}", e),
    }
}

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

    // Create 5 markdown files
    for i in 0..5 {
        std::fs::write(temp.path().join(format!("file{}.md", i)), "# Content").unwrap();
    }

    // Set a limit of 10 files
    let mut config = LintConfig::default();
    config.set_max_files_to_validate(Some(10));

    let result = validate_project(temp.path(), &config);

    // Should succeed
    assert!(
        result.is_ok(),
        "Should succeed when under file limit: {:?}",
        result
    );
}

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

    // Create 15 markdown files
    for i in 0..15 {
        std::fs::write(temp.path().join(format!("file{}.md", i)), "# Content").unwrap();
    }

    // Disable the limit
    let mut config = LintConfig::default();
    config.set_max_files_to_validate(None);

    let result = validate_project(temp.path(), &config);

    // Should succeed even with many files
    assert!(
        result.is_ok(),
        "Should succeed when file limit disabled: {:?}",
        result
    );
}

#[test]
fn test_default_file_count_limit() {
    let config = LintConfig::default();
    assert_eq!(
        config.max_files_to_validate(),
        Some(config::DEFAULT_MAX_FILES)
    );
    assert_eq!(config::DEFAULT_MAX_FILES, 10_000);
}

#[test]
fn test_file_count_concurrent_validation() {
    // Test that file counting is thread-safe during parallel validation
    let temp = tempfile::TempDir::new().unwrap();

    // Create enough files to trigger parallel validation (rayon will use multiple threads)
    for i in 0..20 {
        std::fs::write(temp.path().join(format!("file{}.md", i)), "# Content").unwrap();
    }

    // Set a limit that allows all files
    let mut config = LintConfig::default();
    config.set_max_files_to_validate(Some(25));

    let result = validate_project(temp.path(), &config);

    // Should succeed - no race condition in file counting
    assert!(
        result.is_ok(),
        "Concurrent validation should handle file counting correctly"
    );

    // Verify the count is accurate
    let validation_result = result.unwrap();
    assert_eq!(
        validation_result.files_checked, 20,
        "Should count all validated files"
    );
}

// ===== Performance Tests =====

#[test]
#[ignore] // Run with: cargo test --release -- --ignored test_validation_scales_to_10k_files
fn test_validation_scales_to_10k_files() {
    // This test verifies that validation can handle 10,000 files (the default limit)
    // in reasonable time. It's marked #[ignore] because it's slow.
    use std::time::Instant;

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

    // Create 10,000 small markdown files
    for i in 0..10_000 {
        std::fs::write(
            temp.path().join(format!("file{:05}.md", i)),
            format!("# File {}\n\nContent here.", i),
        )
        .unwrap();
    }

    let config = LintConfig::default();
    let start = Instant::now();
    let result = validate_project(temp.path(), &config);
    let duration = start.elapsed();

    // Should succeed
    assert!(
        result.is_ok(),
        "Should handle 10,000 files: {:?}",
        result.err()
    );

    // Should complete in reasonable time (adjust threshold based on CI performance)
    // On typical hardware: ~2-10 seconds for 10k files
    assert!(
        duration.as_secs() < 60,
        "10,000 file validation took too long: {:?}",
        duration
    );

    let validation_result = result.unwrap();
    assert_eq!(
        validation_result.files_checked, 10_000,
        "Should have checked all 10,000 files"
    );

    eprintln!(
        "Performance: Validated 10,000 files in {:?} ({:.0} files/sec)",
        duration,
        10_000.0 / duration.as_secs_f64()
    );
}

// =========================================================================
// resolve_file_type tests
// =========================================================================

#[test]
fn test_resolve_file_type_no_config_falls_through() {
    let config = LintConfig::default();
    // No files config patterns -> same as detect_file_type
    assert_eq!(
        resolve_file_type(Path::new("CLAUDE.md"), &config),
        FileType::ClaudeMd
    );
    assert_eq!(
        resolve_file_type(Path::new("main.rs"), &config),
        FileType::Unknown
    );
    assert_eq!(
        resolve_file_type(Path::new("notes/setup.md"), &config),
        FileType::GenericMarkdown
    );
}

#[test]
fn test_resolve_file_type_include_as_memory() {
    let mut config = LintConfig::default();
    config.files_mut().include_as_memory = vec!["docs/ai-rules/*.md".to_string()];
    config.set_root_dir(PathBuf::from("/project"));

    // File matching the pattern -> ClaudeMd
    assert_eq!(
        resolve_file_type(Path::new("/project/docs/ai-rules/coding.md"), &config),
        FileType::ClaudeMd
    );

    // File NOT matching -> falls through to detect_file_type
    assert_eq!(
        resolve_file_type(Path::new("/project/docs/other/coding.md"), &config),
        FileType::Unknown // docs/ is a documentation directory
    );
}

#[test]
fn test_resolve_file_type_include_as_generic() {
    let mut config = LintConfig::default();
    config.files_mut().include_as_generic = vec!["internal/*.md".to_string()];
    config.set_root_dir(PathBuf::from("/project"));

    assert_eq!(
        resolve_file_type(Path::new("/project/internal/notes.md"), &config),
        FileType::GenericMarkdown
    );
}

#[test]
fn test_resolve_file_type_exclude() {
    let mut config = LintConfig::default();
    config.files_mut().exclude = vec!["generated/**".to_string()];
    config.set_root_dir(PathBuf::from("/project"));

    // CLAUDE.md in generated/ -> excluded (Unknown)
    assert_eq!(
        resolve_file_type(Path::new("/project/generated/CLAUDE.md"), &config),
        FileType::Unknown
    );

    // CLAUDE.md outside generated/ -> still ClaudeMd
    assert_eq!(
        resolve_file_type(Path::new("/project/CLAUDE.md"), &config),
        FileType::ClaudeMd
    );
}

#[test]
fn test_resolve_file_type_priority_exclude_over_include() {
    let mut config = LintConfig::default();
    config.files_mut().include_as_memory = vec!["docs/**/*.md".to_string()];
    config.files_mut().exclude = vec!["docs/drafts/**".to_string()];
    config.set_root_dir(PathBuf::from("/project"));

    // In docs/ but also in drafts/ -> exclude wins
    assert_eq!(
        resolve_file_type(Path::new("/project/docs/drafts/wip.md"), &config),
        FileType::Unknown
    );

    // In docs/ but not in drafts/ -> include_as_memory wins
    assert_eq!(
        resolve_file_type(Path::new("/project/docs/rules/coding.md"), &config),
        FileType::ClaudeMd
    );
}

#[test]
fn test_resolve_file_type_priority_memory_over_generic() {
    let mut config = LintConfig::default();
    config.files_mut().include_as_memory = vec!["rules/*.md".to_string()];
    config.files_mut().include_as_generic = vec!["rules/*.md".to_string()]; // overlapping
    config.set_root_dir(PathBuf::from("/project"));

    // When both match, memory takes priority
    assert_eq!(
        resolve_file_type(Path::new("/project/rules/coding.md"), &config),
        FileType::ClaudeMd
    );
}

#[test]
fn test_resolve_file_type_no_root_dir_uses_filename() {
    let mut config = LintConfig::default();
    config.files_mut().include_as_memory = vec!["INSTRUCTIONS.md".to_string()];
    // No root_dir set

    assert_eq!(
        resolve_file_type(Path::new("some/path/INSTRUCTIONS.md"), &config),
        FileType::ClaudeMd
    );
}

#[test]
fn test_resolve_file_type_non_matching_files_fall_through() {
    let mut config = LintConfig::default();
    config.files_mut().include_as_memory = vec!["custom/*.md".to_string()];
    config.set_root_dir(PathBuf::from("/project"));

    // Regular SKILL.md still detected normally
    assert_eq!(
        resolve_file_type(Path::new("/project/SKILL.md"), &config),
        FileType::Skill
    );

    // Regular CLAUDE.md still detected normally
    assert_eq!(
        resolve_file_type(Path::new("/project/CLAUDE.md"), &config),
        FileType::ClaudeMd
    );
}

#[test]
fn test_resolve_file_type_exclude_overrides_builtin() {
    let mut config = LintConfig::default();
    config.files_mut().exclude = vec!["vendor/CLAUDE.md".to_string()];
    config.set_root_dir(PathBuf::from("/project"));

    // CLAUDE.md in vendor/ is excluded even though it would normally be ClaudeMd
    assert_eq!(
        resolve_file_type(Path::new("/project/vendor/CLAUDE.md"), &config),
        FileType::Unknown
    );
}

#[test]
fn test_resolve_file_type_backslash_normalization() {
    let mut config = LintConfig::default();
    config.files_mut().include_as_memory = vec!["docs\\ai-rules\\*.md".to_string()];
    config.set_root_dir(PathBuf::from("/project"));

    // Backslashes in patterns are normalized to forward slashes
    assert_eq!(
        resolve_file_type(Path::new("/project/docs/ai-rules/coding.md"), &config),
        FileType::ClaudeMd
    );
}

#[test]
fn test_resolve_file_type_invalid_pattern_falls_back() {
    let mut config = LintConfig::default();
    config.files_mut().include_as_memory = vec!["[invalid".to_string()];

    // Invalid pattern should fall back to detect_file_type
    assert_eq!(
        resolve_file_type(Path::new("CLAUDE.md"), &config),
        FileType::ClaudeMd
    );
}

// =========================================================================
// Integration tests with tempdir
// =========================================================================

#[test]
fn test_validate_project_with_files_config_include() {
    let temp = tempfile::TempDir::new().unwrap();
    let root = temp.path();

    // Create a custom instruction file that would normally be GenericMarkdown.
    // Content includes "Usually" which triggers PE-004 (ambiguous terms) via
    // the PromptValidator. PromptValidator runs for ClaudeMd but NOT for
    // GenericMarkdown, proving the include_as_memory override works correctly.
    let custom_dir = root.join("custom-rules");
    std::fs::create_dir_all(&custom_dir).unwrap();
    let custom_file = custom_dir.join("coding-standards.md");
    std::fs::write(
        &custom_file,
        "# Coding Standards\n\nUsually prefer TypeScript over JavaScript.\n",
    )
    .unwrap();

    // Without config, this file would be GenericMarkdown (in non-doc dir)
    assert_eq!(detect_file_type(&custom_file), FileType::GenericMarkdown);

    // With include_as_memory config, it should be validated as ClaudeMd
    let mut config = LintConfig::default();
    config.files_mut().include_as_memory = vec!["custom-rules/*.md".to_string()];

    let result = validate_project(root, &config).unwrap();
    // Should have checked the file (it's now ClaudeMd, not just GenericMarkdown)
    assert!(result.files_checked > 0);

    // Verify that ClaudeMd-specific validators ran by checking for PE-004
    // (ambiguous instructions). The PromptValidator is registered for ClaudeMd
    // but NOT for GenericMarkdown, so PE-004 firing confirms the file was
    // routed through ClaudeMd validation.
    let pe_diags: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule.starts_with("PE-"))
        .collect();
    assert!(
        !pe_diags.is_empty(),
        "Expected PE-* diagnostics (from PromptValidator, ClaudeMd-only) but found none. \
         This means the file was not validated as ClaudeMd despite include_as_memory config. \
         All diagnostics: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| (&d.rule, &d.message))
            .collect::<Vec<_>>()
    );
}

#[test]
fn test_validate_project_with_files_config_exclude() {
    let temp = tempfile::TempDir::new().unwrap();
    let root = temp.path();

    // Create a CLAUDE.md that would normally be validated
    std::fs::write(root.join("CLAUDE.md"), "# Project\n\nInstructions here.\n").unwrap();

    // Create a CLAUDE.md in a vendor dir that should be excluded
    let vendor_dir = root.join("vendor");
    std::fs::create_dir_all(&vendor_dir).unwrap();
    std::fs::write(
        vendor_dir.join("CLAUDE.md"),
        "# Vendor instructions\n\nDo not validate this.\n",
    )
    .unwrap();

    // With exclude config
    let mut config = LintConfig::default();
    config.files_mut().exclude = vec!["vendor/**".to_string()];

    let result = validate_project(root, &config).unwrap();
    // Only the root CLAUDE.md should be checked, not vendor/CLAUDE.md
    assert_eq!(
        result.files_checked, 1,
        "Only root CLAUDE.md should be checked, got {}",
        result.files_checked
    );
}

#[test]
fn test_validate_project_with_invalid_files_pattern() {
    let temp = tempfile::TempDir::new().unwrap();
    let root = temp.path();

    // Create a file so the project is not empty
    std::fs::write(root.join("CLAUDE.md"), "# Project\n").unwrap();

    let mut config = LintConfig::default();
    config.files_mut().include_as_memory = vec!["[invalid".to_string()];

    // Invalid patterns degrade gracefully: validation proceeds with no
    // file overrides applied (consistent with LintConfig::validate() which
    // only produces warnings for invalid patterns).
    let result = validate_project(root, &config);
    assert!(
        result.is_ok(),
        "Expected graceful degradation for invalid file pattern, got error: {:?}",
        result.unwrap_err()
    );
}

// The walker-side compile of `[files].exclude` must not emit its own
// invalid-pattern warnings, because `compile_files_config_with_diagnostics`
// already emits them. Previously we merged both warning sets and tried to
// dedupe with `dedup_by`, but non-adjacent duplicates slipped through.
#[test]
fn test_invalid_files_exclude_pattern_warns_once() {
    let temp = tempfile::TempDir::new().unwrap();
    let root = temp.path();

    std::fs::write(root.join("CLAUDE.md"), "# Project\n").unwrap();

    let mut config = LintConfig::default();
    config.files_mut().include_as_generic = vec!["[bad-generic".to_string()];
    config.files_mut().exclude = vec!["[bad-exclude".to_string()];

    let result = validate_project(root, &config).unwrap();

    let bad_exclude_warnings: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "config::glob" && d.message.contains("[bad-exclude"))
        .collect();
    assert_eq!(
        bad_exclude_warnings.len(),
        1,
        "expected exactly one warning for the invalid [files].exclude pattern, got {}: {:?}",
        bad_exclude_warnings.len(),
        bad_exclude_warnings
            .iter()
            .map(|d| &d.message)
            .collect::<Vec<_>>()
    );
}

// Regression for #722: previously, `[files].exclude` only skipped per-file
// validators (via FileType::Unknown) while project-level rules like AGM-006
// collected paths by filename during the walk. A vendored AGENTS.md would
// silently trigger AGM-006 "Nested AGENTS.md" despite being excluded.
// After the fix, `[files].exclude` joins the walker filter so excluded paths
// don't feed cross-file rule collection either.
#[test]
fn test_files_config_exclude_also_filters_project_level_rules() {
    let temp = tempfile::TempDir::new().unwrap();
    let root = temp.path();

    std::fs::write(
        root.join("AGENTS.md"),
        "# Project\n\nRoot agent instructions.\n",
    )
    .unwrap();

    let vendor = root.join("vendor").join("other-repo");
    std::fs::create_dir_all(&vendor).unwrap();
    std::fs::write(
        vendor.join("AGENTS.md"),
        "# Vendored\n\nThird-party content.\n",
    )
    .unwrap();

    let mut config = LintConfig::default();
    config.files_mut().exclude = vec!["**/vendor/**".to_string()];

    let result = validate_project(root, &config).unwrap();

    // Project-level rules should not see the vendored AGENTS.md, so AGM-006
    // (nested AGENTS.md) must not fire.
    let agm_006: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "AGM-006")
        .collect();
    assert!(
        agm_006.is_empty(),
        "[files].exclude should prevent AGM-006 on vendored AGENTS.md, got: {:?}",
        agm_006.iter().map(|d| &d.message).collect::<Vec<_>>()
    );

    // And the vendored file must not show up in any diagnostic path.
    let mentions_vendor = result
        .diagnostics
        .iter()
        .any(|d| d.file.to_string_lossy().contains("vendor") || d.message.contains("vendor"));
    assert!(
        !mentions_vendor,
        "no diagnostic should reference vendored paths, got: {:?}",
        result.diagnostics
    );
}

#[test]
fn test_validate_file_respects_files_config_exclude() {
    let temp = tempfile::TempDir::new().unwrap();
    let root = temp.path();

    // Create a CLAUDE.md that would normally produce diagnostics
    let claude_file = root.join("CLAUDE.md");
    std::fs::write(&claude_file, "# Project\n\nNever use var.\n").unwrap();

    // With exclude config, the file should be skipped entirely
    let mut config = LintConfig::default();
    config.files_mut().exclude = vec!["CLAUDE.md".to_string()];
    config.set_root_dir(root.to_path_buf());

    let registry = ValidatorRegistry::with_defaults();
    let outcome = validate_file_with_registry(&claude_file, &config, &registry).unwrap();
    assert!(
        outcome.is_skipped(),
        "Expected Skipped for excluded file, got: {:?}",
        outcome
    );
}

#[test]
fn test_resolve_file_type_glob_separator_behavior() {
    // With require_literal_separator=true, `*` should NOT match path separators.
    // `dir/*.md` should match `dir/file.md` but NOT `dir/sub/file.md`.
    // `dir/**/*.md` should match `dir/sub/file.md`.
    let mut config = LintConfig::default();
    config.files_mut().include_as_memory = vec!["dir/*.md".to_string()];
    config.set_root_dir(PathBuf::from("/project"));

    // Single-level match: dir/*.md matches dir/file.md
    assert_eq!(
        resolve_file_type(Path::new("/project/dir/file.md"), &config),
        FileType::ClaudeMd,
        "dir/*.md should match dir/file.md"
    );

    // Multi-level: dir/*.md should NOT match dir/sub/file.md
    assert_ne!(
        resolve_file_type(Path::new("/project/dir/sub/file.md"), &config),
        FileType::ClaudeMd,
        "dir/*.md should NOT match dir/sub/file.md (require_literal_separator)"
    );

    // With ** pattern, multi-level should match
    let mut config2 = LintConfig::default();
    config2.files_mut().include_as_memory = vec!["dir/**/*.md".to_string()];
    config2.set_root_dir(PathBuf::from("/project"));

    assert_eq!(
        resolve_file_type(Path::new("/project/dir/sub/file.md"), &config2),
        FileType::ClaudeMd,
        "dir/**/*.md should match dir/sub/file.md"
    );
}

#[test]
fn test_resolve_file_type_case_sensitive() {
    // Patterns are case-sensitive (FILES_MATCH_OPTIONS.case_sensitive = true).
    // "DEVELOPER.md" should match "DEVELOPER.md" but NOT "developer.md".
    let mut config = LintConfig::default();
    config.files_mut().include_as_memory = vec!["DEVELOPER.md".to_string()];
    config.set_root_dir(PathBuf::from("/project"));

    assert_eq!(
        resolve_file_type(Path::new("/project/DEVELOPER.md"), &config),
        FileType::ClaudeMd,
        "DEVELOPER.md pattern should match DEVELOPER.md"
    );
    assert_ne!(
        resolve_file_type(Path::new("/project/developer.md"), &config),
        FileType::ClaudeMd,
        "DEVELOPER.md pattern should NOT match developer.md (case-sensitive)"
    );
}

#[test]
fn test_resolve_file_type_double_star_recursive() {
    // "instructions/**/*.md" should match files at arbitrary nesting depth.
    let mut config = LintConfig::default();
    config.files_mut().include_as_memory = vec!["instructions/**/*.md".to_string()];
    config.set_root_dir(PathBuf::from("/project"));

    assert_eq!(
        resolve_file_type(Path::new("/project/instructions/sub/deep/file.md"), &config),
        FileType::ClaudeMd,
        "instructions/**/*.md should match instructions/sub/deep/file.md"
    );
    assert_eq!(
        resolve_file_type(Path::new("/project/instructions/file.md"), &config),
        FileType::ClaudeMd,
        "instructions/**/*.md should match instructions/file.md"
    );
    // Should not match files outside the instructions directory
    assert_ne!(
        resolve_file_type(Path::new("/project/other/file.md"), &config),
        FileType::ClaudeMd,
        "instructions/**/*.md should NOT match other/file.md"
    );
}

// ===== validate_project_rules() Tests =====

#[test]
fn test_validate_project_rules_agm006() {
    let temp_dir = tempfile::tempdir().unwrap();

    // Create two AGENTS.md files at different levels
    std::fs::write(temp_dir.path().join("AGENTS.md"), "# Root AGENTS").unwrap();
    let sub_dir = temp_dir.path().join("sub");
    std::fs::create_dir(&sub_dir).unwrap();
    std::fs::write(sub_dir.join("AGENTS.md"), "# Sub AGENTS").unwrap();

    let config = LintConfig::default();
    let diagnostics = validate_project_rules(temp_dir.path(), &config).unwrap();
    let agm006: Vec<_> = diagnostics.iter().filter(|d| d.rule == "AGM-006").collect();
    assert!(
        agm006.len() >= 2,
        "Expected AGM-006 for both AGENTS.md files, got {} diagnostics",
        agm006.len()
    );
}

// Regression for PR #725 review: validate_project_rules is the LSP
// lightweight path. It must surface Warning diagnostics for invalid
// `[files].exclude` patterns so editor users aren't silently ignored, matching
// `validate_project_with_registry`'s behaviour.
#[test]
fn test_validate_project_rules_warns_on_invalid_files_exclude() {
    let temp_dir = tempfile::tempdir().unwrap();
    std::fs::write(temp_dir.path().join("CLAUDE.md"), "# Project\n").unwrap();

    let mut config = LintConfig::default();
    config.files_mut().exclude = vec!["[bad-exclude".to_string()];

    let diagnostics = validate_project_rules(temp_dir.path(), &config).unwrap();

    let bad_pattern: Vec<_> = diagnostics
        .iter()
        .filter(|d| d.rule == "config::glob" && d.message.contains("[bad-exclude"))
        .collect();
    assert_eq!(
        bad_pattern.len(),
        1,
        "expected exactly one warning for the invalid [files].exclude in the LSP path, got {}: {:?}",
        bad_pattern.len(),
        bad_pattern.iter().map(|d| &d.message).collect::<Vec<_>>()
    );
}

#[test]
fn test_validate_project_rules_empty_dir() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config = LintConfig::default();
    let diagnostics = validate_project_rules(temp_dir.path(), &config).unwrap();
    // Only VER-001 should fire (no version pins)
    let non_ver = diagnostics.iter().filter(|d| d.rule != "VER-001").count();
    assert_eq!(
        non_ver, 0,
        "Empty dir should produce no non-VER diagnostics"
    );
}

#[test]
fn test_validate_project_rules_ver001() {
    let temp_dir = tempfile::tempdir().unwrap();
    // No .agnix.toml, no version pins
    let config = LintConfig::default();
    let diagnostics = validate_project_rules(temp_dir.path(), &config).unwrap();
    assert!(
        diagnostics.iter().any(|d| d.rule == "VER-001"),
        "Expected VER-001 when no versions are pinned"
    );
}

#[test]
fn test_validate_project_rules_disabled_rules() {
    let temp_dir = tempfile::tempdir().unwrap();

    // Create two AGENTS.md files
    std::fs::write(temp_dir.path().join("AGENTS.md"), "# Root").unwrap();
    let sub = temp_dir.path().join("sub");
    std::fs::create_dir(&sub).unwrap();
    std::fs::write(sub.join("AGENTS.md"), "# Sub").unwrap();

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

    let diagnostics = validate_project_rules(temp_dir.path(), &config).unwrap();
    assert!(
        !diagnostics.iter().any(|d| d.rule == "AGM-006"),
        "AGM-006 should be disabled"
    );
    assert!(
        !diagnostics.iter().any(|d| d.rule == "VER-001"),
        "VER-001 should be disabled"
    );
}

#[test]
fn test_validate_project_rules_xp004() {
    let temp_dir = tempfile::tempdir().unwrap();

    // Create conflicting instruction files
    std::fs::write(
        temp_dir.path().join("CLAUDE.md"),
        "# Setup\n\nRun `npm install` to install deps.\n`npm test` to run tests.\n",
    )
    .unwrap();
    std::fs::write(
        temp_dir.path().join("AGENTS.md"),
        "# Setup\n\nRun `yarn install` to install deps.\n`yarn test` to run tests.\n",
    )
    .unwrap();

    let config = LintConfig::default();
    let diagnostics = validate_project_rules(temp_dir.path(), &config).unwrap();
    let xp004: Vec<_> = diagnostics.iter().filter(|d| d.rule == "XP-004").collect();
    assert!(
        !xp004.is_empty(),
        "Expected XP-004 for conflicting package managers"
    );
}

#[test]
fn test_validate_project_rules_xp005() {
    let temp_dir = tempfile::tempdir().unwrap();

    // CLAUDE.md allows Bash
    std::fs::write(
        temp_dir.path().join("CLAUDE.md"),
        "# Project\n\nallowed-tools: Read Write Bash\n",
    )
    .unwrap();

    // AGENTS.md disallows Bash
    std::fs::write(
        temp_dir.path().join("AGENTS.md"),
        "# Project\n\nNever use Bash for operations.\n",
    )
    .unwrap();

    let config = LintConfig::default();
    let diagnostics = validate_project_rules(temp_dir.path(), &config).unwrap();
    let xp005: Vec<_> = diagnostics.iter().filter(|d| d.rule == "XP-005").collect();
    assert!(
        !xp005.is_empty(),
        "Expected XP-005 for conflicting tool constraints (Bash allowed in one, disallowed in other)"
    );
    assert!(
        xp005.iter().any(|d| d.message.contains("Bash")),
        "XP-005 diagnostic should mention the conflicting tool 'Bash'"
    );
}

#[test]
fn test_validate_project_rules_xp006() {
    let temp_dir = tempfile::tempdir().unwrap();

    // CLAUDE.md with commands section (no precedence documentation)
    std::fs::write(
        temp_dir.path().join("CLAUDE.md"),
        "# Project\n\n## Commands\n- npm test\n",
    )
    .unwrap();

    // AGENTS.md with commands section (no precedence documentation)
    std::fs::write(
        temp_dir.path().join("AGENTS.md"),
        "# Project\n\n## Commands\n- npm build\n",
    )
    .unwrap();

    let config = LintConfig::default();
    let diagnostics = validate_project_rules(temp_dir.path(), &config).unwrap();
    let xp006: Vec<_> = diagnostics.iter().filter(|d| d.rule == "XP-006").collect();
    assert!(
        !xp006.is_empty(),
        "Expected XP-006 for multiple instruction layers without precedence documentation"
    );
}

// ===== resolve_validation_root file-input Tests =====

#[test]
fn test_validate_project_file_input_single_file() {
    // When a file path is passed to validate_project(), only that single file
    // should be validated - sibling files in other directories are ignored.
    let temp = tempfile::TempDir::new().unwrap();

    let alpha_dir = temp.path().join("skills").join("alpha");
    std::fs::create_dir_all(&alpha_dir).unwrap();
    std::fs::write(
        alpha_dir.join("SKILL.md"),
        "---\nname: deploy-prod\ndescription: Deploys\n---\nBody",
    )
    .unwrap();

    let beta_dir = temp.path().join("skills").join("beta");
    std::fs::create_dir_all(&beta_dir).unwrap();
    std::fs::write(
        beta_dir.join("SKILL.md"),
        "---\nname: deploy-staging\ndescription: Deploys staging\n---\nBody",
    )
    .unwrap();

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

    // Pass the file path for alpha/SKILL.md, not the directory
    let target_file = alpha_dir.join("SKILL.md");
    let result = validate_project(&target_file, &config).unwrap();

    assert_eq!(
        result.files_checked, 1,
        "Only the targeted file should be checked, got {}",
        result.files_checked
    );

    // All diagnostics should reference the target file, not the beta sibling
    for d in &result.diagnostics {
        assert!(
            d.file.ends_with("alpha/SKILL.md") || d.file.ends_with("alpha\\SKILL.md"),
            "Diagnostic should reference alpha/SKILL.md, got: {}",
            d.file.display()
        );
    }
}

#[test]
fn test_validate_project_file_input_produces_diagnostics() {
    // Passing a single SKILL.md with a known violation should produce diagnostics.
    let temp = tempfile::TempDir::new().unwrap();
    let skill_path = temp.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        "---\nname: deploy-prod\ndescription: Deploys\n---\nBody",
    )
    .unwrap();

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

    let result = validate_project(&skill_path, &config).unwrap();

    assert_eq!(
        result.files_checked, 1,
        "Exactly one file should be checked, got {}",
        result.files_checked
    );
    assert!(
        result.diagnostics.iter().any(|d| d.rule == "CC-SK-006"),
        "Expected CC-SK-006 for dangerous deploy-prod name, got rules: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );
}

#[test]
fn test_validate_project_file_input_valid_file_no_errors() {
    // Passing a valid CLAUDE.md file should produce no diagnostics,
    // even when a sibling SKILL.md has violations.
    let temp = tempfile::TempDir::new().unwrap();

    // Valid CLAUDE.md
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nInstructions here.",
    )
    .unwrap();

    // Sibling with violations (should not be scanned)
    std::fs::write(
        temp.path().join("SKILL.md"),
        "---\nname: deploy-prod\ndescription: Deploys\n---\nBody",
    )
    .unwrap();

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

    let target_file = temp.path().join("CLAUDE.md");
    let result = validate_project(&target_file, &config).unwrap();

    assert_eq!(
        result.files_checked, 1,
        "Only the targeted CLAUDE.md should be checked, got {}",
        result.files_checked
    );
    assert!(
        result.diagnostics.is_empty(),
        "Valid CLAUDE.md should produce no diagnostics, got: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );
}

#[test]
fn test_validate_project_rules_file_input() {
    // When a file path is passed to validate_project_rules(), the walk is
    // scoped to that single file. AGM-006 requires multiple AGENTS.md files,
    // so it should NOT fire when only one file is walked.
    let temp = tempfile::TempDir::new().unwrap();

    std::fs::write(temp.path().join("AGENTS.md"), "# Root agents").unwrap();

    let sub_dir = temp.path().join("sub");
    std::fs::create_dir_all(&sub_dir).unwrap();
    std::fs::write(sub_dir.join("AGENTS.md"), "# Sub agents").unwrap();

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

    // Pass the root AGENTS.md file path, not the directory
    let target_file = temp.path().join("AGENTS.md");
    let diagnostics = validate_project_rules(&target_file, &config).unwrap();

    let agm006: Vec<_> = diagnostics.iter().filter(|d| d.rule == "AGM-006").collect();
    assert!(
        agm006.is_empty(),
        "AGM-006 should not fire when walk is scoped to a single file, got {} diagnostics",
        agm006.len()
    );
}

#[test]
fn test_validate_project_file_input_unknown_type_skipped() {
    // Passing an unrecognized file type should result in zero files checked
    // and no diagnostics, even when a sibling recognized file has violations.
    let temp = tempfile::TempDir::new().unwrap();

    std::fs::write(temp.path().join("main.rs"), "fn main() {}").unwrap();
    std::fs::write(
        temp.path().join("SKILL.md"),
        "---\nname: deploy-prod\ndescription: Deploys\n---\nBody",
    )
    .unwrap();

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

    let target_file = temp.path().join("main.rs");
    let result = validate_project(&target_file, &config).unwrap();

    assert_eq!(
        result.files_checked, 0,
        "Unrecognized file type should not be counted, got {}",
        result.files_checked
    );
    assert!(
        result.diagnostics.is_empty(),
        "Unrecognized file type should produce no diagnostics, got: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );
}

#[test]
fn test_validate_project_with_registry_file_input() {
    // validate_project_with_registry() should also respect file-input paths,
    // validating only the targeted file.
    let temp = tempfile::TempDir::new().unwrap();
    let skill_path = temp.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        "---\nname: deploy-prod\ndescription: Deploys\n---\nBody",
    )
    .unwrap();

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

    let registry = ValidatorRegistry::with_defaults();
    let result = validate_project_with_registry(&skill_path, &config, &registry).unwrap();

    assert_eq!(
        result.files_checked, 1,
        "Exactly one file should be checked via registry path, got {}",
        result.files_checked
    );
    assert!(
        !result.diagnostics.is_empty(),
        "Expected diagnostics for deploy-prod skill via registry path"
    );
    assert!(
        result.diagnostics.iter().any(|d| d.rule == "CC-SK-006"),
        "Expected CC-SK-006 for dangerous deploy-prod name via registry path, got rules: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );
}

/// Passing a nonexistent file path should return an error, not silently succeed
/// with 0 files checked.
#[test]
fn test_validate_project_file_input_nonexistent_path() {
    let temp = tempfile::TempDir::new().unwrap();
    let config = LintConfig::builder().build_lenient().unwrap();

    // Pass a nonexistent file - should return Err, not silently succeed
    let nonexistent = temp.path().join("nonexistent.md");
    let result = validate_project(&nonexistent, &config);

    assert!(
        result.is_err(),
        "Nonexistent file path should return Err, got: {:?}",
        result
    );
    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("Validation root not found"),
        "Error message should contain 'Validation root not found': {err_msg}"
    );
    assert!(
        err_msg.contains(nonexistent.to_str().unwrap()),
        "Error message should contain the path: {err_msg}"
    );
}

#[test]
fn test_validate_project_nonexistent_dir_returns_error() {
    let config = LintConfig::builder().build_lenient().unwrap();
    let nonexistent = Path::new("/nonexistent/path/that/does/not/exist");
    let result = validate_project(nonexistent, &config);
    assert!(result.is_err());
    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("Validation root not found"),
        "Error message should contain 'Validation root not found': {err_msg}"
    );
    assert!(
        err_msg.contains(nonexistent.to_str().unwrap()),
        "Error message should contain the path: {err_msg}"
    );
}

#[test]
fn test_validate_project_rules_nonexistent_returns_error() {
    let config = LintConfig::builder().build_lenient().unwrap();
    let nonexistent = Path::new("/nonexistent/path/rules");
    let result = validate_project_rules(nonexistent, &config);
    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("Validation root not found"),
        "Error message should contain 'Validation root not found': {err_msg}"
    );
    assert!(
        err_msg.contains(nonexistent.to_str().unwrap()),
        "Error message should contain the path: {err_msg}"
    );
}

#[test]
fn test_validate_project_with_registry_nonexistent_returns_error() {
    let registry = ValidatorRegistry::with_defaults();
    let config = LintConfig::builder().build_lenient().unwrap();
    let nonexistent = Path::new("/nonexistent/path/registry");
    let result = validate_project_with_registry(nonexistent, &config, &registry);
    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("Validation root not found"),
        "Error message should contain 'Validation root not found': {err_msg}"
    );
    assert!(
        err_msg.contains(nonexistent.to_str().unwrap()),
        "Error message should contain the path: {err_msg}"
    );
}

// ============================================================================
// Validator name() tests
// ============================================================================

#[test]
fn test_validator_name_returns_expected_values() {
    let registry = ValidatorRegistry::with_defaults();

    // Skill validators should include known names
    let skill_validators = registry.validators_for(FileType::Skill);
    let names: Vec<&str> = skill_validators.iter().map(|v| v.name()).collect();
    assert!(names.contains(&"SkillValidator"));
    assert!(names.contains(&"PerClientSkillValidator"));
    assert!(names.contains(&"XmlValidator"));
    assert!(names.contains(&"ImportsValidator"));

    // ClaudeMd validators should include known names
    let claude_validators = registry.validators_for(FileType::ClaudeMd);
    let claude_names: Vec<&str> = claude_validators.iter().map(|v| v.name()).collect();
    assert!(claude_names.contains(&"ClaudeMdValidator"));
    assert!(claude_names.contains(&"CrossPlatformValidator"));
    assert!(claude_names.contains(&"AgentsMdValidator"));
    assert!(claude_names.contains(&"PromptValidator"));
}

#[test]
fn test_validator_names_are_ascii_and_nonempty() {
    let registry = ValidatorRegistry::with_defaults();

    // Check all file types that have validators
    let file_types = [
        FileType::Skill,
        FileType::ClaudeMd,
        FileType::Agent,
        FileType::AmpCheck,
        FileType::Hooks,
        FileType::Plugin,
        FileType::Mcp,
        FileType::Copilot,
        FileType::CopilotScoped,
        FileType::ClaudeRule,
        FileType::CursorRule,
        FileType::CursorHooks,
        FileType::CursorAgent,
        FileType::CursorEnvironment,
        FileType::CursorRulesLegacy,
        FileType::ClineRules,
        FileType::ClineRulesFolder,
        FileType::OpenCodeConfig,
        FileType::GeminiMd,
        FileType::GeminiSettings,
        FileType::AmpSettings,
        FileType::GeminiExtension,
        FileType::GeminiIgnore,
        FileType::CodexConfig,
        FileType::GenericMarkdown,
    ];

    for file_type in file_types {
        let validators = registry.validators_for(file_type);
        for v in validators {
            let name = v.name();
            assert!(!name.is_empty(), "Validator name should not be empty");
            assert!(name.is_ascii(), "Validator name should be ASCII: {}", name);
            assert!(
                name.ends_with("Validator"),
                "Validator name should end with 'Validator': {}",
                name
            );
        }
    }
}

// ============================================================================
// Validator metadata() tests
// ============================================================================

const ALL_VALIDATED_FILE_TYPES: &[FileType] = &[
    FileType::Skill,
    FileType::ClaudeMd,
    FileType::Agent,
    FileType::AmpCheck,
    FileType::Hooks,
    FileType::Plugin,
    FileType::Mcp,
    FileType::Copilot,
    FileType::CopilotScoped,
    FileType::ClaudeRule,
    FileType::CursorRule,
    FileType::CursorHooks,
    FileType::CursorAgent,
    FileType::CursorEnvironment,
    FileType::CursorRulesLegacy,
    FileType::ClineRules,
    FileType::ClineRulesFolder,
    FileType::OpenCodeConfig,
    FileType::GeminiMd,
    FileType::GeminiSettings,
    FileType::AmpSettings,
    FileType::GeminiExtension,
    FileType::GeminiIgnore,
    FileType::CodexConfig,
    FileType::GenericMarkdown,
];

#[test]
fn test_all_validators_have_nonempty_rule_ids() {
    let registry = ValidatorRegistry::with_defaults();

    for file_type in ALL_VALIDATED_FILE_TYPES {
        let validators = registry.validators_for(*file_type);
        for v in validators {
            let meta = v.metadata();
            assert!(
                !meta.rule_ids.is_empty(),
                "Validator '{}' (file_type={:?}) should have at least one rule ID",
                meta.name,
                file_type,
            );
        }
    }
}

#[test]
fn test_metadata_name_matches_name_method() {
    let registry = ValidatorRegistry::with_defaults();

    for file_type in ALL_VALIDATED_FILE_TYPES {
        let validators = registry.validators_for(*file_type);
        for v in validators {
            let meta = v.metadata();
            assert_eq!(
                meta.name,
                v.name(),
                "metadata().name should match name() for validator '{}'",
                v.name(),
            );
        }
    }
}

#[test]
fn test_metadata_rule_ids_are_well_formed() {
    let registry = ValidatorRegistry::with_defaults();

    let rule_id_pattern = regex::Regex::new(r"^[A-Z]{1,6}-[A-Z]{0,4}-?\d{1,3}$").unwrap();

    for file_type in ALL_VALIDATED_FILE_TYPES {
        let validators = registry.validators_for(*file_type);
        for v in validators {
            let meta = v.metadata();
            for rule_id in meta.rule_ids {
                assert!(
                    rule_id_pattern.is_match(rule_id),
                    "Rule ID '{}' from validator '{}' does not match expected pattern",
                    rule_id,
                    meta.name,
                );
            }
        }
    }
}

#[test]
fn test_no_duplicate_rule_ids_across_validators() {
    use std::collections::HashMap;

    let registry = ValidatorRegistry::with_defaults();

    // Collect all rule_id -> validator_name mappings
    let mut rule_owners: HashMap<&str, &str> = HashMap::new();

    for file_type in ALL_VALIDATED_FILE_TYPES {
        let validators = registry.validators_for(*file_type);
        for v in validators {
            let meta = v.metadata();
            for rule_id in meta.rule_ids {
                if let Some(existing_owner) = rule_owners.get(rule_id) {
                    // Same validator registered for multiple file types is OK
                    assert_eq!(
                        *existing_owner, meta.name,
                        "Rule ID '{}' claimed by both '{}' and '{}'",
                        rule_id, existing_owner, meta.name,
                    );
                } else {
                    rule_owners.insert(rule_id, meta.name);
                }
            }
        }
    }
}

// ============================================================================
// disabled_validators config integration tests
// ============================================================================

#[test]
fn test_disabled_validators_config_filters_in_validate_file() {
    let temp_dir = tempfile::tempdir().unwrap();
    let claude_md = temp_dir.path().join("CLAUDE.md");
    // Content with an unclosed XML tag to trigger XmlValidator (XML-001)
    // Pattern: <example>text (opening tag with body, no closing tag)
    std::fs::write(&claude_md, "# Project\n\n<example>some content here\n").unwrap();

    // Without disabling, XmlValidator should fire
    let config = LintConfig::default();
    let diags = expect_success(validate_file(&claude_md, &config).unwrap());
    let xml_diags: Vec<_> = diags.iter().filter(|d| d.rule == "XML-001").collect();
    assert!(
        !xml_diags.is_empty(),
        "Expected XML-001 diagnostic without disabled_validators, got rules: {:?}",
        diags.iter().map(|d| &d.rule).collect::<Vec<_>>()
    );

    // With XmlValidator disabled, XML-001 should not appear
    let mut config_disabled = LintConfig::default();
    config_disabled.rules_mut().disabled_validators = vec!["XmlValidator".to_string()];
    let diags_disabled = expect_success(validate_file(&claude_md, &config_disabled).unwrap());
    let xml_diags_disabled: Vec<_> = diags_disabled
        .iter()
        .filter(|d| d.rule == "XML-001")
        .collect();
    assert!(
        xml_diags_disabled.is_empty(),
        "Expected no XML-001 with XmlValidator disabled, got: {:?}",
        xml_diags_disabled
    );
}

#[test]
fn test_disabled_validators_config_filters_in_validate_project() {
    let temp_dir = tempfile::tempdir().unwrap();
    let claude_md = temp_dir.path().join("CLAUDE.md");
    std::fs::write(&claude_md, "# Project\n\n<example>some content here\n").unwrap();

    // Without disabling
    let config = LintConfig::default();
    let result = validate_project(temp_dir.path(), &config).unwrap();
    let xml_diags: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XML-001")
        .collect();
    assert!(
        !xml_diags.is_empty(),
        "Expected XML-001 in project validation, got rules: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );

    // With XmlValidator disabled
    let mut config_disabled = LintConfig::default();
    config_disabled.rules_mut().disabled_validators = vec!["XmlValidator".to_string()];
    let result_disabled = validate_project(temp_dir.path(), &config_disabled).unwrap();
    let xml_diags_disabled: Vec<_> = result_disabled
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XML-001")
        .collect();
    assert!(
        xml_diags_disabled.is_empty(),
        "Expected no XML-001 with XmlValidator disabled"
    );
}

#[test]
fn test_disabled_validators_respected_in_validate_file_with_registry() {
    let temp_dir = tempfile::tempdir().unwrap();
    let claude_md = temp_dir.path().join("CLAUDE.md");
    // Content with an unclosed XML tag to trigger XmlValidator (XML-001)
    std::fs::write(&claude_md, "# Project\n\n<example>some content here\n").unwrap();

    // Shared registry without any pre-applied disables
    let registry = ValidatorRegistry::with_defaults();

    // Without disabling, XmlValidator should fire via validate_file_with_registry
    let config = LintConfig::default();
    let diags =
        expect_success(validate_file_with_registry(&claude_md, &config, &registry).unwrap());
    let xml_diags: Vec<_> = diags.iter().filter(|d| d.rule == "XML-001").collect();
    assert!(
        !xml_diags.is_empty(),
        "Expected XML-001 diagnostic from validate_file_with_registry without disabled_validators, got rules: {:?}",
        diags.iter().map(|d| &d.rule).collect::<Vec<_>>()
    );

    // With XmlValidator disabled via config, XML-001 should be filtered at runtime
    let mut config_disabled = LintConfig::default();
    config_disabled.rules_mut().disabled_validators = vec!["XmlValidator".to_string()];
    let diags_disabled = expect_success(
        validate_file_with_registry(&claude_md, &config_disabled, &registry).unwrap(),
    );
    let xml_diags_disabled: Vec<_> = diags_disabled
        .iter()
        .filter(|d| d.rule == "XML-001")
        .collect();
    assert!(
        xml_diags_disabled.is_empty(),
        "Expected no XML-001 from validate_file_with_registry with XmlValidator disabled, got: {:?}",
        xml_diags_disabled
    );
}

#[test]
fn test_validate_file_with_registry_consistent_with_validate_content() {
    let temp_dir = tempfile::tempdir().unwrap();
    let claude_md = temp_dir.path().join("CLAUDE.md");
    // Content with an unclosed XML tag to trigger XmlValidator (XML-001)
    std::fs::write(&claude_md, "# Project\n\n<example>some content here\n").unwrap();

    // Shared registry, config with XmlValidator disabled
    let registry = ValidatorRegistry::with_defaults();
    let mut config = LintConfig::default();
    config.rules_mut().disabled_validators = vec!["XmlValidator".to_string()];

    // validate_file_with_registry path
    let file_diags =
        expect_success(validate_file_with_registry(&claude_md, &config, &registry).unwrap());
    let file_rules: std::collections::HashSet<&str> =
        file_diags.iter().map(|d| d.rule.as_str()).collect();

    // validate_content path (read file content manually)
    let content = std::fs::read_to_string(&claude_md).unwrap();
    let content_diags = validate_content(&claude_md, &content, &config, &registry);
    let content_rules: std::collections::HashSet<&str> =
        content_diags.iter().map(|d| d.rule.as_str()).collect();

    assert_eq!(
        file_rules, content_rules,
        "validate_file_with_registry and validate_content should produce the same rule set \
         when using the same registry and config. \
         file_rules={:?}, content_rules={:?}",
        file_rules, content_rules
    );

    // Verify XML-001 is absent from both (sanity check)
    assert!(
        !file_rules.contains("XML-001"),
        "XML-001 should be filtered out by disabled_validators in validate_file_with_registry"
    );
    assert!(
        !content_rules.contains("XML-001"),
        "XML-001 should be filtered out by disabled_validators in validate_content"
    );

    // Also verify both paths agree when disabled_validators is empty
    let config_empty = LintConfig::default();
    let file_diags_enabled =
        expect_success(validate_file_with_registry(&claude_md, &config_empty, &registry).unwrap());
    let content = std::fs::read_to_string(&claude_md).unwrap();
    let content_diags_enabled = validate_content(&claude_md, &content, &config_empty, &registry);
    let file_rules_enabled: std::collections::HashSet<&str> =
        file_diags_enabled.iter().map(|d| d.rule.as_str()).collect();
    let content_rules_enabled: std::collections::HashSet<&str> = content_diags_enabled
        .iter()
        .map(|d| d.rule.as_str())
        .collect();
    assert_eq!(
        file_rules_enabled, content_rules_enabled,
        "validate_file_with_registry and validate_content should agree with empty disabled list"
    );
}

#[test]
fn test_validate_project_with_registry_respects_disabled_validators() {
    let temp_dir = tempfile::tempdir().unwrap();
    let claude_md = temp_dir.path().join("CLAUDE.md");
    std::fs::write(&claude_md, "# Project\n\n<example>some content here\n").unwrap();

    // Shared registry without pre-applied disables (mirrors the LSP shared-registry pattern)
    let registry = ValidatorRegistry::with_defaults();

    // Without disabling, XmlValidator should fire
    let config = LintConfig::default();
    let result = validate_project_with_registry(temp_dir.path(), &config, &registry).unwrap();
    let xml_diags: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XML-001")
        .collect();
    assert!(
        !xml_diags.is_empty(),
        "Expected XML-001 from validate_project_with_registry without disabled_validators, got rules: {:?}",
        result
            .diagnostics
            .iter()
            .map(|d| &d.rule)
            .collect::<Vec<_>>()
    );

    // With XmlValidator disabled via config, XML-001 should be filtered at runtime
    let mut config_disabled = LintConfig::default();
    config_disabled.rules_mut().disabled_validators = vec!["XmlValidator".to_string()];
    let result_disabled =
        validate_project_with_registry(temp_dir.path(), &config_disabled, &registry).unwrap();
    let xml_diags_disabled: Vec<_> = result_disabled
        .diagnostics
        .iter()
        .filter(|d| d.rule == "XML-001")
        .collect();
    assert!(
        xml_diags_disabled.is_empty(),
        "Expected no XML-001 from validate_project_with_registry with XmlValidator disabled, got: {:?}",
        xml_diags_disabled
    );
}

#[test]
fn test_disabled_validators_multi_validator_validate_file_with_registry() {
    let temp_dir = tempfile::tempdir().unwrap();
    let claude_md = temp_dir.path().join("CLAUDE.md");
    // Unclosed XML tag triggers XmlValidator (XML-001).
    // "Never use var" (negative-only instruction) triggers ClaudeMdValidator (CC-MEM-006).
    std::fs::write(
        &claude_md,
        "Never use var in JavaScript.\n\n<example>some content here\n",
    )
    .unwrap();

    let registry = ValidatorRegistry::with_defaults();

    // Confirm both rules fire with default config before disabling anything
    let config = LintConfig::default();
    let diags =
        expect_success(validate_file_with_registry(&claude_md, &config, &registry).unwrap());
    assert!(
        diags.iter().any(|d| d.rule == "XML-001"),
        "Expected XML-001 to fire with default config, got rules: {:?}",
        diags.iter().map(|d| &d.rule).collect::<Vec<_>>()
    );
    assert!(
        diags.iter().any(|d| d.rule == "CC-MEM-006"),
        "Expected CC-MEM-006 to fire with default config, got rules: {:?}",
        diags.iter().map(|d| &d.rule).collect::<Vec<_>>()
    );

    // Disable both validators simultaneously - both rule sets should be absent
    let mut config_multi = LintConfig::default();
    config_multi.rules_mut().disabled_validators =
        vec!["XmlValidator".to_string(), "ClaudeMdValidator".to_string()];
    let diags_multi =
        expect_success(validate_file_with_registry(&claude_md, &config_multi, &registry).unwrap());
    assert!(
        !diags_multi.iter().any(|d| d.rule == "XML-001"),
        "Expected XML-001 absent when XmlValidator is disabled, got: {:?}",
        diags_multi
            .iter()
            .filter(|d| d.rule == "XML-001")
            .collect::<Vec<_>>()
    );
    assert!(
        !diags_multi.iter().any(|d| d.rule == "CC-MEM-006"),
        "Expected CC-MEM-006 absent when ClaudeMdValidator is disabled, got: {:?}",
        diags_multi
            .iter()
            .filter(|d| d.rule == "CC-MEM-006")
            .collect::<Vec<_>>()
    );
}

#[test]
fn test_validate_file_with_registry_no_state_leakage_between_configs() {
    // Verify a shared registry produces correct results when called with alternating
    // configs (one disabling XmlValidator, one not), i.e. no state leakage between calls.
    let temp_dir = tempfile::tempdir().unwrap();
    let claude_md = temp_dir.path().join("CLAUDE.md");
    std::fs::write(&claude_md, "# Project\n\n<example>some content here\n").unwrap();

    let registry = ValidatorRegistry::with_defaults();
    let config_enabled = LintConfig::default();
    let mut config_disabled = LintConfig::default();
    config_disabled.rules_mut().disabled_validators = vec!["XmlValidator".to_string()];

    // Call 1: enabled - XML-001 should fire
    let diags1 = expect_success(
        validate_file_with_registry(&claude_md, &config_enabled, &registry).unwrap(),
    );
    assert!(
        diags1.iter().any(|d| d.rule == "XML-001"),
        "Call 1 (enabled): expected XML-001"
    );

    // Call 2: disabled - XML-001 should be absent
    let diags2 = expect_success(
        validate_file_with_registry(&claude_md, &config_disabled, &registry).unwrap(),
    );
    assert!(
        !diags2.iter().any(|d| d.rule == "XML-001"),
        "Call 2 (disabled): expected no XML-001"
    );

    // Call 3: enabled again - XML-001 must return (no state leakage from call 2)
    let diags3 = expect_success(
        validate_file_with_registry(&claude_md, &config_enabled, &registry).unwrap(),
    );
    assert!(
        diags3.iter().any(|d| d.rule == "XML-001"),
        "Call 3 (re-enabled): expected XML-001 to return after disabled call"
    );
}

// ============================================================================
// Custom provider end-to-end test
// ============================================================================

#[test]
fn test_custom_provider_end_to_end() {
    use agnix_core::{ValidatorFactory, ValidatorProvider};

    struct NoOpProvider;
    impl ValidatorProvider for NoOpProvider {
        fn validators(&self) -> Vec<(FileType, ValidatorFactory)> {
            vec![]
        }
    }

    // Build registry with defaults + empty provider
    let registry = ValidatorRegistry::builder()
        .with_defaults()
        .with_provider(&NoOpProvider)
        .build();

    // Should have the same count as defaults (empty provider adds nothing)
    let defaults = ValidatorRegistry::with_defaults();
    assert_eq!(
        registry.total_validator_count(),
        defaults.total_validator_count()
    );
}

// ============================================================================
// ValidationOutcome integration tests
// ============================================================================

#[test]
fn test_validation_outcome_io_error_for_nonexistent_file() {
    let config = LintConfig::default();
    let temp = tempfile::TempDir::new().unwrap();
    // Create a path to a file that doesn't exist within a temp directory
    let nonexistent_file = temp.path().join("CLAUDE.md");
    let outcome = validate_file(&nonexistent_file, &config).unwrap();
    assert!(
        outcome.is_io_error(),
        "Nonexistent file with known type should return IoError, got: {:?}",
        outcome
    );
    // into_diagnostics should produce a file::read diagnostic
    let diags = outcome.into_diagnostics();
    assert_eq!(diags.len(), 1);
    assert_eq!(diags[0].rule, "file::read");
}

#[test]
fn test_validation_outcome_skipped_for_unknown_type() {
    let temp = tempfile::TempDir::new().unwrap();
    let rs_file = temp.path().join("main.rs");
    std::fs::write(&rs_file, "fn main() {}").unwrap();

    let config = LintConfig::default();
    let outcome = validate_file(&rs_file, &config).unwrap();
    assert!(
        outcome.is_skipped(),
        "Unknown file type should return Skipped, got: {:?}",
        outcome
    );
    assert!(outcome.diagnostics().is_empty());
}

#[test]
fn test_validation_outcome_success_for_valid_file() {
    let temp = tempfile::TempDir::new().unwrap();
    let skill_path = temp.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        "---\nname: code-review\ndescription: Use when reviewing code\n---\nBody",
    )
    .unwrap();

    let config = LintConfig::default();
    let outcome = validate_file(&skill_path, &config).unwrap();
    assert!(
        outcome.is_success(),
        "Valid file should return Success, got: {:?}",
        outcome
    );
}

#[test]
fn test_validation_outcome_into_diagnostics_preserves_all() {
    let temp = tempfile::TempDir::new().unwrap();
    let claude_path = temp.path().join("CLAUDE.md");
    std::fs::write(&claude_path, "<unclosed>").unwrap();

    let config = LintConfig::default();
    let outcome = validate_file(&claude_path, &config).unwrap();
    assert!(outcome.is_success());

    let diag_count = outcome.diagnostics().len();
    let into_diags = outcome.into_diagnostics();
    assert_eq!(
        into_diags.len(),
        diag_count,
        "into_diagnostics should preserve all diagnostics"
    );
}

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

    let dir = tempfile::TempDir::new().unwrap();
    let skill_path = dir.path().join("SKILL.md");
    std::fs::write(&skill_path, "# Test\n").unwrap();

    // Make file unreadable so safe_read_file returns an IoError
    let original_mode = std::fs::metadata(&skill_path).unwrap().permissions().mode();
    std::fs::set_permissions(&skill_path, std::fs::Permissions::from_mode(0o000)).unwrap();

    // Probe whether the permission change took effect. On systems where the
    // process runs as root, chmod(0o000) does not prevent reads, so we skip
    // rather than produce a false failure.
    let probe_readable = std::fs::read(&skill_path).is_ok();
    if probe_readable {
        // Running as root or on a filesystem that ignores permission bits.
        // Restore and skip.
        std::fs::set_permissions(&skill_path, std::fs::Permissions::from_mode(original_mode))
            .unwrap();
        return;
    }

    let config = LintConfig::builder().build().unwrap();
    let result = validate_project(dir.path(), &config).unwrap();

    // Restore permissions before cleanup so the tempdir can be deleted
    std::fs::set_permissions(&skill_path, std::fs::Permissions::from_mode(0o644)).unwrap();

    let has_file_read_error = result.diagnostics.iter().any(|d| d.rule == "file::read");
    assert!(
        has_file_read_error,
        "Expected file::read diagnostic for unreadable file, got: {:?}",
        result.diagnostics
    );
}

#[test]
fn test_validate_project_skipped_files_not_counted() {
    // Verify that files with unknown types (Skipped outcome) are not counted
    // in files_checked, while recognized types are.
    let temp = tempfile::TempDir::new().unwrap();

    // Create one recognized file (SKILL.md)
    std::fs::write(
        temp.path().join("SKILL.md"),
        "---\nname: test-skill\ndescription: Test skill\n---\nBody",
    )
    .unwrap();

    // Create several unrecognized files that should be skipped
    std::fs::write(temp.path().join("helper.rs"), "fn main() {}").unwrap();
    std::fs::write(temp.path().join("data.csv"), "a,b,c").unwrap();
    std::fs::write(temp.path().join("notes.txt"), "some notes").unwrap();

    let config = LintConfig::default();
    let result = validate_project(temp.path(), &config).unwrap();

    assert_eq!(
        result.files_checked, 1,
        "files_checked should count only the recognized SKILL.md, not the skipped .rs/.csv/.txt files, got {}",
        result.files_checked
    );
}

/// Regression test for #459: invalid glob patterns in [files] config should
/// produce config::glob Warning diagnostics in validate_project output, not
/// eprintln! to stderr.
#[test]
fn test_invalid_glob_in_files_config_produces_diagnostic() {
    let temp = tempfile::TempDir::new().unwrap();

    // Write a valid CLAUDE.md so the project has at least one recognized file
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nSome instructions.\n",
    )
    .unwrap();

    // Build a config with an invalid glob pattern in include_as_memory
    let mut config = LintConfig::default();
    config
        .files_mut()
        .include_as_memory
        .push("[invalid-glob".to_string());

    let result = validate_project(temp.path(), &config).unwrap();

    let glob_diags: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "config::glob")
        .collect();

    assert_eq!(
        glob_diags.len(),
        1,
        "Expected exactly 1 config::glob diagnostic for the invalid pattern, got: {glob_diags:?}"
    );

    assert_eq!(
        glob_diags[0].level,
        DiagnosticLevel::Warning,
        "config::glob diagnostic should be Warning level"
    );

    assert!(
        glob_diags[0].message.contains("[invalid-glob"),
        "Diagnostic message should mention the invalid pattern, got: {}",
        glob_diags[0].message
    );

    assert!(
        glob_diags[0].suggestion.is_some(),
        "config::glob diagnostic should include a suggestion"
    );

    assert_eq!(
        glob_diags[0].file,
        std::fs::canonicalize(temp.path())
            .unwrap()
            .join(".agnix.toml"),
        "diagnostic file should be absolute path"
    );
}

/// Regression test: invalid patterns across all three [files] lists each produce a diagnostic.
#[test]
fn test_invalid_glob_in_all_files_config_lists_produces_diagnostics() {
    let temp = tempfile::TempDir::new().unwrap();

    // Write a valid CLAUDE.md so the project has at least one recognized file
    std::fs::write(
        temp.path().join("CLAUDE.md"),
        "# Project\n\nSome instructions.\n",
    )
    .unwrap();

    // Build a config with an invalid glob pattern in each of the three lists
    let mut config = LintConfig::default();
    config
        .files_mut()
        .include_as_memory
        .push("[bad-memory".to_string());
    config
        .files_mut()
        .include_as_generic
        .push("[bad-generic".to_string());
    config.files_mut().exclude.push("[bad-exclude".to_string());

    let result = validate_project(temp.path(), &config).unwrap();

    let glob_diags: Vec<_> = result
        .diagnostics
        .iter()
        .filter(|d| d.rule == "config::glob")
        .collect();

    assert_eq!(
        glob_diags.len(),
        3,
        "Expected exactly 3 config::glob diagnostics (one per list), got: {glob_diags:?}"
    );

    for d in &glob_diags {
        assert_eq!(d.level, DiagnosticLevel::Warning);
        assert_eq!(
            d.file,
            std::fs::canonicalize(temp.path())
                .unwrap()
                .join(".agnix.toml"),
            "diagnostic file should be absolute path"
        );
        assert!(d.suggestion.is_some());
    }
}