agnix-cli 0.19.0

CLI for agnix - agent config linter
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
use assert_cmd::Command;
use predicates::prelude::*;

fn agnix() -> Command {
    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("agnix");
    cmd.current_dir(workspace_root());
    cmd
}

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

    static ROOT: OnceLock<std::path::PathBuf> = OnceLock::new();
    ROOT.get_or_init(|| {
        let manifest_dir = std::path::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()
}

fn workspace_path(relative: &str) -> std::path::PathBuf {
    workspace_root().join(relative)
}

fn fixtures_config() -> tempfile::NamedTempFile {
    use std::io::Write;

    let mut file = tempfile::NamedTempFile::new().unwrap();
    file.write_all(
        br#"severity = "Error"
target = "Generic"
exclude = [
  "node_modules/**",
  ".git/**",
  "target/**",
]

[rules]
"#,
    )
    .unwrap();
    file.flush().unwrap();

    file
}

fn assert_fix_flags_rejected(format: &str, flag: &str) {
    let mut cmd = agnix();
    cmd.arg("tests/fixtures/valid")
        .arg("--format")
        .arg(format)
        .arg(flag)
        .assert()
        .failure()
        .stderr(predicate::str::contains(
            "Fix flags are only supported with text output",
        ));
}

// Helper function to check JSON output contains rules from a specific family
fn check_json_rule_family(fixture: &str, prefixes: &[&str], family_name: &str) {
    let mut cmd = agnix();
    let output = cmd
        .arg(fixture)
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let diagnostics = json["diagnostics"].as_array().unwrap();

    let has_rule = diagnostics.iter().any(|d| {
        let rule = d["rule"].as_str().unwrap_or("");
        prefixes.iter().any(|p| rule.starts_with(p))
    });

    assert!(
        has_rule,
        "Expected at least one {} rule ({}) in diagnostics, got: {}",
        family_name,
        prefixes.join(" or "),
        stdout
    );
}

// Helper function to check SARIF output contains rules from a specific family
fn check_sarif_rule_family(fixture: &str, prefixes: &[&str], family_name: &str) {
    let mut cmd = agnix();
    let output = cmd
        .arg(fixture)
        .arg("--format")
        .arg("sarif")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let results = json["runs"][0]["results"].as_array().unwrap();

    let has_rule = results.iter().any(|r| {
        let rule_id = r["ruleId"].as_str().unwrap_or("");
        prefixes.iter().any(|p| rule_id.starts_with(p))
    });

    assert!(
        has_rule,
        "SARIF results should include {} diagnostics ({})",
        family_name,
        prefixes.join(" or ")
    );
}

#[test]
fn test_format_sarif_produces_valid_json() {
    let mut cmd = agnix();
    let assert = cmd
        .arg("tests/fixtures/valid")
        .arg("--format")
        .arg("sarif")
        .assert();

    assert
        .success()
        .stdout(predicate::str::contains("\"version\": \"2.1.0\""))
        .stdout(predicate::str::contains("\"$schema\""))
        .stdout(predicate::str::contains("\"runs\""));
}

#[test]
fn test_fix_flags_rejected_for_json_and_sarif() {
    let formats = ["json", "sarif"];
    let flags = ["--fix", "--dry-run", "--fix-safe", "--fix-unsafe"];

    for format in formats {
        for flag in flags {
            assert_fix_flags_rejected(format, flag);
        }
    }
}

#[test]
fn test_format_sarif_contains_tool_info() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/valid")
        .arg("--format")
        .arg("sarif")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    assert_eq!(json["runs"][0]["tool"]["driver"]["name"], "agnix");
    assert!(json["runs"][0]["tool"]["driver"]["rules"].is_array());
}

#[test]
fn test_format_sarif_has_all_rules() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/valid")
        .arg("--format")
        .arg("sarif")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    let rules = json["runs"][0]["tool"]["driver"]["rules"]
        .as_array()
        .unwrap();

    // Use threshold range to avoid brittleness when rules are added/removed,
    // while still catching major regressions (missing rules) or explosions.
    // As of writing, there are ~405 rules documented in VALIDATION-RULES.md;
    // the upper bound has ~10% headroom against accidental explosion.
    assert!(
        rules.len() >= 70,
        "Expected at least 70 validation rules, found {} (possible rule registration bug)",
        rules.len()
    );
    assert!(
        rules.len() <= 450,
        "Expected at most 450 validation rules, found {} (unexpected rule explosion)",
        rules.len()
    );

    // Verify rule structure: each rule should have id and shortDescription
    for (i, rule) in rules.iter().enumerate() {
        assert!(
            rule["id"].is_string(),
            "Rule at index {} should have an 'id' field. Rule: {}",
            i,
            rule
        );
        assert!(
            rule["shortDescription"]["text"].is_string(),
            "Rule at index {} should have a 'shortDescription.text' field. Rule: {}",
            i,
            rule
        );
    }
}

#[test]
fn test_format_sarif_exit_code_on_success() {
    let mut cmd = agnix();
    cmd.arg("tests/fixtures/valid")
        .arg("--format")
        .arg("sarif")
        .assert()
        .success();
}

#[test]
fn test_format_text_is_default() {
    let mut cmd = agnix();
    cmd.arg("tests/fixtures/valid")
        .assert()
        .success()
        .stdout(predicate::str::contains("\"version\"").not());
}

#[test]
fn test_format_sarif_results_array_exists() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures")
        .arg("--format")
        .arg("sarif")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    assert!(
        json["runs"][0]["results"].is_array(),
        "SARIF output should have results array"
    );
}

#[test]
fn test_format_sarif_schema_url() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/valid")
        .arg("--format")
        .arg("sarif")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    assert!(
        json["$schema"]
            .as_str()
            .unwrap()
            .contains("sarif-schema-2.1.0"),
        "Schema URL should reference SARIF 2.1.0"
    );
}

#[test]
fn test_help_shows_format_option() {
    let mut cmd = agnix();
    cmd.arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("--format"));
}

// JSON format tests

#[test]
fn test_format_json_produces_valid_json() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/valid")
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: Result<serde_json::Value, _> = serde_json::from_str(&stdout);
    assert!(json.is_ok(), "JSON output should be valid JSON");

    let json = json.unwrap();
    assert!(json["version"].is_string());
    assert!(json["files_checked"].is_number());
    assert!(json["diagnostics"].is_array());
    assert!(json["summary"].is_object());
}

#[test]
fn test_format_json_version_matches_cargo() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/valid")
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    // Version must exactly match CARGO_PKG_VERSION (works for 0.x and 1.x+)
    let version = json["version"].as_str().unwrap();
    assert_eq!(
        version,
        env!("CARGO_PKG_VERSION"),
        "JSON version should match Cargo.toml version"
    );
}

#[test]
fn test_format_json_summary_counts() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/valid")
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    let summary = &json["summary"];
    assert!(summary["errors"].is_number());
    assert!(summary["warnings"].is_number());
    assert!(summary["info"].is_number());

    // Valid fixtures should have no errors
    assert_eq!(summary["errors"].as_u64().unwrap(), 0);
}

#[test]
fn test_format_json_diagnostic_fields() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures")
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    let diagnostics = json["diagnostics"].as_array().unwrap();
    if !diagnostics.is_empty() {
        let diag = &diagnostics[0];
        assert!(diag["level"].is_string());
        assert!(diag["rule"].is_string());
        assert!(diag["file"].is_string());
        assert!(diag["line"].is_number());
        assert!(diag["column"].is_number());
        assert!(diag["message"].is_string());
        // suggestion is optional, so just verify it's either null or string
        assert!(diag["suggestion"].is_null() || diag["suggestion"].is_string());
    }
}

#[test]
fn test_format_json_exit_code_on_error() {
    use std::fs;
    use std::io::Write;

    // Use tempfile for automatic cleanup even on panic
    let temp_dir = tempfile::tempdir().unwrap();

    let skills_dir = temp_dir.path().join("skills").join("bad-skill");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    let mut file = fs::File::create(&skill_path).unwrap();
    // Create a skill with invalid name (uppercase) to trigger error
    writeln!(
        file,
        "---\nname: Bad-Skill\ndescription: test\n---\nContent"
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    let errors = json["summary"]["errors"].as_u64().unwrap();
    // Invalid skill name should produce an error
    assert!(
        errors > 0,
        "Invalid skill name should produce at least one error, got: {}",
        stdout
    );
    assert!(
        !output.status.success(),
        "Should exit with error code when errors present"
    );
}

#[test]
fn test_format_json_strict_mode_with_warnings() {
    use std::fs;
    use std::io::Write;

    // Create a dedicated fixture that guarantees warnings but no errors
    let temp_dir = tempfile::tempdir().unwrap();

    let skills_dir = temp_dir.path().join("skills").join("test-skill-name");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    let mut file = fs::File::create(&skill_path).unwrap();
    // Valid skill name but missing trigger phrase (AS-010 warning)
    writeln!(
        file,
        "---\nname: test-skill-name\ndescription: A test skill for validation\n---\nThis skill does something."
    )
    .unwrap();

    // Without --strict, warnings should not cause failure
    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let warnings = json["summary"]["warnings"].as_u64().unwrap();
    let errors = json["summary"]["errors"].as_u64().unwrap();

    assert_eq!(errors, 0, "Should have no errors");
    assert!(warnings > 0, "Should have at least one warning (AS-010)");
    assert!(
        output.status.success(),
        "Without --strict, warnings should not cause failure"
    );

    // With --strict, warnings should cause exit code 1
    let mut cmd_strict = agnix();
    let output_strict = cmd_strict
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--format")
        .arg("json")
        .arg("--strict")
        .output()
        .unwrap();

    assert!(
        !output_strict.status.success(),
        "With --strict, warnings should cause exit code 1"
    );
}

#[test]
fn test_format_json_strict_mode_no_warnings() {
    // With --strict but no warnings or errors, should succeed
    // Use a path that produces clean output
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/valid/skills")
        .arg("--format")
        .arg("json")
        .arg("--strict")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    let errors = json["summary"]["errors"].as_u64().unwrap();
    let warnings = json["summary"]["warnings"].as_u64().unwrap();

    // Unconditionally assert: valid/skills fixture must be clean
    assert_eq!(errors, 0, "valid/skills fixture should have no errors");
    assert_eq!(warnings, 0, "valid/skills fixture should have no warnings");
    assert!(
        output.status.success(),
        "With --strict and no issues, should succeed"
    );
}

#[test]
fn test_format_json_exit_code_on_success() {
    let mut cmd = agnix();
    cmd.arg("tests/fixtures/valid")
        .arg("--format")
        .arg("json")
        .assert()
        .success();
}

#[test]
fn test_help_shows_json_format() {
    let mut cmd = agnix();
    cmd.arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("json"));
}

#[test]
fn test_format_json_files_checked_count() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/valid")
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    // files_checked should be a valid number
    let files_checked = json["files_checked"].as_u64();
    assert!(
        files_checked.is_some(),
        "files_checked should be a valid number"
    );
}

#[test]
fn test_format_json_forward_slashes_in_paths() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures")
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    let diagnostics = json["diagnostics"].as_array().unwrap();
    for diag in diagnostics {
        let file = diag["file"].as_str().unwrap();
        assert!(
            !file.contains('\\'),
            "File paths should use forward slashes, got: {}",
            file
        );
    }
}

#[test]
fn test_cli_covers_hook_fixtures_via_cli_validation() {
    let config = fixtures_config();

    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/invalid/hooks/missing-command-field")
        .arg("--format")
        .arg("json")
        .arg("--config")
        .arg(config.path())
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "Invalid hooks fixture should exit non-zero"
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    let diagnostics = json["diagnostics"].as_array().unwrap();
    let has_cchk006 = diagnostics.iter().any(|d| {
        d["rule"].as_str() == Some("CC-HK-006")
            && d["file"]
                .as_str()
                .map(|file| file.ends_with("missing-command-field/settings.json"))
                .unwrap_or(false)
    });
    assert!(
        has_cchk006,
        "Expected CC-HK-006 for missing-command-field settings.json, got: {}",
        stdout
    );
}

// ============================================================================
// JSON Output Rule Family Coverage Tests
// ============================================================================

#[test]
fn test_format_json_contains_skill_rules() {
    check_json_rule_family("tests/fixtures/invalid/skills", &["AS-", "CC-SK-"], "skill");
}

#[test]
fn test_format_json_contains_hook_rules() {
    check_json_rule_family("tests/fixtures/invalid/hooks", &["CC-HK-"], "hook");
}

#[test]
fn test_format_json_contains_agent_rules() {
    check_json_rule_family("tests/fixtures/invalid/agents", &["CC-AG-"], "agent");
}

#[test]
fn test_format_json_contains_mcp_rules() {
    check_json_rule_family("tests/fixtures/mcp", &["MCP-"], "MCP");
}

#[test]
fn test_format_json_contains_xml_rules() {
    check_json_rule_family("tests/fixtures/xml", &["XML-"], "XML");
}

#[test]
fn test_format_json_contains_plugin_rules() {
    check_json_rule_family("tests/fixtures/invalid/plugins", &["CC-PL-"], "plugin");
}

#[test]
fn test_format_json_contains_copilot_rules() {
    check_json_rule_family("tests/fixtures/copilot-invalid", &["COP-"], "Copilot");
}

#[test]
fn test_format_json_contains_agents_md_rules() {
    check_json_rule_family("tests/fixtures/agents_md", &["AGM-"], "AGENTS.md");
}

#[test]
fn test_format_json_contains_memory_rules() {
    use std::fs;
    use std::io::Write;

    // CC-MEM rules require specific content patterns to trigger
    // Create a fixture with generic instructions (CC-MEM-005)
    let temp_dir = tempfile::tempdir().unwrap();
    let claude_md = temp_dir.path().join("CLAUDE.md");
    let mut file = fs::File::create(&claude_md).unwrap();
    writeln!(
        file,
        "# Project Memory\n\nBe helpful and concise. Always follow best practices."
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let diagnostics = json["diagnostics"].as_array().unwrap();

    let has_memory_rule = diagnostics
        .iter()
        .any(|d| d["rule"].as_str().unwrap_or("").starts_with("CC-MEM-"));

    assert!(
        has_memory_rule,
        "Expected at least one memory rule (CC-MEM-*) in diagnostics, got: {}",
        stdout
    );
}

#[test]
fn test_format_json_contains_ref_rules() {
    check_json_rule_family("tests/fixtures/refs", &["REF-"], "reference");
}

#[test]
fn test_format_json_contains_cross_platform_rules() {
    check_json_rule_family("tests/fixtures/cross_platform", &["XP-"], "cross-platform");
}

#[test]
fn test_format_json_contains_amp_rules() {
    check_json_rule_family("tests/fixtures/amp-checks", &["AMP-"], "Amp");
}

#[test]
fn test_format_json_contains_amp_002_diagnostic() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/amp-checks")
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let diagnostics = json["diagnostics"].as_array().unwrap();
    assert!(
        diagnostics
            .iter()
            .any(|d| d["rule"].as_str() == Some("AMP-002")),
        "Expected AMP-002 in JSON diagnostics, got: {}",
        stdout
    );
}

// ============================================================================
// SARIF Output Completeness Tests
// ============================================================================

#[test]
fn test_format_sarif_results_include_skill_diagnostics() {
    check_sarif_rule_family("tests/fixtures/invalid/skills", &["AS-", "CC-SK-"], "skill");
}

#[test]
fn test_format_sarif_results_include_hook_diagnostics() {
    check_sarif_rule_family("tests/fixtures/invalid/hooks", &["CC-HK-"], "hook");
}

#[test]
fn test_format_sarif_results_include_mcp_diagnostics() {
    check_sarif_rule_family("tests/fixtures/mcp", &["MCP-"], "MCP");
}

#[test]
fn test_format_sarif_results_include_amp_diagnostics() {
    check_sarif_rule_family("tests/fixtures/amp-checks", &["AMP-"], "Amp");
}

#[test]
fn test_format_sarif_results_include_amp_002_diagnostic() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/amp-checks")
        .arg("--format")
        .arg("sarif")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let results = json["runs"][0]["results"].as_array().unwrap();
    assert!(
        results
            .iter()
            .any(|r| r["ruleId"].as_str() == Some("AMP-002")),
        "Expected AMP-002 in SARIF results, got: {}",
        stdout
    );
}

#[test]
fn test_format_sarif_results_include_memory_diagnostics() {
    use std::fs;
    use std::io::Write;

    // CC-MEM rules require specific content patterns to trigger
    // Create a fixture with generic instructions (CC-MEM-005)
    let temp_dir = tempfile::tempdir().unwrap();
    let claude_md = temp_dir.path().join("CLAUDE.md");
    let mut file = fs::File::create(&claude_md).unwrap();
    writeln!(
        file,
        "# Project Memory\n\nBe helpful and concise. Always follow best practices."
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--format")
        .arg("sarif")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let results = json["runs"][0]["results"].as_array().unwrap();

    let has_memory_result = results
        .iter()
        .any(|r| r["ruleId"].as_str().unwrap_or("").starts_with("CC-MEM-"));

    assert!(
        has_memory_result,
        "SARIF results should include memory diagnostics (CC-MEM-*)"
    );
}

#[test]
fn test_format_sarif_location_fields() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/invalid/skills")
        .arg("--format")
        .arg("sarif")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let results = json["runs"][0]["results"].as_array().unwrap();

    assert!(!results.is_empty(), "Should have at least one result");

    for result in results {
        let locations = result["locations"].as_array();
        assert!(
            locations.is_some(),
            "Each result should have locations array"
        );

        if let Some(locs) = locations {
            assert!(!locs.is_empty(), "Result should have at least one location");
            let physical = &locs[0]["physicalLocation"];
            assert!(
                physical["artifactLocation"]["uri"].is_string(),
                "Should have artifactLocation.uri"
            );
            assert!(
                physical["region"]["startLine"].is_number(),
                "Should have region.startLine"
            );
            assert!(
                physical["region"]["startColumn"].is_number(),
                "Should have region.startColumn"
            );
        }
    }
}

#[test]
fn test_format_sarif_rules_have_help_uri() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/valid")
        .arg("--format")
        .arg("sarif")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let rules = json["runs"][0]["tool"]["driver"]["rules"]
        .as_array()
        .unwrap();

    for rule in rules {
        let help_uri = rule["helpUri"].as_str();
        assert!(
            help_uri.is_some(),
            "Rule {} should have helpUri",
            rule["id"]
        );
        assert!(
            help_uri
                .unwrap()
                .contains("avifenesh.github.io/agnix/docs/rules/generated/"),
            "helpUri should reference website rule docs"
        );
    }
}

#[test]
fn test_sarif_artifact_uris_relative_to_git_root() {
    // Create a temp directory simulating a git repo with a subdirectory
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join(".git")).unwrap();

    // Create a nested project structure: repo_root/sub/CLAUDE.md
    let sub = tmp.path().join("sub");
    std::fs::create_dir(&sub).unwrap();
    // Write a file that triggers diagnostics (unclosed XML tag)
    std::fs::write(sub.join("CLAUDE.md"), "<unclosed>\nSome content\n").unwrap();

    // Run agnix from the subdirectory with SARIF output
    let mut cmd = assert_cmd::Command::cargo_bin("agnix").unwrap();
    let output = cmd
        .current_dir(&sub)
        .arg(".")
        .arg("--format")
        .arg("sarif")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value =
        serde_json::from_str(&stdout).expect("SARIF should be valid JSON");
    let results = json["runs"][0]["results"].as_array().unwrap();

    assert!(
        !results.is_empty(),
        "Test requires diagnostics to verify URI format"
    );

    let uri = results[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"]
        .as_str()
        .unwrap();
    // URI should include "sub/" prefix because it's relative to the git root,
    // not just "CLAUDE.md" which would be relative to CWD
    assert!(
        uri.starts_with("sub/"),
        "SARIF artifact URI should be relative to git root (expected 'sub/...'), got: {}",
        uri
    );
}

#[test]
fn test_json_format_uses_cwd_not_git_root() {
    // Verify JSON format still uses CWD for backwards compatibility
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join(".git")).unwrap();

    let sub = tmp.path().join("sub");
    std::fs::create_dir(&sub).unwrap();
    std::fs::write(sub.join("CLAUDE.md"), "<unclosed>\nSome content\n").unwrap();

    // Run from subdirectory with JSON format
    let mut cmd = assert_cmd::Command::cargo_bin("agnix").unwrap();
    let output = cmd
        .current_dir(&sub)
        .arg(".")
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("JSON should be valid");
    let diagnostics = json["diagnostics"].as_array().unwrap();

    assert!(
        !diagnostics.is_empty(),
        "Test requires diagnostics to verify path format"
    );

    let file = diagnostics[0]["file"].as_str().unwrap();
    // JSON should NOT have "sub/" prefix - it uses CWD-relative paths
    assert!(
        !file.starts_with("sub/"),
        "JSON file path should be relative to CWD, not git root, got: {}",
        file
    );
}

// ============================================================================
// Text Output Formatting Tests
// ============================================================================

#[test]
fn test_format_text_shows_file_location() {
    let mut cmd = agnix();
    cmd.arg("tests/fixtures/invalid/skills/unknown-tool")
        .assert()
        .failure()
        .stdout(predicate::str::is_match(r"[^:]+:\d+:\d+").unwrap());
}

#[test]
fn test_format_text_shows_error_level() {
    let mut cmd = agnix();
    // Match diagnostic line format: file:line:col error: message
    cmd.arg("tests/fixtures/invalid/skills/unknown-tool")
        .assert()
        .failure()
        .stdout(predicate::str::is_match(r":\d+:\d+.*error").unwrap());
}

#[test]
fn test_format_text_shows_warning_level() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("test-skill-name");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    let mut file = fs::File::create(&skill_path).unwrap();
    // Valid skill name but missing trigger phrase (AS-010 warning)
    writeln!(
        file,
        "---\nname: test-skill-name\ndescription: A test skill\n---\nContent"
    )
    .unwrap();

    let mut cmd = agnix();
    // Match diagnostic line format: file:line:col warning: message
    cmd.arg(temp_dir.path().to_str().unwrap())
        .assert()
        .success()
        .stdout(predicate::str::is_match(r":\d+:\d+.*warning").unwrap());
}

#[test]
fn test_format_text_shows_summary() {
    let mut cmd = agnix();
    cmd.arg("tests/fixtures/invalid/skills")
        .assert()
        .failure()
        .stdout(predicate::str::contains("Found"));
}

#[test]
fn test_format_text_verbose_shows_rule() {
    let mut cmd = agnix();
    cmd.arg("tests/fixtures/invalid/skills/unknown-tool")
        .arg("--verbose")
        .assert()
        .failure()
        .stdout(predicate::str::is_match(r"(AS|CC)-\w+-\d+").unwrap());
}

#[test]
fn test_format_text_verbose_shows_suggestion() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/invalid/skills/unknown-tool")
        .arg("--verbose")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    // Verbose mode should show additional help/suggestion info
    assert!(
        stdout.contains("help") || stdout.contains("suggestion") || stdout.contains("-->"),
        "Verbose output should contain help or suggestion info, got: {}",
        stdout
    );
}

// ============================================================================
// Fix and Dry-Run Tests
// ============================================================================

#[test]
fn test_dry_run_no_file_modification() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("bad-skill");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    let original_content = "---\nname: Bad-Skill\ndescription: test\n---\nContent";
    {
        let mut file = fs::File::create(&skill_path).unwrap();
        write!(file, "{}", original_content).unwrap();
    }

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--dry-run")
        .output()
        .unwrap();

    // Verify file was not modified
    let content_after = fs::read_to_string(&skill_path).unwrap();
    assert_eq!(
        content_after, original_content,
        "File should not be modified with --dry-run"
    );

    // Verify the flag was recognized (not just silently ignored)
    // CLI should still produce diagnostic output
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        !stdout.is_empty() || !output.status.success(),
        "--dry-run flag should be recognized and produce output or error"
    );
}

#[test]
fn test_fix_exit_code_on_remaining_errors() {
    let mut cmd = agnix();
    // Invalid fixtures have errors that cannot be auto-fixed
    let output = cmd
        .arg("tests/fixtures/invalid/skills/unknown-tool")
        .arg("--fix")
        .output()
        .unwrap();

    // Should still exit with error since errors remain
    assert!(
        !output.status.success(),
        "Should exit with error code when non-fixable errors remain"
    );

    // Verify the flag was recognized (produces diagnostic output, not clap error)
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stdout.is_empty() || stderr.is_empty(),
        "--fix flag should be recognized and run fix mode, got stderr: {}",
        stderr
    );
}

#[test]
fn test_fix_exit_code_when_all_issues_are_fixed() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().expect("Failed to create temp dir for test");
    let skills_dir = temp_dir.path().join("skills").join("test-skill-name");
    fs::create_dir_all(&skills_dir).expect("Failed to create skill dir for test");

    let skill_path = skills_dir.join("SKILL.md");
    {
        let mut file = fs::File::create(&skill_path).expect("Failed to create skill file for test");
        // Only AS-004 should fail here, and it is auto-fixable.
        write!(
            file,
            "---\nname: Test_Skill_Name\ndescription: Use when testing\n---\nContent"
        )
        .expect("Failed to write to skill file for test");
    }

    let mut cmd = agnix();
    let output = cmd
        .arg(
            temp_dir
                .path()
                .to_str()
                .expect("Temp path is not valid UTF-8"),
        )
        .arg("--fix")
        .output()
        .expect("Failed to execute agnix command");

    assert!(
        output.status.success(),
        "Expected --fix to exit 0 when all issues are fixed, stdout: {}, stderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    let fixed_content = fs::read_to_string(&skill_path).expect("Failed to read fixed skill file");
    assert!(
        fixed_content.contains("name: test-skill-name"),
        "Expected AS-004 fix to be applied, got: {}",
        fixed_content
    );
}

#[test]
fn test_fix_safe_exit_code() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/invalid/skills/unknown-tool")
        .arg("--fix-safe")
        .output()
        .unwrap();

    // Should still exit with error since errors remain
    assert!(
        !output.status.success(),
        "Should exit with error code when errors remain after --fix-safe"
    );

    // Verify the flag was recognized (produces diagnostic output, not clap error)
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stdout.is_empty() || stderr.is_empty(),
        "--fix-safe flag should be recognized and run fix mode, got stderr: {}",
        stderr
    );
}

#[test]
fn test_fix_unsafe_flag_recognized() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/invalid/skills/unknown-tool")
        .arg("--fix-unsafe")
        .output()
        .unwrap();

    // This fixture still has remaining diagnostics, so non-zero is expected.
    // The key assertion is that clap does not reject the flag as unknown.
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("unexpected argument '--fix-unsafe'"),
        "--fix-unsafe should be accepted by the CLI, got stderr: {}",
        stderr
    );
}

#[test]
fn test_dry_run_combines_with_fix_safe() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/invalid/skills/unknown-tool")
        .arg("--dry-run")
        .arg("--fix-safe")
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("cannot be used with"),
        "--dry-run should combine with --fix-safe, got stderr: {}",
        stderr
    );
}

#[test]
fn test_dry_run_combines_with_fix_unsafe() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/invalid/skills/unknown-tool")
        .arg("--dry-run")
        .arg("--fix-unsafe")
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("cannot be used with"),
        "--dry-run should combine with --fix-unsafe, got stderr: {}",
        stderr
    );
}

#[test]
fn test_show_fixes_displays_fixes_without_verbose() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("show-fixes");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    let mut file = fs::File::create(&skill_path).unwrap();
    writeln!(
        file,
        "---\nname: Invalid_Name\ndescription: use when testing\n---\nSome content"
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path())
        .arg("--show-fixes")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.to_lowercase().contains("fix:"),
        "--show-fixes should print inline fix descriptions, got:\n{}",
        stdout
    );
}

// ============================================================================
// Flag Combination Tests
// ============================================================================

#[test]
fn test_strict_with_sarif_format() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    let mut file = fs::File::create(&skill_path).unwrap();
    // Valid skill name but missing trigger phrase (AS-010 warning)
    writeln!(
        file,
        "---\nname: test-skill\ndescription: A test skill\n---\nContent"
    )
    .unwrap();

    // With --strict, warnings should cause exit code 1
    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--format")
        .arg("sarif")
        .arg("--strict")
        .output()
        .unwrap();

    // Verify it's valid SARIF
    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert!(json["runs"].is_array(), "Should produce valid SARIF");

    // Should fail due to warnings in strict mode
    assert!(
        !output.status.success(),
        "With --strict and warnings, should exit with error code"
    );
}

#[test]
fn test_verbose_with_json_ignored() {
    let mut cmd = agnix();
    let output = cmd
        .arg("tests/fixtures/valid")
        .arg("--verbose")
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    // Should still be valid JSON (verbose doesn't corrupt JSON output)
    let json: Result<serde_json::Value, _> = serde_json::from_str(&stdout);
    assert!(
        json.is_ok(),
        "--verbose should not corrupt JSON output, got: {}",
        stdout
    );
}

#[test]
fn test_target_cursor_disables_cc_rules() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("deploy-prod");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    let mut file = fs::File::create(&skill_path).unwrap();
    // This would normally trigger CC-SK-006 (Claude-specific rule)
    writeln!(
        file,
        "---\nname: deploy-prod\ndescription: Deploy to production\n---\nDeploy the application"
    )
    .unwrap();

    // With --target cursor, CC-* rules should be disabled
    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--format")
        .arg("json")
        .arg("--target")
        .arg("cursor")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let diagnostics = json["diagnostics"].as_array().unwrap();

    // Should not have any CC-* rules for cursor target
    let has_cc_rule = diagnostics
        .iter()
        .any(|d| d["rule"].as_str().unwrap_or("").starts_with("CC-"));

    assert!(
        !has_cc_rule,
        "With --target cursor, CC-* rules should be disabled"
    );
}

#[test]
fn test_target_kiro_disables_cc_rules() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("deploy-prod");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    let mut file = fs::File::create(&skill_path).unwrap();
    // This would normally trigger CC-SK-006 (Claude-specific rule)
    writeln!(
        file,
        "---\nname: deploy-prod\ndescription: Deploy to production\n---\nDeploy the application"
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--format")
        .arg("json")
        .arg("--target")
        .arg("kiro")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let diagnostics = json["diagnostics"].as_array().unwrap();

    let has_cc_rule = diagnostics
        .iter()
        .any(|d| d["rule"].as_str().unwrap_or("").starts_with("CC-"));
    let has_non_cc_rule = diagnostics
        .iter()
        .any(|d| !d["rule"].as_str().unwrap_or("").starts_with("CC-"));

    assert!(
        !has_cc_rule,
        "With --target kiro, CC-* rules should be disabled"
    );
    assert!(
        has_non_cc_rule,
        "With --target kiro, non-CC rules should still run"
    );
}

#[test]
fn test_validate_subcommand() {
    let mut cmd = agnix();
    cmd.arg("validate")
        .arg("tests/fixtures/valid")
        .assert()
        .success();
}

#[test]
fn test_dry_run_with_format_json_rejected() {
    assert_fix_flags_rejected("json", "--dry-run");
}

#[test]
fn test_fixtures_have_no_empty_placeholder_dirs() {
    use std::fs;
    use std::path::{Path, PathBuf};

    fn check_dir(dir: &Path, empty_dirs: &mut Vec<PathBuf>) -> bool {
        let mut has_file = false;
        let entries = fs::read_dir(dir).unwrap_or_else(|e| {
            panic!("Failed to read fixture directory {}: {}", dir.display(), e)
        });

        for entry in entries {
            let entry = entry
                .unwrap_or_else(|e| panic!("Failed to read entry under {}: {}", dir.display(), e));
            let path = entry.path();
            if path.is_file() {
                has_file = true;
                continue;
            }
            if path.is_dir() && check_dir(&path, empty_dirs) {
                has_file = true;
            }
        }

        if !has_file {
            empty_dirs.push(dir.to_path_buf());
        }

        has_file
    }

    let root = workspace_path("tests/fixtures");
    assert!(
        root.is_dir(),
        "Expected fixtures directory at {}",
        root.display()
    );

    let mut empty_dirs = Vec::new();
    check_dir(&root, &mut empty_dirs);

    assert!(
        empty_dirs.is_empty(),
        "Empty fixture directories found:\n{}",
        empty_dirs
            .iter()
            .map(|p| p.display().to_string())
            .collect::<Vec<_>>()
            .join("\n")
    );
}

// ===== Config Parse Warning Tests =====

#[test]
fn test_invalid_config_displays_warning_to_stderr() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_path = temp_dir.path().join(".agnix.toml");

    // Create invalid TOML
    std::fs::write(&config_path, "this is [ invalid toml").unwrap();

    // Create a minimal valid directory to scan
    let skill_dir = temp_dir.path().join(".claude").join("skills");
    std::fs::create_dir_all(&skill_dir).unwrap();
    let skill_file = skill_dir.join("test.md");
    std::fs::write(&skill_file, "# Test\nSimple content").unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path())
        .arg("--config")
        .arg(&config_path)
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should contain warning message
    assert!(
        stderr.contains("Warning:") && stderr.contains("Failed to parse config"),
        "Expected config warning in stderr, got: {}",
        stderr
    );

    // Should still produce validation output (continues with defaults)
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("Validating:"),
        "Should still run validation with default config"
    );
}

#[test]
fn test_valid_config_no_warning_in_stderr() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_path = temp_dir.path().join(".agnix.toml");

    // Create valid config
    std::fs::write(
        &config_path,
        r#"
severity = "Warning"
target = "Generic"
exclude = []

[rules]
"#,
    )
    .unwrap();

    // Create a minimal valid directory to scan
    let skill_dir = temp_dir.path().join(".claude").join("skills");
    std::fs::create_dir_all(&skill_dir).unwrap();
    let skill_file = skill_dir.join("test.md");
    std::fs::write(&skill_file, "# Test\nSimple content").unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path())
        .arg("--config")
        .arg(&config_path)
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should NOT contain any config warning
    assert!(
        !stderr.contains("Failed to parse config"),
        "Valid config should not produce warning, stderr: {}",
        stderr
    );
}

#[test]
fn test_config_warning_with_json_output() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_path = temp_dir.path().join(".agnix.toml");

    // Create invalid TOML
    std::fs::write(&config_path, "invalid [[ toml").unwrap();

    // Create a minimal valid directory to scan
    let skill_dir = temp_dir.path().join(".claude").join("skills");
    std::fs::create_dir_all(&skill_dir).unwrap();
    let skill_file = skill_dir.join("test.md");
    std::fs::write(&skill_file, "# Test\nSimple content").unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path())
        .arg("--config")
        .arg(&config_path)
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Warning should go to stderr, not corrupt JSON output
    assert!(
        stderr.contains("Warning:"),
        "Warning should be in stderr for JSON output"
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: Result<serde_json::Value, _> = serde_json::from_str(&stdout);
    assert!(
        json.is_ok(),
        "JSON output should be valid despite config warning, got: {}",
        stdout
    );
}

// ============================================================================
// Target Argument Validation Tests (Issue #129)
// ============================================================================

#[test]
fn test_invalid_target_rejected() {
    let mut cmd = agnix();
    cmd.arg("tests/fixtures/valid")
        .arg("--target")
        .arg("invalid-target")
        .assert()
        .failure()
        .stderr(predicate::str::contains("invalid value"));
}

#[test]
fn test_typo_target_rejected() {
    let mut cmd = agnix();
    // Underscore instead of hyphen should be rejected
    cmd.arg("tests/fixtures/valid")
        .arg("--target")
        .arg("claude_code")
        .assert()
        .failure()
        .stderr(predicate::str::contains("invalid value"));
}

#[test]
fn test_case_sensitive_target_rejected() {
    let mut cmd = agnix();
    // PascalCase should be rejected (CLI uses kebab-case)
    cmd.arg("tests/fixtures/valid")
        .arg("--target")
        .arg("ClaudeCode")
        .assert()
        .failure()
        .stderr(predicate::str::contains("invalid value"));
}

#[test]
fn test_valid_targets_accepted() {
    for target in ["generic", "claude-code", "cursor", "codex", "kiro"] {
        let mut cmd = agnix();
        cmd.arg("tests/fixtures/valid")
            .arg("--target")
            .arg(target)
            .assert()
            .success();
    }
}

#[test]
fn test_help_shows_target_possible_values() {
    let mut cmd = agnix();
    let output = cmd.arg("--help").output().unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    // Help should list exact possible values for --target
    assert!(
        stdout.contains("[possible values: generic, claude-code, cursor, codex, kiro]"),
        "Help should show exact possible target values, got: {}",
        stdout
    );
}

// ============================================================================
// JSON Output files_checked Accuracy Tests (Issue #127)
// ============================================================================

#[test]
fn test_format_json_files_checked_counts_all_validated_files() {
    use std::fs;

    // Create a directory with valid files that produce no diagnostics
    let temp_dir = tempfile::tempdir().unwrap();

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

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

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "agnix exited with non-zero status: {:?}",
        output.status
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    let files_checked = json["files_checked"].as_u64().unwrap();

    // files_checked should be exactly 2 (the two SKILL.md files we created)
    assert_eq!(
        files_checked, 2,
        "Expected 2 files checked, found {}",
        files_checked
    );
}

#[test]
fn test_format_json_files_checked_excludes_unknown_types() {
    use std::fs;

    // Create a directory with mixed file types
    let temp_dir = tempfile::tempdir().unwrap();

    // Create files of unknown type (should NOT be counted)
    fs::write(temp_dir.path().join("main.rs"), "fn main() {}").unwrap();
    fs::write(temp_dir.path().join("index.ts"), "console.log('hello')").unwrap();

    // Create one recognized file (should be counted)
    let skill_dir = temp_dir.path().join("code-review");
    fs::create_dir_all(&skill_dir).unwrap();
    fs::write(
        skill_dir.join("SKILL.md"),
        "---\nname: code-review\ndescription: Use when reviewing code\n---\nBody",
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "agnix exited with non-zero status: {:?}",
        output.status
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    let files_checked = json["files_checked"].as_u64().unwrap();

    // Only the SKILL.md file should be counted
    assert_eq!(
        files_checked, 1,
        "files_checked should only count recognized file types (SKILL.md), got {}",
        files_checked
    );
}

#[test]
fn test_init_creates_config_file_with_plain_text_output() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_path = temp_dir.path().join(".agnix.toml");

    let mut cmd = agnix();
    let output = cmd
        .arg("init")
        .arg(config_path.to_str().unwrap())
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Verify output contains "Created:" (plain text, no emoji)
    assert!(
        stdout.contains("Created:"),
        "Init output should contain 'Created:', got: {}",
        stdout
    );

    // Verify output does NOT contain checkmark emoji
    assert!(
        !stdout.contains('\u{2713}') && !stdout.contains('\u{2714}'),
        "Init output should not contain checkmark emoji, got: {}",
        stdout
    );

    // Verify the config file was created
    assert!(
        config_path.exists(),
        "Config file should be created at {}",
        config_path.display()
    );

    // Verify the config file contains valid TOML
    let content = std::fs::read_to_string(&config_path).unwrap();
    let parsed: Result<toml::Value, _> = toml::from_str(&content);
    assert!(
        parsed.is_ok(),
        "Created config should be valid TOML, got: {}",
        content
    );

    // Verify exit code is success
    assert!(output.status.success(), "Init command should succeed");
}

// ============================================================================
// Auto-Fix Tests for AS-004 and AS-010 (Issue #15)
// ============================================================================

#[test]
fn test_fix_as_004_converts_name_to_kebab_case() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    {
        let mut file = fs::File::create(&skill_path).unwrap();
        // Invalid name with underscores
        write!(
            file,
            "---\nname: Test_Skill_Name\ndescription: Use when testing\n---\nBody"
        )
        .unwrap();
    }

    // Run with --fix
    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--fix")
        .output()
        .unwrap();

    // Read the fixed file
    let fixed_content = fs::read_to_string(&skill_path).unwrap();

    // Should convert Test_Skill_Name to test-skill-name
    assert!(
        fixed_content.contains("name: test-skill-name"),
        "AS-004 fix should convert name to kebab-case, got: {}",
        fixed_content
    );

    // Output should indicate fixes applied
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("Fixed") || stdout.contains("fix"),
        "Output should mention fix applied"
    );
}

#[test]
fn test_fix_as_010_prepends_trigger_phrase() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("code-review");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    {
        let mut file = fs::File::create(&skill_path).unwrap();
        // Valid name but missing trigger phrase
        write!(
            file,
            "---\nname: code-review\ndescription: Reviews code for quality\n---\nBody"
        )
        .unwrap();
    }

    // Run with --fix (not --fix-safe since AS-010 is not a safe fix)
    let mut cmd = agnix();
    cmd.arg(temp_dir.path().to_str().unwrap())
        .arg("--fix")
        .output()
        .unwrap();

    // Read the fixed file
    let fixed_content = fs::read_to_string(&skill_path).unwrap();

    // Should prepend "Use when user wants to " to description
    assert!(
        fixed_content.contains("Use when user wants to Reviews code for quality"),
        "AS-010 fix should prepend trigger phrase, got: {}",
        fixed_content
    );
}

#[test]
fn test_fix_safe_skips_as_010() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("code-review");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    let original_content = "---\nname: code-review\ndescription: Reviews code\n---\nBody";
    {
        let mut file = fs::File::create(&skill_path).unwrap();
        write!(file, "{}", original_content).unwrap();
    }

    // Run with --fix-safe (should NOT fix AS-010 since it's not safe)
    let mut cmd = agnix();
    cmd.arg(temp_dir.path().to_str().unwrap())
        .arg("--fix-safe")
        .output()
        .unwrap();

    // Read the file
    let content_after = fs::read_to_string(&skill_path).unwrap();

    // AS-010 fix is NOT safe, so it should NOT be applied
    assert_eq!(
        content_after, original_content,
        "--fix-safe should not apply AS-010 fix"
    );
}

#[test]
fn test_fix_safe_applies_case_only_as_004() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    {
        let mut file = fs::File::create(&skill_path).unwrap();
        // Name only needs lowercase (case-only change = safe)
        write!(
            file,
            "---\nname: TestSkill\ndescription: Use when testing\n---\nBody"
        )
        .unwrap();
    }

    // Run with --fix-safe
    let mut cmd = agnix();
    cmd.arg(temp_dir.path().to_str().unwrap())
        .arg("--fix-safe")
        .output()
        .unwrap();

    // Read the fixed file
    let fixed_content = fs::read_to_string(&skill_path).unwrap();

    // Case-only fix IS safe, so it should be applied
    assert!(
        fixed_content.contains("name: testskill"),
        "--fix-safe should apply case-only AS-004 fix, got: {}",
        fixed_content
    );
}

#[test]
fn test_dry_run_shows_as_004_fix_without_applying() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    let original_content = "---\nname: Test_Skill\ndescription: Use when testing\n---\nBody";
    {
        let mut file = fs::File::create(&skill_path).unwrap();
        write!(file, "{}", original_content).unwrap();
    }

    // Run with --dry-run
    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--dry-run")
        .output()
        .unwrap();

    // File should NOT be modified
    let content_after = fs::read_to_string(&skill_path).unwrap();
    assert_eq!(
        content_after, original_content,
        "--dry-run should not modify files"
    );

    // Output should show what would be fixed
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("Would fix") || stdout.contains("dry-run") || stdout.contains("test-skill"),
        "--dry-run should show what would be fixed"
    );
}

#[test]
fn test_fix_both_as_004_and_as_010_simultaneously() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    {
        let mut file = fs::File::create(&skill_path).unwrap();
        // Both AS-004 (invalid name) and AS-010 (missing trigger)
        write!(
            file,
            "---\nname: Test_Skill\ndescription: Does testing\n---\nBody"
        )
        .unwrap();
    }

    // Run with --fix
    let mut cmd = agnix();
    cmd.arg(temp_dir.path().to_str().unwrap())
        .arg("--fix")
        .output()
        .unwrap();

    // Read the fixed file
    let fixed_content = fs::read_to_string(&skill_path).unwrap();

    // Both fixes should be applied
    assert!(
        fixed_content.contains("name: test-skill"),
        "AS-004 fix should be applied, got: {}",
        fixed_content
    );
    assert!(
        fixed_content.contains("Use when user wants to Does testing"),
        "AS-010 fix should be applied, got: {}",
        fixed_content
    );
}

#[test]
fn test_fix_safe_skips_structural_as_004() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    let original_content = "---\nname: test_skill_name\ndescription: Use when testing\n---\nBody";
    {
        let mut file = fs::File::create(&skill_path).unwrap();
        // Name with underscores = structural change (not just case)
        write!(file, "{}", original_content).unwrap();
    }

    // Run with --fix-safe
    let mut cmd = agnix();
    cmd.arg(temp_dir.path().to_str().unwrap())
        .arg("--fix-safe")
        .output()
        .unwrap();

    // Read the file
    let content_after = fs::read_to_string(&skill_path).unwrap();

    // Structural AS-004 fix is NOT safe, should NOT be applied
    assert_eq!(
        content_after, original_content,
        "--fix-safe should not apply structural AS-004 fix"
    );
}

// ============================================================================
// Telemetry Command Tests (Issue #209)
// ============================================================================

#[test]
fn test_telemetry_status_shows_disabled_by_default() {
    let mut cmd = agnix();
    let output = cmd.arg("telemetry").arg("status").output().unwrap();

    assert!(output.status.success(), "telemetry status should succeed");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should show telemetry is disabled
    assert!(
        stdout.contains("disabled"),
        "Telemetry should be disabled by default, got: {}",
        stdout
    );

    // Should show privacy guarantees
    assert!(
        stdout.contains("Privacy Guarantees"),
        "Should display privacy guarantees, got: {}",
        stdout
    );
}

#[test]
fn test_telemetry_status_default_action() {
    // "agnix telemetry" without action should default to status
    let mut cmd = agnix();
    let output = cmd.arg("telemetry").output().unwrap();

    assert!(
        output.status.success(),
        "telemetry without action should succeed"
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("Telemetry Status"),
        "Should show status by default, got: {}",
        stdout
    );
}

#[test]
fn test_telemetry_help_shows_actions() {
    let mut cmd = agnix();
    let output = cmd.arg("telemetry").arg("--help").output().unwrap();

    assert!(output.status.success(), "telemetry --help should succeed");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should list the available actions
    assert!(
        stdout.contains("status") && stdout.contains("enable") && stdout.contains("disable"),
        "Help should show status/enable/disable actions, got: {}",
        stdout
    );
}

#[test]
fn test_telemetry_enable_disable_roundtrip() {
    use std::env;

    // Use a temp config directory to avoid affecting real config
    let temp_dir = tempfile::tempdir().unwrap();
    let config_dir = temp_dir.path().join("agnix");
    std::fs::create_dir_all(&config_dir).unwrap();

    // Skip this test in CI - it would try to write to the real config dir
    // and we can't easily override dirs::config_dir()
    if env::var("CI").is_ok() || env::var("GITHUB_ACTIONS").is_ok() {
        eprintln!("Skipping telemetry roundtrip test in CI");
        return;
    }

    // Test enable
    let mut cmd = agnix();
    let output = cmd.arg("telemetry").arg("enable").output().unwrap();

    assert!(output.status.success(), "telemetry enable should succeed");

    let stdout = String::from_utf8_lossy(&output.stdout);
    // Should indicate success or already enabled
    assert!(
        stdout.contains("enabled") || stdout.contains("already"),
        "Should confirm enable, got: {}",
        stdout
    );

    // Test disable
    let mut cmd = agnix();
    let output = cmd.arg("telemetry").arg("disable").output().unwrap();

    assert!(output.status.success(), "telemetry disable should succeed");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("disabled") || stdout.contains("already"),
        "Should confirm disable, got: {}",
        stdout
    );
}

#[test]
fn test_telemetry_invalid_action_rejected() {
    let mut cmd = agnix();
    cmd.arg("telemetry")
        .arg("invalid-action")
        .assert()
        .failure()
        .stderr(predicate::str::contains("invalid value"));
}

// ============================================================================
// Schema Command Integration Tests (Issue #206)
// ============================================================================

#[test]
fn test_schema_command_stdout() {
    // agnix schema outputs valid JSON to stdout
    let mut cmd = agnix();
    cmd.arg("schema")
        .assert()
        .success()
        .stdout(predicate::str::contains("\"$schema\""))
        .stdout(predicate::str::contains("LintConfig"));
}

#[test]
fn test_schema_command_output_file() {
    // agnix schema --output file.json writes to file
    let temp_dir = tempfile::tempdir().unwrap();
    let output_path = temp_dir.path().join("schema.json");

    let mut cmd = agnix();
    cmd.arg("schema")
        .arg("--output")
        .arg(&output_path)
        .assert()
        .success();

    // Verify file was created and contains valid JSON
    let content = std::fs::read_to_string(&output_path).unwrap();
    let json: serde_json::Value = serde_json::from_str(&content).unwrap();

    // Verify it's a valid JSON Schema
    assert!(
        json["$schema"].is_string(),
        "Schema output should have $schema field"
    );
    assert!(
        json["title"].is_string() || json["definitions"].is_object(),
        "Schema output should have title or definitions"
    );
}

#[test]
fn test_schema_command_help_shows_output_option() {
    let mut cmd = agnix();
    cmd.arg("schema")
        .arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("--output"));
}

// ============================================================================
// Config Validation Warning Display Integration Tests (Issue #206)
// ============================================================================

#[test]
fn test_invalid_rule_displays_semantic_warning() {
    // Use tests/fixtures/config_validation/invalid_rules.toml
    let mut cmd = agnix();
    cmd.arg("--config")
        .arg("tests/fixtures/config_validation/invalid_rules.toml")
        .arg("tests/fixtures/valid")
        .assert()
        .success()
        .stderr(predicate::str::contains("Config warning"))
        .stderr(predicate::str::contains("INVALID-001"));
}

#[test]
fn test_deprecated_field_displays_warning() {
    // Use tests/fixtures/config_validation/deprecated_fields.toml
    let mut cmd = agnix();
    cmd.arg("--config")
        .arg("tests/fixtures/config_validation/deprecated_fields.toml")
        .arg("tests/fixtures/valid")
        .assert()
        .success()
        .stderr(predicate::str::contains("mcp_protocol_version"))
        .stderr(predicate::str::contains("deprecated"));
}

#[test]
fn test_invalid_tools_displays_warning() {
    // Use tests/fixtures/config_validation/invalid_tools.toml
    let mut cmd = agnix();
    cmd.arg("--config")
        .arg("tests/fixtures/config_validation/invalid_tools.toml")
        .arg("tests/fixtures/valid")
        .assert()
        .success()
        .stderr(predicate::str::contains("Config warning"))
        .stderr(predicate::str::contains("unknown-tool"));
}

#[test]
fn test_valid_config_no_semantic_warnings() {
    // Use tests/fixtures/config_validation/valid_config.toml
    let mut cmd = agnix();
    let output = cmd
        .arg("--config")
        .arg("tests/fixtures/config_validation/valid_config.toml")
        .arg("tests/fixtures/valid")
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Valid config should NOT produce "Config warning:" messages
    assert!(
        !stderr.contains("Config warning:"),
        "Valid config should not produce semantic warnings, stderr: {}",
        stderr
    );
}

#[test]
fn test_config_semantic_warnings_go_to_stderr_with_json_output() {
    // Semantic warnings should go to stderr, not corrupt JSON output
    let mut cmd = agnix();
    let output = cmd
        .arg("--config")
        .arg("tests/fixtures/config_validation/invalid_rules.toml")
        .arg("tests/fixtures/valid")
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let _stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Note: Semantic warnings only display for text output per main.rs line 273
    // JSON output suppresses them to avoid corrupting the JSON
    // So this test verifies JSON is still valid
    let json: Result<serde_json::Value, _> = serde_json::from_str(&stdout);
    assert!(
        json.is_ok(),
        "JSON output should be valid even with config that has semantic issues, got: {}",
        stdout
    );

    // The parse warning (if any) goes to stderr, but semantic warnings are suppressed for JSON
    // This is intentional behavior per the implementation
}

// ============================================================================
// i18n / Locale CLI Integration Tests (Issue #207)
// ============================================================================

#[test]
fn test_locale_flag_switches_output_to_spanish() {
    use std::fs;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();
    fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: test-skill\ndescription: Use when testing\n---\nBody",
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--locale")
        .arg("es")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Spanish locale should produce "Validando:" instead of "Validating:"
    assert!(
        stdout.contains("Validando:"),
        "--locale es should produce Spanish output ('Validando:'), got: {}",
        stdout
    );
    assert!(
        !stdout.contains("Validating:"),
        "--locale es should NOT produce English 'Validating:', got: {}",
        stdout
    );
}

#[test]
fn test_locale_flag_switches_output_to_chinese() {
    use std::fs;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();
    fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: test-skill\ndescription: Use when testing\n---\nBody",
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--locale")
        .arg("zh-CN")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Chinese locale should produce the zh-CN translated header
    assert!(
        stdout.contains("\u{6b63}\u{5728}\u{9a8c}\u{8bc1}:"),
        "--locale zh-CN should produce Chinese output, got: {}",
        stdout
    );
}

#[test]
fn test_list_locales_flag_outputs_supported_locales() {
    let mut cmd = agnix();
    let output = cmd.arg("--list-locales").output().unwrap();

    assert!(
        output.status.success(),
        "--list-locales should exit successfully"
    );

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should contain the header
    assert!(
        stdout.contains("Supported locales:"),
        "--list-locales should show 'Supported locales:' header, got: {}",
        stdout
    );

    // Should list all three supported locales
    assert!(
        stdout.contains("en"),
        "--list-locales should list 'en', got: {}",
        stdout
    );
    assert!(
        stdout.contains("es"),
        "--list-locales should list 'es', got: {}",
        stdout
    );
    assert!(
        stdout.contains("zh-CN"),
        "--list-locales should list 'zh-CN', got: {}",
        stdout
    );

    // Should include display names
    assert!(
        stdout.contains("English"),
        "--list-locales should show 'English' display name, got: {}",
        stdout
    );
    assert!(
        stdout.contains("Spanish"),
        "--list-locales should show 'Spanish' display name, got: {}",
        stdout
    );
    assert!(
        stdout.contains("Chinese"),
        "--list-locales should show 'Chinese' display name, got: {}",
        stdout
    );
}

#[test]
fn test_list_locales_exits_without_validation() {
    // --list-locales should print locales and exit, even without a valid path
    let mut cmd = agnix();
    let output = cmd
        .arg("--list-locales")
        .arg("/nonexistent/path/that/does/not/exist")
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "--list-locales should succeed even with nonexistent path"
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("Supported locales:"),
        "--list-locales should print locale list regardless of path, got: {}",
        stdout
    );
}

#[test]
fn test_agnix_locale_env_var_switches_output() {
    use std::fs;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();
    fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: test-skill\ndescription: Use when testing\n---\nBody",
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .env("AGNIX_LOCALE", "es")
        // Clear LANG/LC_ALL to avoid interference
        .env_remove("LANG")
        .env_remove("LC_ALL")
        .arg(temp_dir.path().to_str().unwrap())
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);

    // AGNIX_LOCALE=es should produce Spanish output
    assert!(
        stdout.contains("Validando:"),
        "AGNIX_LOCALE=es should produce Spanish output, got: {}",
        stdout
    );
}

#[test]
fn test_config_file_locale_field() {
    use std::fs;

    let temp_dir = tempfile::tempdir().unwrap();

    // Create a config file with locale = "es"
    let config_path = temp_dir.path().join(".agnix.toml");
    fs::write(
        &config_path,
        "severity = \"Warning\"\ntarget = \"Generic\"\nlocale = \"es\"\nexclude = []\n\n[rules]\n",
    )
    .unwrap();

    // Create a minimal valid fixture
    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();
    fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: test-skill\ndescription: Use when testing\n---\nBody",
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--config")
        .arg(&config_path)
        // Clear env vars so config locale takes effect
        .env_remove("AGNIX_LOCALE")
        .env_remove("LANG")
        .env_remove("LC_ALL")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Config locale = "es" should produce Spanish output
    assert!(
        stdout.contains("Validando:"),
        "Config locale = 'es' should produce Spanish output, got: {}",
        stdout
    );
}

#[test]
fn test_locale_priority_cli_flag_overrides_env_var() {
    use std::fs;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();
    fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: test-skill\ndescription: Use when testing\n---\nBody",
    )
    .unwrap();

    // Set env to Spanish, but CLI flag to English
    let mut cmd = agnix();
    let output = cmd
        .env("AGNIX_LOCALE", "es")
        .env_remove("LANG")
        .env_remove("LC_ALL")
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--locale")
        .arg("en")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);

    // --locale en should override AGNIX_LOCALE=es
    assert!(
        stdout.contains("Validating:"),
        "--locale en should override AGNIX_LOCALE=es, got: {}",
        stdout
    );
    assert!(
        !stdout.contains("Validando:"),
        "--locale en should NOT show Spanish output, got: {}",
        stdout
    );
}

#[test]
fn test_locale_priority_cli_flag_overrides_config() {
    use std::fs;

    let temp_dir = tempfile::tempdir().unwrap();

    // Config file with locale = "es"
    let config_path = temp_dir.path().join(".agnix.toml");
    fs::write(
        &config_path,
        "severity = \"Warning\"\ntarget = \"Generic\"\nlocale = \"es\"\nexclude = []\n\n[rules]\n",
    )
    .unwrap();

    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();
    fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: test-skill\ndescription: Use when testing\n---\nBody",
    )
    .unwrap();

    // CLI flag should override config
    let mut cmd = agnix();
    let output = cmd
        .env_remove("AGNIX_LOCALE")
        .env_remove("LANG")
        .env_remove("LC_ALL")
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--config")
        .arg(&config_path)
        .arg("--locale")
        .arg("en")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);

    // --locale en should override config locale = "es"
    assert!(
        stdout.contains("Validating:"),
        "--locale en should override config locale=es, got: {}",
        stdout
    );
    assert!(
        !stdout.contains("Validando:"),
        "--locale en should NOT show Spanish output when overriding config, got: {}",
        stdout
    );
}

#[test]
fn test_locale_priority_env_var_overrides_config() {
    use std::fs;

    let temp_dir = tempfile::tempdir().unwrap();

    // Config file with locale = "en"
    let config_path = temp_dir.path().join(".agnix.toml");
    fs::write(
        &config_path,
        "severity = \"Warning\"\ntarget = \"Generic\"\nlocale = \"en\"\nexclude = []\n\n[rules]\n",
    )
    .unwrap();

    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();
    fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: test-skill\ndescription: Use when testing\n---\nBody",
    )
    .unwrap();

    // AGNIX_LOCALE=es should be picked up by detect_locale() which runs before
    // config is loaded, so env var takes effect for initial output.
    // However, locale re-initialization happens after config load only when no --locale flag.
    // The priority is: --locale > config > env var (inside detect_locale).
    // Actually per the code: locale::init(cli_locale, None) first, then
    // if cli.locale.is_none() && config.locale.is_some(), re-init with config locale.
    // So config locale overrides env var when no --locale flag is set.
    // This test documents that behavior.
    let mut cmd = agnix();
    let output = cmd
        .env("AGNIX_LOCALE", "es")
        .env_remove("LANG")
        .env_remove("LC_ALL")
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--config")
        .arg(&config_path)
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);

    // When no --locale flag: config locale takes precedence over AGNIX_LOCALE
    // because the code re-initializes locale from config after loading it.
    // The initial locale::init picks up AGNIX_LOCALE but then config overrides it.
    // This verifies the re-initialization logic works.
    assert!(
        stdout.contains("Validating:"),
        "Config locale='en' should override AGNIX_LOCALE=es (no --locale flag), got: {}",
        stdout
    );
}

#[test]
fn test_invalid_locale_warns_and_falls_back_to_english() {
    use std::fs;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();
    fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: test-skill\ndescription: Use when testing\n---\nBody",
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--locale")
        .arg("xx-INVALID")
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should warn about unsupported locale on stderr
    assert!(
        stderr.contains("unsupported locale") || stderr.contains("Warning"),
        "Invalid locale should produce warning on stderr, got stderr: {}",
        stderr
    );

    // Should fall back to English output
    assert!(
        stdout.contains("Validating:"),
        "Invalid locale should fall back to English output, got: {}",
        stdout
    );
}

#[test]
fn test_invalid_locale_in_config_warns_and_falls_back() {
    use std::fs;

    let temp_dir = tempfile::tempdir().unwrap();

    // Config with invalid locale
    let config_path = temp_dir.path().join(".agnix.toml");
    fs::write(
        &config_path,
        "severity = \"Warning\"\ntarget = \"Generic\"\nlocale = \"xx-INVALID\"\nexclude = []\n\n[rules]\n",
    )
    .unwrap();

    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();
    fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: test-skill\ndescription: Use when testing\n---\nBody",
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .env_remove("AGNIX_LOCALE")
        .env_remove("LANG")
        .env_remove("LC_ALL")
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--config")
        .arg(&config_path)
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should warn about unsupported locale
    assert!(
        stderr.contains("unsupported locale") || stderr.contains("Warning"),
        "Invalid config locale should produce warning, got stderr: {}",
        stderr
    );

    // Should fall back to English
    assert!(
        stdout.contains("Validating:"),
        "Invalid config locale should fall back to English, got stdout: {}",
        stdout
    );
}

#[test]
fn test_locale_flag_with_json_output_still_works() {
    use std::fs;

    // Locale flag should not affect JSON structure (JSON always uses keys not messages)
    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skills_dir).unwrap();
    fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: test-skill\ndescription: Use when testing\n---\nBody",
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--locale")
        .arg("es")
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: Result<serde_json::Value, _> = serde_json::from_str(&stdout);
    assert!(
        json.is_ok(),
        "--locale es with --format json should produce valid JSON, got: {}",
        stdout
    );

    let json = json.unwrap();
    assert!(
        json["version"].is_string(),
        "JSON should have version field"
    );
    assert!(
        json["diagnostics"].is_array(),
        "JSON should have diagnostics array"
    );
}

#[test]
fn test_help_shows_locale_flags() {
    let mut cmd = agnix();
    let output = cmd.arg("--help").output().unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(
        stdout.contains("--locale"),
        "Help should show --locale flag, got: {}",
        stdout
    );
    assert!(
        stdout.contains("--list-locales"),
        "Help should show --list-locales flag, got: {}",
        stdout
    );
}

// ============================================================================
// Cross-Crate Autofix Consistency Tests (Issue #285)
// ============================================================================

/// Verify that all major autofix rule families produce fixable diagnostics
/// when run through the CLI.  This is a cross-crate end-to-end smoke test:
/// agnix-rules  ->  agnix-core (validators + fix generation)  ->  agnix-cli.
#[test]
fn test_autofix_rules_json_reports_fixes_available() {
    use std::fs;
    use std::io::Write;

    // Create temp fixtures that trigger fixable rules from each family

    let temp_dir = tempfile::tempdir().unwrap();

    // 1. Skill fixture (AS-004: invalid name -> fixable)
    let skill_dir = temp_dir.path().join("skills").join("test-skill");
    fs::create_dir_all(&skill_dir).unwrap();
    {
        let mut f = fs::File::create(skill_dir.join("SKILL.md")).unwrap();
        write!(
            f,
            "---\nname: Test_Skill\ndescription: Use when testing\n---\nBody"
        )
        .unwrap();
    }

    // 2. Hooks fixture (CC-HK-001: invalid event -> fixable)
    let hooks_dir = temp_dir.path().join(".claude");
    fs::create_dir_all(&hooks_dir).unwrap();
    fs::write(
        hooks_dir.join("settings.json"),
        r#"{
  "hooks": {
    "pretooluse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "echo ok" }
        ]
      }
    ]
  }
}"#,
    )
    .unwrap();

    // 3. Agent fixture (CC-AG-003: invalid model -> fixable)
    let agent_dir = temp_dir.path().join(".claude").join("agents");
    fs::create_dir_all(&agent_dir).unwrap();
    fs::write(
        agent_dir.join("bad-agent.md"),
        "---\nname: bad-agent\ndescription: An agent\nmodel: gpt-4\n---\nBody",
    )
    .unwrap();

    // 4. MCP fixture (MCP-002: invalid jsonrpc version -> fixable)
    fs::write(
        temp_dir.path().join("tools.mcp.json"),
        r#"{"jsonrpc": "1.0", "method": "tools/list", "id": 1}"#,
    )
    .unwrap();

    // Run with --dry-run (text output includes [fixable] markers)
    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--dry-run")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Verify that at least one fixable diagnostic exists from each family
    assert!(
        stdout.contains("[fixable]"),
        "Expected at least one [fixable] diagnostic, got: {}",
        stdout
    );

    // Per-family assertions: each fixture path must produce a [fixable] diagnostic.
    // Rule IDs are not emitted in text output, so we match by fixture path segments.
    let family_markers: &[(&str, &str)] = &[
        ("AS-", "SKILL.md"),
        ("CC-HK-", "settings.json"),
        ("CC-AG-", "bad-agent.md"),
        ("MCP-", ".mcp.json"),
    ];
    for (family, path_marker) in family_markers {
        let has_fixable_in_family = stdout
            .lines()
            .any(|line| line.contains(path_marker) && line.contains("[fixable]"));
        assert!(
            has_fixable_in_family,
            "Expected a [fixable] diagnostic for the {} family (path contains '{}'), got: {}",
            family, path_marker, stdout
        );
    }
    // Verify the summary line reports a non-zero fixable count
    assert!(
        stdout.contains("automatically fixable"),
        "Expected fixable count in summary line, got: {}",
        stdout
    );
}

// ============================================================================
// CLI --fix Integration Tests for Pack 2 Rules (Issue #285)
// ============================================================================

/// CC-SK: Skill name fix (AS-004) via --fix on invalid name
#[test]
fn test_fix_ccsk_invalid_skill_name() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("my-broken-skill");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    {
        let mut f = fs::File::create(&skill_path).unwrap();
        write!(
            f,
            "---\nname: My_Broken_Skill\ndescription: Use when testing\n---\nBody"
        )
        .unwrap();
    }

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--fix")
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "--fix should exit successfully after applying skill name fix"
    );

    let fixed = fs::read_to_string(&skill_path).unwrap();
    assert!(
        fixed.contains("name: my-broken-skill"),
        "AS-004 fix should convert name to kebab-case, got: {}",
        fixed
    );
}

/// CC-HK: Hook event-name fix (CC-HK-001) via --fix on invalid event casing
#[test]
fn test_fix_cchk_invalid_event_name() {
    use std::fs;

    let temp_dir = tempfile::tempdir().unwrap();
    let claude_dir = temp_dir.path().join(".claude");
    fs::create_dir_all(&claude_dir).unwrap();

    let settings_path = claude_dir.join("settings.json");
    fs::write(
        &settings_path,
        r#"{
  "hooks": {
    "pretooluse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "echo test" }
        ]
      }
    ]
  }
}"#,
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--fix")
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "--fix should exit successfully after applying hook event name fix"
    );

    let fixed = fs::read_to_string(&settings_path).unwrap();
    assert!(
        fixed.contains("PreToolUse"),
        "CC-HK-001 fix should correct event name casing, got: {}",
        fixed
    );
}

/// CC-AG: Agent model fix (CC-AG-003) via --fix on invalid model value
#[test]
fn test_fix_ccag_invalid_model() {
    use std::fs;

    let temp_dir = tempfile::tempdir().unwrap();
    let agent_dir = temp_dir.path().join(".claude").join("agents");
    fs::create_dir_all(&agent_dir).unwrap();

    let agent_path = agent_dir.join("test-agent.md");
    fs::write(
        &agent_path,
        "---\nname: test-agent\ndescription: An agent\nmodel: gpt-4\n---\nBody",
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--fix")
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "--fix should exit successfully after applying agent model fix"
    );

    let fixed = fs::read_to_string(&agent_path).unwrap();
    // CC-AG-003 replaces invalid model 'gpt-4' with 'sonnet' (the default valid model)
    assert!(
        !fixed.contains("model: gpt-4"),
        "CC-AG-003 fix should replace invalid model 'gpt-4', got: {}",
        fixed
    );
    assert!(
        fixed.contains("model: sonnet"),
        "CC-AG-003 fix should replace invalid model with 'sonnet', got: {}",
        fixed
    );
}

/// MCP: jsonrpc version fix (MCP-002) via --fix
#[test]
fn test_fix_mcp_invalid_jsonrpc_version() {
    use std::fs;

    let temp_dir = tempfile::tempdir().unwrap();
    let mcp_path = temp_dir.path().join("server.mcp.json");
    fs::write(
        &mcp_path,
        r#"{"jsonrpc": "1.0", "method": "tools/list", "id": 1}"#,
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--fix")
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "--fix should exit successfully after applying jsonrpc version fix"
    );

    let fixed = fs::read_to_string(&mcp_path).unwrap();
    assert!(
        fixed.contains("\"2.0\""),
        "MCP-002 fix should correct jsonrpc version to 2.0, got: {}",
        fixed
    );
}

/// COP/CUR: Copilot scoped instruction file with fixable issue
#[test]
fn test_fix_copilot_scoped_missing_applyto() {
    use std::fs;

    // Create a copilot scoped instructions file.  COP-002 checks for missing
    // applyTo frontmatter in .instructions.md and provides a fix.
    let temp_dir = tempfile::tempdir().unwrap();
    let instructions_dir = temp_dir.path().join(".github").join("instructions");
    fs::create_dir_all(&instructions_dir).unwrap();

    let instr_path = instructions_dir.join("typescript.instructions.md");
    // Use an unknown frontmatter key (`someUnknownKey`) to trip COP-004's
    // delete-line fix. `description` was previously used here but became a
    // recognised key in the v0.43.0 catch-up (PR #748), so it no longer
    // triggers an unknown-key diagnostic.
    fs::write(
        &instr_path,
        "---\nsomeUnknownKey: TypeScript rules\n---\nUse strict TypeScript.",
    )
    .unwrap();

    // Run with --dry-run first to see if this triggers any fixable rule
    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--dry-run")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);

    // The fixture must produce at least one [fixable] diagnostic; fail early
    // so a COP-002 regression (missing fix) does not go unnoticed.
    assert!(
        stdout.contains("[fixable]"),
        "Expected at least one [fixable] copilot diagnostic, got: {}",
        stdout
    );

    let original = fs::read_to_string(&instr_path).unwrap();

    let mut cmd2 = agnix();
    // Note: --fix may still exit non-zero if unfixable diagnostics remain
    // after applying available fixes.  We only assert the file was modified.
    cmd2.arg(temp_dir.path().to_str().unwrap())
        .arg("--fix")
        .output()
        .unwrap();

    let fixed = fs::read_to_string(&instr_path).unwrap();
    // --dry-run reported [fixable] diagnostics, so --fix must modify the file
    assert_ne!(
        fixed, original,
        "Fixable copilot diagnostics should result in file changes after --fix"
    );
}

#[test]
fn test_locale_es_translates_diagnostic_messages() {
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();
    let skills_dir = temp_dir.path().join("skills").join("bad-skill");
    fs::create_dir_all(&skills_dir).unwrap();

    let skill_path = skills_dir.join("SKILL.md");
    let mut file = fs::File::create(&skill_path).unwrap();
    // Invalid name triggers AS-004 error
    writeln!(
        file,
        "---\nname: Bad-Skill\ndescription: test\n---\nContent"
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg(temp_dir.path().to_str().unwrap())
        .arg("--locale")
        .arg("es")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Spanish AS-004 message contains "debe tener" (must have) or
    // the Spanish summary "Encontrados" (Found)
    assert!(
        stdout.contains("Encontrados")
            || stdout.contains("debe tener")
            || stdout.contains("minusculas"),
        "--locale es should produce Spanish diagnostic output, got: {}",
        stdout
    );
}

/// Verify that CLI diagnostic output contains resolved messages, not raw
/// i18n key paths like "rules.as_004.message" or "cli.found_errors_warnings".
#[test]
fn test_no_raw_i18n_keys_in_diagnostic_output() {
    use regex::Regex;
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();

    // Create a skill with an invalid name to trigger AS-004
    let skills_dir = temp_dir.path().join("skills").join("bad-skill");
    fs::create_dir_all(&skills_dir).unwrap();
    let mut file = fs::File::create(skills_dir.join("SKILL.md")).unwrap();
    writeln!(
        file,
        "---\nname: Bad-Skill\ndescription: test\n---\nContent"
    )
    .unwrap();

    // Create a CLAUDE.md with unclosed XML to trigger XML-001
    let mut claude_file = fs::File::create(temp_dir.path().join("CLAUDE.md")).unwrap();
    writeln!(claude_file, "<unclosed>\nSome memory content").unwrap();

    let mut cmd = agnix();
    let output = cmd.arg(temp_dir.path().to_str().unwrap()).output().unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);

    // These patterns match raw i18n key paths that should never appear in output
    let raw_key_patterns = [
        Regex::new(r"\brules\.[a-z_]+_\d+\.message\b").unwrap(),
        Regex::new(r"\brules\.[a-z_]+_\d+\.suggestion\b").unwrap(),
        Regex::new(r"\bcli\.[a-z_]+\b").unwrap(),
        Regex::new(r"\blsp\.[a-z_]+\b").unwrap(),
        Regex::new(r"\bcore\.error\.[a-z_]+\b").unwrap(),
    ];

    for pattern in &raw_key_patterns {
        let matches: Vec<&str> = pattern.find_iter(&stdout).map(|m| m.as_str()).collect();
        assert!(
            matches.is_empty(),
            "Found raw i18n key(s) in CLI output: {:?}\nFull output:\n{}",
            matches,
            stdout
        );
    }

    // Sanity check: output should contain real diagnostic text
    assert!(
        !stdout.is_empty(),
        "CLI should produce diagnostic output for invalid fixtures"
    );
}

/// Verify that JSON format output also contains resolved messages, not raw
/// i18n key paths in the message and suggestion fields.
#[test]
fn test_no_raw_i18n_keys_in_json_output() {
    use regex::Regex;
    use std::fs;
    use std::io::Write;

    let temp_dir = tempfile::tempdir().unwrap();

    // Create a skill with an invalid name to trigger AS-004
    let skills_dir = temp_dir.path().join("skills").join("bad-skill");
    fs::create_dir_all(&skills_dir).unwrap();
    let mut file = fs::File::create(skills_dir.join("SKILL.md")).unwrap();
    writeln!(
        file,
        "---\nname: Bad-Skill\ndescription: test\n---\nContent"
    )
    .unwrap();

    let mut cmd = agnix();
    let output = cmd
        .arg("--format")
        .arg("json")
        .arg(temp_dir.path().to_str().unwrap())
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Parse JSON output and check message/suggestion fields
    let json: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("Failed to parse JSON output: {}\nOutput: {}", e, stdout));

    let raw_key_re = Regex::new(r"^(rules|cli|lsp|core)\.[a-z_]+").unwrap();

    let diagnostics = json
        .get("diagnostics")
        .and_then(|v| v.as_array())
        .expect("JSON output should have a 'diagnostics' array");
    assert!(
        !diagnostics.is_empty(),
        "JSON output should contain at least one diagnostic"
    );

    for diag in diagnostics {
        if let Some(msg) = diag.get("message").and_then(|v| v.as_str()) {
            assert!(
                !raw_key_re.is_match(msg),
                "JSON diagnostic 'message' contains raw i18n key: {}",
                msg
            );
        }
        if let Some(sug) = diag.get("suggestion").and_then(|v| v.as_str()) {
            assert!(
                !raw_key_re.is_match(sug),
                "JSON diagnostic 'suggestion' contains raw i18n key: {}",
                sug
            );
        }
    }
}

#[test]
fn test_cli_nonexistent_path_returns_error() {
    let temp = tempfile::TempDir::new().unwrap();
    let missing = temp.path().join("nonexistent_subdir");

    let mut cmd = agnix();
    cmd.arg(missing.to_str().unwrap())
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("Validation root not found"))
        .stderr(predicate::str::contains(missing.to_str().unwrap()));
}

// Regression test for #723: pre-commit passes the list of changed files as
// positional args. The CLI must accept multiple paths and validate only those
// files rather than rescanning the whole repo.
#[test]
fn test_cli_accepts_multiple_file_paths() {
    let f1 = workspace_path("tests/fixtures/valid/skills/code-review/SKILL.md");
    let f2 = workspace_path("tests/fixtures/valid/skills/deploy-prod/SKILL.md");

    let mut cmd = agnix();
    cmd.arg(f1.to_str().unwrap())
        .arg(f2.to_str().unwrap())
        .arg("--format")
        .arg("json")
        .assert()
        .success();
}

// When multiple file paths are passed we should only validate those files,
// not every matching file under the workspace root.
#[test]
fn test_cli_multiple_paths_scope_to_listed_files() {
    let f1 = workspace_path("tests/fixtures/valid/skills/code-review/SKILL.md");
    let f2 = workspace_path("tests/fixtures/valid/skills/deploy-prod/SKILL.md");

    let mut cmd = agnix();
    let output = cmd
        .arg(f1.to_str().unwrap())
        .arg(f2.to_str().unwrap())
        .arg("--format")
        .arg("json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    // Exactly two files checked -- not a full project walk.
    assert_eq!(
        json["files_checked"].as_u64(),
        Some(2),
        "expected exactly the two passed files to be checked, got: {}",
        stdout
    );
}

// --watch with more than one path should be rejected with the localized error,
// not silently pick one. Ensures we don't regress the ergonomics when someone
// combines --watch with a pre-commit style invocation.
#[test]
fn test_cli_watch_rejects_multiple_paths() {
    let f1 = workspace_path("tests/fixtures/valid/skills/code-review/SKILL.md");
    let f2 = workspace_path("tests/fixtures/valid/skills/deploy-prod/SKILL.md");

    let mut cmd = agnix();
    cmd.arg("--watch")
        .arg(f1.to_str().unwrap())
        .arg(f2.to_str().unwrap())
        .assert()
        .failure()
        .stderr(predicate::str::contains("single path"));
}

// Passing more files than `--max-files` should surface the same TooManyFiles
// error the full project walk emits, so a long pre-commit file list can't
// bypass the DoS guard.
#[test]
fn test_cli_multiple_paths_respect_max_files_limit() {
    let f1 = workspace_path("tests/fixtures/valid/skills/code-review/SKILL.md");
    let f2 = workspace_path("tests/fixtures/valid/skills/deploy-prod/SKILL.md");
    let f3 = workspace_path("tests/fixtures/valid/skills/with-model/SKILL.md");

    let mut cmd = agnix();
    cmd.arg("--max-files")
        .arg("1")
        .arg(f1.to_str().unwrap())
        .arg(f2.to_str().unwrap())
        .arg(f3.to_str().unwrap())
        .assert()
        .failure()
        .stderr(predicate::str::contains("Too many files"));
}