normalize-rules 0.3.1

Rule orchestration and CLI service for normalize (syntax + fact + native + SARIF engines)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
//! Rules management service for server-less CLI.

use normalize_output::OutputFormatter;
use normalize_output::diagnostics::DiagnosticsReport;
use server_less::cli;
use std::cell::Cell;
use std::path::Path;

use normalize_syntax_rules::apply_fixes;

use crate::cmd_rules::run_syntax_rules;
use crate::runner::{
    ListFilters, RuleInfoReport, RuleKind, RulesListReport, RulesRunConfig, RulesTagsReport,
    add_rule, apply_native_rules_config, build_list_report, enable_disable, list_tags_structured,
    remove_rule, run_rules_report, show_rule_structured, update_rules,
};

/// Typed config for summary rules (stale-summary, missing-summary).
/// Deserialized from `extra` fields on the `RuleOverride` via `rule_config()`.
#[derive(serde::Deserialize, Default)]
struct SummaryRuleConfig {
    #[serde(
        default,
        deserialize_with = "normalize_rules_config::deserialize_one_or_many"
    )]
    filenames: Vec<String>,
    #[serde(
        default,
        deserialize_with = "normalize_rules_config::deserialize_one_or_many"
    )]
    paths: Vec<String>,
}

/// Typed config for threshold-based rules (long-file, high-complexity, long-function).
/// Deserialized from `extra` fields on the `RuleOverride` via `rule_config()`.
#[derive(serde::Deserialize, Default)]
struct ThresholdConfig {
    threshold: Option<usize>,
}

/// Resolve pretty mode: enabled on TTY (or forced via --pretty), disabled by --compact.
fn resolve_pretty(pretty: bool, compact: bool) -> bool {
    use std::io::IsTerminal;
    !compact && (pretty || std::io::stdout().is_terminal())
}

/// A single error found when compiling a `.dl` rules file.
#[derive(serde::Serialize, schemars::JsonSchema)]
pub struct CompileError {
    /// 1-based line number in the source file (0 = unknown / not line-specific).
    pub line: usize,
    /// 1-based column number in the source file (0 = unknown).
    pub col: usize,
    /// Human-readable description of the error.
    pub message: String,
}

/// A single warning found when compiling a `.dl` rules file.
#[derive(serde::Serialize, schemars::JsonSchema)]
pub struct CompileWarning {
    /// 1-based line number in the source file (0 = unknown / not line-specific).
    pub line: usize,
    /// 1-based column number in the source file (0 = unknown).
    pub col: usize,
    /// Human-readable description of the warning.
    pub message: String,
}

/// Report returned by `normalize rules compile`.
#[derive(serde::Serialize, schemars::JsonSchema)]
pub struct RulesCompileReport {
    /// Path to the `.dl` file that was checked.
    pub path: String,
    /// `true` if no errors were found; `false` otherwise.
    pub valid: bool,
    /// Hard errors — the program cannot run correctly.
    pub errors: Vec<CompileError>,
    /// Warnings — the program will run but may not behave as expected.
    pub warnings: Vec<CompileWarning>,
    /// All relation names referenced in rule heads or bodies (sorted).
    pub relations_used: Vec<String>,
}

impl OutputFormatter for RulesCompileReport {
    fn format_text(&self) -> String {
        let mut out = String::new();
        for e in &self.errors {
            if e.line > 0 {
                out.push_str(&format!(
                    "{}:{}:{}: error: {}\n",
                    self.path, e.line, e.col, e.message
                ));
            } else {
                out.push_str(&format!("{}: error: {}\n", self.path, e.message));
            }
        }
        for w in &self.warnings {
            if w.line > 0 {
                out.push_str(&format!(
                    "{}:{}:{}: warning: {}\n",
                    self.path, w.line, w.col, w.message
                ));
            } else {
                out.push_str(&format!("{}: warning: {}\n", self.path, w.message));
            }
        }
        if self.valid {
            out.push_str(&format!(
                "{}: ok — {} relation{} used\n",
                self.path,
                self.relations_used.len(),
                if self.relations_used.len() == 1 {
                    ""
                } else {
                    "s"
                },
            ));
        }
        out
    }
}

/// Report returned by `normalize rules validate`.
#[derive(serde::Serialize, schemars::JsonSchema)]
pub struct RulesValidateReport {
    /// Path to the config file that was checked.
    pub config_path: String,
    /// Overall validity — false if any errors were found.
    pub valid: bool,
    /// TOML parse errors or unknown rule IDs.
    pub errors: Vec<String>,
    /// Non-fatal warnings (e.g. disabled rules that have no effect).
    pub warnings: Vec<String>,
    /// Number of per-rule overrides found in the config.
    pub rule_count: usize,
    /// Number of global-allow patterns.
    pub global_allow_count: usize,
}

impl OutputFormatter for RulesValidateReport {
    fn format_text(&self) -> String {
        let mut out = String::new();
        if self.valid {
            out.push_str("Rules configuration is valid\n");
        } else {
            out.push_str("Rules configuration has errors\n");
        }
        out.push('\n');
        out.push_str(&format!("Config file: {}\n", self.config_path));

        if self.valid {
            out.push_str(&format!(
                "  {} rule override{}, {} global-allow pattern{}\n",
                self.rule_count,
                if self.rule_count == 1 { "" } else { "s" },
                self.global_allow_count,
                if self.global_allow_count == 1 {
                    ""
                } else {
                    "s"
                },
            ));
        } else {
            out.push_str(&format!(
                "  {} error{}:\n\n",
                self.errors.len(),
                if self.errors.len() == 1 { "" } else { "s" }
            ));
            for e in &self.errors {
                out.push_str(&format!("  error: {e}\n"));
            }
        }

        if !self.warnings.is_empty() {
            out.push('\n');
            for w in &self.warnings {
                out.push_str(&format!("  warning: {w}\n"));
            }
        }

        out
    }
}

/// One mismatch found during `normalize rules test`.
#[derive(serde::Serialize, schemars::JsonSchema)]
pub struct TestMismatch {
    /// 1-based line number.
    pub line: usize,
    /// Rule ID involved in the mismatch.
    pub rule_id: String,
    /// "expected finding missing" or "unexpected finding"
    pub kind: String,
}

/// Report returned by `normalize rules test`.
#[derive(serde::Serialize, schemars::JsonSchema)]
pub struct RulesTestReport {
    /// Path to the file that was tested.
    pub file: String,
    /// `true` if all assertions passed.
    pub passed: bool,
    /// Number of `// error[...]` annotations found in the file.
    pub annotations: usize,
    /// Number of findings from rule execution.
    pub findings: usize,
    /// List of mismatches (empty when passed = true).
    pub mismatches: Vec<TestMismatch>,
}

impl OutputFormatter for RulesTestReport {
    fn format_text(&self) -> String {
        if self.passed {
            format!(
                "PASS {} ({} annotation(s), {} finding(s))\n",
                self.file, self.annotations, self.findings
            )
        } else {
            let mut out = format!("FAIL {}:\n", self.file);
            for m in &self.mismatches {
                out.push_str(&format!("  line {}: {}{}\n", m.line, m.rule_id, m.kind));
            }
            out
        }
    }

    fn format_pretty(&self) -> String {
        use nu_ansi_term::Color;
        if self.passed {
            format!(
                "{} {} ({} annotation(s), {} finding(s))\n",
                Color::Green.bold().paint("PASS"),
                self.file,
                self.annotations,
                self.findings
            )
        } else {
            let mut out = format!("{} {}:\n", Color::Red.bold().paint("FAIL"), self.file);
            for m in &self.mismatches {
                out.push_str(&format!(
                    "  line {}: {}{}\n",
                    m.line,
                    Color::Yellow.paint(&m.rule_id),
                    m.kind
                ));
            }
            out
        }
    }
}

/// One expected finding in a fixture `expected.json` file.
#[derive(
    Debug,
    Clone,
    serde::Serialize,
    serde::Deserialize,
    schemars::JsonSchema,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
)]
pub struct FixtureExpectedFinding {
    /// Rule ID that should fire (e.g. `rust/unwrap-in-impl`).
    pub rule: String,
    /// Source file path, relative to the fixture's `input/` dir (or the input filename for single-file cases).
    pub file: String,
    /// 1-based line number.
    pub line: usize,
    /// Diagnostic message (substring match — actual message must contain this).
    pub message: String,
}

/// Result for a single fixture case.
#[derive(serde::Serialize, schemars::JsonSchema)]
pub struct FixtureCaseResult {
    /// Case name (directory or file stem).
    pub case: String,
    /// `true` if actual findings matched expected.
    pub passed: bool,
    /// Lines describing mismatches (empty when passed).
    pub diff: Vec<String>,
}

/// Report returned by `normalize rules test-fixtures`.
#[derive(serde::Serialize, schemars::JsonSchema)]
pub struct RulesFixtureTestReport {
    /// Root directory that was scanned for fixtures.
    pub fixture_dir: String,
    /// Results for each discovered case.
    pub cases: Vec<FixtureCaseResult>,
    /// Number of cases that passed.
    pub passed: usize,
    /// Number of cases that failed.
    pub failed: usize,
    /// `true` when run with --update (rewrites expected.json).
    pub updated: bool,
}

impl OutputFormatter for RulesFixtureTestReport {
    fn format_text(&self) -> String {
        let mut out = String::new();
        for c in &self.cases {
            if c.passed {
                out.push_str(&format!("PASS {}\n", c.case));
            } else {
                out.push_str(&format!("FAIL {}:\n", c.case));
                for line in &c.diff {
                    out.push_str(&format!("  {line}\n"));
                }
            }
        }
        if self.updated {
            out.push_str(&format!("\nUpdated {} case(s).\n", self.cases.len()));
        } else {
            out.push_str(&format!(
                "\n{} passed, {} failed\n",
                self.passed, self.failed
            ));
        }
        out
    }

    fn format_pretty(&self) -> String {
        use nu_ansi_term::Color;
        let mut out = String::new();
        for c in &self.cases {
            if c.passed {
                out.push_str(&format!(
                    "{} {}\n",
                    Color::Green.bold().paint("PASS"),
                    c.case
                ));
            } else {
                out.push_str(&format!(
                    "{} {}:\n",
                    Color::Red.bold().paint("FAIL"),
                    c.case
                ));
                for line in &c.diff {
                    out.push_str(&format!("  {}\n", Color::Yellow.paint(line.as_str())));
                }
            }
        }
        if self.updated {
            out.push_str(&format!("\n{} case(s) updated.\n", self.cases.len()));
        } else {
            out.push_str(&format!(
                "\n{} passed, {} failed\n",
                Color::Green.paint(self.passed.to_string()),
                if self.failed > 0 {
                    Color::Red.paint(self.failed.to_string()).to_string()
                } else {
                    "0".to_string()
                }
            ));
        }
        out
    }
}

/// Rules management sub-service.
pub struct RulesService {
    pretty: Cell<bool>,
    /// Set to true when --sarif is active; display_run emits SARIF instead of text.
    sarif: Cell<bool>,
    /// Issue display limit for text output (default 50).
    limit: Cell<usize>,
}

impl RulesService {
    pub fn new(pretty: &Cell<bool>) -> Self {
        Self {
            pretty: Cell::new(pretty.get()),
            sarif: Cell::new(false),
            limit: Cell::new(50),
        }
    }

    fn resolve_format(&self, pretty: bool, compact: bool) {
        self.pretty.set(resolve_pretty(pretty, compact));
    }
}

/// Generic result type for rule operations.
#[derive(serde::Serialize, schemars::JsonSchema)]
pub struct RuleShowReport {
    pub success: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl OutputFormatter for RuleShowReport {
    fn format_text(&self) -> String {
        if let Some(ref msg) = self.message {
            msg.clone()
        } else if self.success {
            "Done".to_string()
        } else {
            "Failed".to_string()
        }
    }
}

impl RulesService {
    /// Generic display bridge that routes to `OutputFormatter::format_text()`.
    fn display_output<T: OutputFormatter>(&self, value: &T) -> String {
        if self.pretty.get() {
            value.format_pretty()
        } else {
            value.format_text()
        }
    }

    fn display_run(&self, r: &DiagnosticsReport) -> String {
        if self.sarif.get() {
            return r.format_sarif();
        }
        if self.pretty.get() {
            r.format_pretty()
        } else {
            r.format_text_limited(Some(self.limit.get()))
        }
    }
}

#[cli(
    name = "rules",
    description = "Manage and run analysis rules (syntax + fact + native)",
    global = [
        pretty = "Human-friendly output with colors and formatting",
        compact = "Compact output without colors (overrides TTY detection)",
    ]
)]
impl RulesService {
    /// List all rules (syntax + fact, builtin + user)
    ///
    /// Examples:
    ///   normalize rules list                   # all rules with status
    ///   normalize rules list --pretty          # with full descriptions
    ///   normalize rules list --json            # machine-readable output
    #[cli(display_with = "display_output")]
    #[allow(clippy::too_many_arguments)]
    pub fn list(
        &self,
        #[param(short = 't', help = "Filter by rule type (all, syntax, fact)")] r#type: Option<
            String,
        >,
        #[param(help = "Filter by tag")] tag: Option<String>,
        #[param(help = "Filter to enabled rules only")] enabled: bool,
        #[param(help = "Filter to disabled rules only")] disabled: bool,
        #[param(short = 'r', help = "Root directory (defaults to current directory)")] root: Option<
            String,
        >,
        pretty: bool,
        compact: bool,
    ) -> Result<RulesListReport, String> {
        let effective_root = root
            .as_deref()
            .map(std::path::PathBuf::from)
            .map(Ok)
            .unwrap_or_else(std::env::current_dir)
            .map_err(|e| format!("Failed to get current directory: {e}"))?;
        self.resolve_format(pretty, compact);
        let config = load_rules_config(&effective_root);
        let rule_type: RuleKind = r#type
            .as_deref()
            .unwrap_or("all")
            .parse()
            .unwrap_or_default();
        let report = build_list_report(
            &effective_root,
            &ListFilters {
                type_filter: &rule_type,
                tag: tag.as_deref(),
                enabled,
                disabled,
            },
            &config,
        );
        Ok(report)
    }

    /// Run rules against the codebase
    ///
    /// Examples:
    ///   normalize rules run                    # run all enabled rules
    ///   normalize rules run src/               # run on specific directory
    ///   normalize rules run --rule rust/unwrap-in-impl   # single rule
    ///   normalize rules run --pretty           # colored output with details
    ///   normalize rules run --type syntax      # only syntax rules
    ///   normalize rules run --only "*.rs"      # only Rust files
    ///   normalize rules run --exclude "tests/" # skip test directories
    ///   normalize rules run --files src/main.rs src/lib.rs  # explicit file list
    #[cli(display_with = "display_run")]
    #[allow(clippy::too_many_arguments)]
    pub async fn run(
        &self,
        #[param(help = "Specific rule ID to run")] rule: Option<String>,
        #[param(help = "Filter by tag")] tag: Option<String>,
        #[param(help = "Apply auto-fixes (syntax rules only)")] fix: bool,
        #[param(help = "Output in SARIF format")] sarif: bool,
        #[param(positional, help = "Target directory or file")] target: Option<String>,
        #[param(
            short = 't',
            help = "Filter by rule type (all, syntax, fact, native, sarif)"
        )]
        r#type: Option<String>,
        #[param(help = "Debug flags (comma-separated)")] debug: Vec<String>,
        #[param(short = 'r', help = "Root directory (defaults to current directory)")] root: Option<
            String,
        >,
        #[param(help = "Exit 0 even when error-severity issues are found")] no_fail: bool,
        #[param(help = "Maximum number of issues to show in detail (default: 50)")] limit: Option<
            usize,
        >,
        #[param(help = "Only include files matching glob patterns")] only: Vec<String>,
        #[param(help = "Exclude files matching glob patterns")] exclude: Vec<String>,
        #[param(help = "Explicit file paths to check (bypasses file walker)")] files: Vec<String>,
        pretty: bool,
        compact: bool,
    ) -> Result<DiagnosticsReport, String> {
        let effective_root = root
            .as_deref()
            .map(std::path::PathBuf::from)
            .map(Ok)
            .unwrap_or_else(std::env::current_dir)
            .map_err(|e| format!("Failed to get current directory: {e}"))?;
        self.resolve_format(pretty, compact);
        self.sarif.set(sarif);
        // Cap limit to prevent accidental OOM from huge values (e.g. usize::MAX).
        let limit = limit.unwrap_or(50).min(10_000);
        self.limit.set(limit);
        let config = load_rules_config(&effective_root);
        let rule_type: RuleKind = r#type
            .as_deref()
            .unwrap_or("all")
            .parse()
            .unwrap_or_default();
        let target_root = target
            .as_deref()
            .map(std::path::PathBuf::from)
            .unwrap_or_else(|| effective_root.clone());
        let project_root = effective_root.clone();

        // Resolve --files to absolute paths (relative to effective_root).
        // When `target` is a single file, treat it as an explicit file too so the
        // daemon can hit the per-file fast path instead of walking from `target_root`.
        let explicit_files: Option<Vec<std::path::PathBuf>> = if files.is_empty() {
            if target_root.is_file() {
                Some(vec![target_root.clone()])
            } else {
                None
            }
        } else {
            Some(
                files
                    .iter()
                    .map(|f| {
                        let p = std::path::PathBuf::from(f);
                        if p.is_absolute() {
                            p
                        } else {
                            effective_root.join(p)
                        }
                    })
                    .collect(),
            )
        };

        // Parse --only / --exclude into a PathFilter early so every engine can
        // skip non-matching files *before* doing expensive work (parsing, walking).
        let path_filter = normalize_rules_config::PathFilter::new(&only, &exclude);

        // --fix path: syntax-only, loop until no fixable issues remain
        if fix {
            let debug_flags = normalize_syntax_rules::DebugFlags::from_args(&debug);
            let fix_filter = path_filter.clone();
            tokio::task::spawn_blocking(move || {
                const MAX_FIX_ITERATIONS: usize = 100;
                let mut total_fixed = 0usize;
                let mut total_files = 0usize;
                let mut iterations = 0usize;
                loop {
                    if iterations >= MAX_FIX_ITERATIONS {
                        eprintln!(
                            "Warning: --fix stopped after {MAX_FIX_ITERATIONS} iterations; \
                             a rule fix may be generating output that still matches the same rule."
                        );
                        break;
                    }
                    iterations += 1;
                    let findings = run_syntax_rules(
                        &target_root,
                        &project_root,
                        rule.as_deref(),
                        tag.as_deref(),
                        None,
                        &config.rules,
                        &debug_flags,
                        explicit_files.as_deref(),
                        &fix_filter,
                        &config.walk,
                    );
                    let fixable_count = findings.iter().filter(|f| f.fix.is_some()).count();
                    if fixable_count == 0 {
                        break;
                    }
                    match apply_fixes(&findings) {
                        Ok(0) => break,
                        Ok(files_modified) => {
                            total_fixed += fixable_count;
                            total_files = files_modified;
                        }
                        Err(e) => return Err(format!("Error applying fixes: {e}")),
                    }
                }
                if total_fixed == 0 {
                    eprintln!("No auto-fixable issues found.");
                } else {
                    println!("Fixed {} issue(s) in {} file(s).", total_fixed, total_files);
                }
                Ok(())
            })
            .await
            .map_err(|e| format!("Task error: {e}"))??;
            return Ok(DiagnosticsReport::new());
        }

        let run_native = matches!(rule_type, RuleKind::All | RuleKind::Native);
        let rule_filter = rule.clone();

        // Syntax + fact + SARIF engines via run_rules_report() (blocking)
        let explicit_files_clone = explicit_files.clone();
        let syntax_filter = path_filter.clone();
        let mut report = tokio::task::spawn_blocking(move || {
            run_rules_report(
                &target_root,
                &project_root,
                rule.as_deref(),
                tag.as_deref(),
                &rule_type,
                &debug,
                &config,
                explicit_files_clone.as_deref(),
                &syntax_filter,
            )
        })
        .await
        .map_err(|e| format!("Task error: {e}"))?;

        // Native engine (missing-summary, stale-summary, check-refs, stale-docs, check-examples,
        // ratchet, budget, long-file, high-complexity, long-function)
        // runs in async context; included in All and Native engine types.
        // All checks are independent — run them in parallel.
        // Skip when daemon already served cached native results.
        if run_native && !report.daemon_cached {
            let native_timings_start = std::time::Instant::now();
            let native_root = effective_root.clone();
            let native_config = load_rules_config(&native_root);
            let threshold = 10;
            let missing_summary_cfg: SummaryRuleConfig = native_config
                .rules
                .rules
                .get("missing-summary")
                .map(|r| r.rule_config())
                .unwrap_or_default();
            let missing_summary_filenames = missing_summary_cfg.filenames;
            let missing_summary_paths = missing_summary_cfg.paths;
            let stale_summary_cfg: SummaryRuleConfig = native_config
                .rules
                .rules
                .get("stale-summary")
                .map(|r| r.rule_config())
                .unwrap_or_default();
            let stale_summary_filenames = stale_summary_cfg.filenames;
            let stale_summary_paths = stale_summary_cfg.paths;

            // Helper: check if a native rule is enabled given config overrides and
            // the descriptor's default_enabled. A `--rule <id>` filter implicitly
            // enables the targeted rule so users can test disabled rules on demand.
            let is_native_enabled = |rule_id: &str| -> bool {
                if rule_filter.as_deref() == Some(rule_id) {
                    return true;
                }
                let desc = normalize_native_rules::NATIVE_RULES
                    .iter()
                    .find(|d| d.id == rule_id);
                let default = desc.map(|d| d.default_enabled).unwrap_or(true);
                native_config
                    .rules
                    .rules
                    .get(rule_id)
                    .and_then(|o| o.enabled)
                    .unwrap_or(default)
            };

            let run_long_file = is_native_enabled("long-file");
            let run_high_complexity = is_native_enabled("high-complexity");
            let run_long_function = is_native_enabled("long-function");
            let run_stale_doc = is_native_enabled("stale-doc");
            let run_boundary_violations = is_native_enabled("boundary-violations");
            let run_high_fan_out = is_native_enabled("high-fan-out");
            let run_high_fan_in = is_native_enabled("high-fan-in");
            let run_dead_parameter = is_native_enabled("dead-parameter");

            let boundary_cfg: normalize_native_rules::BoundaryViolationsConfig = native_config
                .rules
                .rules
                .get("boundary-violations")
                .map(|r| r.rule_config())
                .unwrap_or_default();
            let boundaries: Vec<normalize_native_rules::Boundary> = boundary_cfg
                .boundaries
                .iter()
                .filter_map(|s| normalize_native_rules::parse_boundary(s))
                .collect();

            let long_file_threshold: usize = native_config
                .rules
                .rules
                .get("long-file")
                .map(|r| r.rule_config::<ThresholdConfig>())
                .and_then(|c| c.threshold)
                .unwrap_or(500);
            let long_file_allow: Vec<String> = native_config
                .rules
                .rules
                .get("long-file")
                .map(|r| r.allow.clone())
                .unwrap_or_default();
            let high_complexity_threshold: usize = native_config
                .rules
                .rules
                .get("high-complexity")
                .map(|r| r.rule_config::<ThresholdConfig>())
                .and_then(|c| c.threshold)
                .unwrap_or(20);
            let long_function_threshold: usize = native_config
                .rules
                .rules
                .get("long-function")
                .map(|r| r.rule_config::<ThresholdConfig>())
                .and_then(|c| c.threshold)
                .unwrap_or(100);
            let high_fan_out_threshold: usize = native_config
                .rules
                .rules
                .get("high-fan-out")
                .map(|r| r.rule_config::<ThresholdConfig>())
                .and_then(|c| c.threshold)
                .unwrap_or(20);
            let high_fan_in_threshold: usize = native_config
                .rules
                .rules
                .get("high-fan-in")
                .map(|r| r.rule_config::<ThresholdConfig>())
                .and_then(|c| c.threshold)
                .unwrap_or(20);

            let stale_doc_cfg: normalize_native_rules::StaleDocConfig = native_config
                .rules
                .rules
                .get("stale-doc")
                .map(|r| r.rule_config())
                .unwrap_or_default();

            // Compute effective_files concurrently with group-1 rules so advisory
            // rules (group 2) can start immediately after group 1 finishes rather
            // than waiting for a sequential file walk.
            let effective_files_future = {
                let root = native_root.clone();
                let pf = path_filter.clone();
                let ef = explicit_files.clone();
                let wc = native_config.walk.clone();
                tokio::task::spawn_blocking(move || -> Option<Vec<std::path::PathBuf>> {
                    if !pf.is_empty() {
                        if let Some(ef) = ef {
                            Some(
                                ef.into_iter()
                                    .filter(|p| {
                                        let rel = p.strip_prefix(&root).unwrap_or(p);
                                        pf.matches_path(rel)
                                    })
                                    .collect(),
                            )
                        } else {
                            // Walk once, filtering by PathFilter, and share the list
                            // across all advisory rules.
                            Some(
                                normalize_native_rules::walk::filtered_gitignore_walk(
                                    &root, &pf, &wc,
                                )
                                .filter(|e| e.path().is_file())
                                .map(|e| e.path().to_path_buf())
                                .collect(),
                            )
                        }
                    } else {
                        None
                    }
                })
            };

            let (
                missing_res,
                summary_res,
                stale_res,
                examples_res,
                refs_res,
                ratchet_res,
                budget_res,
                effective_files_res,
            ) = tokio::join!(
                tokio::task::spawn_blocking({
                    let root = native_root.clone();
                    let wc = native_config.walk.clone();
                    move || {
                        let t = std::time::Instant::now();
                        let r = normalize_native_rules::build_missing_summary_report(
                            &root,
                            threshold,
                            &missing_summary_filenames,
                            &missing_summary_paths,
                            &wc,
                        );
                        eprintln!("[timings] missing-summary: {:.1?}", t.elapsed());
                        r
                    }
                }),
                tokio::task::spawn_blocking({
                    let root = native_root.clone();
                    let wc = native_config.walk.clone();
                    move || {
                        let t = std::time::Instant::now();
                        let r = normalize_native_rules::build_stale_summary_report(
                            &root,
                            threshold,
                            &stale_summary_filenames,
                            &stale_summary_paths,
                            &wc,
                        );
                        eprintln!("[timings] stale-summary: {:.1?}", t.elapsed());
                        r
                    }
                }),
                tokio::task::spawn_blocking({
                    let root = native_root.clone();
                    let wc = native_config.walk.clone();
                    move || {
                        let t = std::time::Instant::now();
                        let r = normalize_native_rules::build_stale_docs_report(&root, &wc);
                        eprintln!("[timings] stale-docs: {:.1?}", t.elapsed());
                        r
                    }
                }),
                tokio::task::spawn_blocking({
                    let root = native_root.clone();
                    let wc = native_config.walk.clone();
                    move || {
                        let t = std::time::Instant::now();
                        let r = normalize_native_rules::build_check_examples_report(&root, &wc);
                        eprintln!("[timings] check-examples: {:.1?}", t.elapsed());
                        r
                    }
                }),
                async {
                    let t = std::time::Instant::now();
                    let r = normalize_native_rules::build_check_refs_report(
                        &native_root,
                        &native_config.walk,
                    )
                    .await;
                    eprintln!("[timings] check-refs: {:.1?}", t.elapsed());
                    r
                },
                tokio::task::spawn_blocking({
                    let root = native_root.clone();
                    move || {
                        let t = std::time::Instant::now();
                        let r = normalize_native_rules::build_ratchet_report(&root);
                        eprintln!("[timings] ratchet: {:.1?}", t.elapsed());
                        r
                    }
                }),
                tokio::task::spawn_blocking({
                    let root = native_root.clone();
                    move || {
                        let t = std::time::Instant::now();
                        let r = normalize_native_rules::build_budget_report(&root);
                        eprintln!("[timings] budget: {:.1?}", t.elapsed());
                        r
                    }
                }),
                effective_files_future,
            );

            // Unwrap effective_files; fall back to explicit_files if the walk task failed.
            let effective_files: Option<Vec<std::path::PathBuf>> = effective_files_res
                .ok()
                .flatten()
                .or_else(|| explicit_files.clone());

            // Track how many issues existed before adding native results so
            // global_allow filtering only touches the newly added native issues.
            let native_start = report.issues.len();

            if let Ok(r) = missing_res {
                report.merge(r.into());
            }
            if let Ok(r) = summary_res {
                report.merge(r.into());
            }
            if let Ok(r) = stale_res {
                report.merge(r.into());
            }
            if let Ok(r) = examples_res {
                report.merge(r.into());
            }
            if let Ok(r) = refs_res {
                report.merge(r.into());
            }
            if let Ok(r) = ratchet_res {
                report.merge(r.into());
            }
            if let Ok(r) = budget_res {
                report.merge(r.into());
            }

            // Advisory rules (default disabled — only run when explicitly enabled).
            // long-file / high-complexity / long-function are tree-sitter-heavy.
            // dead-parameter uses the scope engine (locals.scm queries).
            // stale-doc, boundary-violations, high-fan-out, and high-fan-in require the index.
            let (
                long_file_res,
                high_complexity_res,
                long_function_res,
                stale_doc_res,
                boundary_violations_res,
                high_fan_out_res,
                high_fan_in_res,
                dead_parameter_res,
            ) = tokio::join!(
                async {
                    if !run_long_file {
                        return None;
                    }
                    let root = native_root.clone();
                    let threshold = long_file_threshold;
                    let allow = long_file_allow.clone();
                    let ef = effective_files.clone();
                    let wc = native_config.walk.clone();
                    let t = std::time::Instant::now();
                    let r = tokio::task::spawn_blocking(move || {
                        normalize_native_rules::build_long_file_report(
                            &root,
                            threshold,
                            ef.as_deref(),
                            &wc,
                            &allow,
                        )
                    })
                    .await
                    .ok();
                    eprintln!("[timings] long-file: {:.1?}", t.elapsed());
                    r
                },
                async {
                    if !run_high_complexity {
                        return None;
                    }
                    let root = native_root.clone();
                    let threshold = high_complexity_threshold;
                    let ef = effective_files.clone();
                    let wc = native_config.walk.clone();
                    let t = std::time::Instant::now();
                    let r = tokio::task::spawn_blocking(move || {
                        normalize_native_rules::build_high_complexity_report(
                            &root,
                            threshold,
                            ef.as_deref(),
                            &wc,
                        )
                    })
                    .await
                    .ok();
                    eprintln!("[timings] high-complexity: {:.1?}", t.elapsed());
                    r
                },
                async {
                    if !run_long_function {
                        return None;
                    }
                    let root = native_root.clone();
                    let threshold = long_function_threshold;
                    let ef = effective_files.clone();
                    let wc = native_config.walk.clone();
                    let t = std::time::Instant::now();
                    let r = tokio::task::spawn_blocking(move || {
                        normalize_native_rules::build_long_function_report(
                            &root,
                            threshold,
                            ef.as_deref(),
                            &wc,
                        )
                    })
                    .await
                    .ok();
                    eprintln!("[timings] long-function: {:.1?}", t.elapsed());
                    r
                },
                async {
                    if !run_stale_doc {
                        return None;
                    }
                    let root = native_root.clone();
                    let cfg = stale_doc_cfg;
                    let ef = effective_files.clone();
                    let t = std::time::Instant::now();
                    let r = tokio::task::spawn_blocking(move || {
                        normalize_native_rules::build_stale_doc_report(&root, cfg, ef.as_deref())
                    })
                    .await
                    .ok();
                    eprintln!("[timings] stale-doc: {:.1?}", t.elapsed());
                    r
                },
                async {
                    if !run_boundary_violations {
                        return None;
                    }
                    let root = native_root.clone();
                    let t = std::time::Instant::now();
                    let r = normalize_native_rules::build_boundary_violations_report(
                        &root,
                        &boundaries,
                    )
                    .await;
                    eprintln!("[timings] boundary-violations: {:.1?}", t.elapsed());
                    Some(r)
                },
                async {
                    if !run_high_fan_out {
                        return None;
                    }
                    let root = native_root.clone();
                    let threshold = high_fan_out_threshold;
                    let t = std::time::Instant::now();
                    let r =
                        normalize_native_rules::build_high_fan_out_report(&root, threshold).await;
                    eprintln!("[timings] high-fan-out: {:.1?}", t.elapsed());
                    Some(r)
                },
                async {
                    if !run_high_fan_in {
                        return None;
                    }
                    let root = native_root.clone();
                    let threshold = high_fan_in_threshold;
                    let t = std::time::Instant::now();
                    let r =
                        normalize_native_rules::build_high_fan_in_report(&root, threshold).await;
                    eprintln!("[timings] high-fan-in: {:.1?}", t.elapsed());
                    Some(r)
                },
                async {
                    if !run_dead_parameter {
                        return None;
                    }
                    let root = native_root.clone();
                    let ef = effective_files.clone();
                    let wc = native_config.walk.clone();
                    let t = std::time::Instant::now();
                    let r = tokio::task::spawn_blocking(move || {
                        normalize_native_rules::build_dead_parameter_report(
                            &root,
                            ef.as_deref(),
                            &wc,
                        )
                    })
                    .await
                    .ok();
                    eprintln!("[timings] dead-parameter: {:.1?}", t.elapsed());
                    r
                },
            );

            if let Some(r) = long_file_res {
                report.merge(r);
            }
            if let Some(r) = high_complexity_res {
                report.merge(r);
            }
            if let Some(r) = long_function_res {
                report.merge(r);
            }
            if let Some(r) = stale_doc_res {
                report.merge(r);
            }
            if let Some(r) = boundary_violations_res {
                report.merge(r);
            }
            if let Some(r) = high_fan_out_res {
                report.merge(r);
            }
            if let Some(r) = high_fan_in_res {
                report.merge(r);
            }
            if let Some(r) = dead_parameter_res {
                report.merge(r);
            }

            // Apply global_allow patterns to native-rule issues (syntax/fact rules
            // apply global_allow during their own execution; native rules need it here).
            let global_allow: Vec<glob::Pattern> = native_config
                .rules
                .global_allow
                .iter()
                .filter_map(|s| glob::Pattern::new(s).ok())
                .collect();
            if !global_allow.is_empty() {
                let mut keep_idx = 0usize;
                report.issues.retain(|issue| {
                    let idx = keep_idx;
                    keep_idx += 1;
                    if idx < native_start {
                        // pre-existing syntax/fact issue — already filtered, keep it
                        return true;
                    }
                    !global_allow.iter().any(|p| p.matches(&issue.file))
                });
            }
            apply_native_rules_config(&mut report, &native_config.rules);
            tracing::debug!(
                "[timings] total native: {:.1?}",
                native_timings_start.elapsed()
            );
            report.sources_run.push("native".into());
        }

        // Apply --rule filter across all engines (syntax/fact already filter internally,
        // but native engine produces all its issues unconditionally).
        if let Some(ref filter) = rule_filter {
            report
                .issues
                .retain(|issue| issue.rule_id == filter.as_str());
        }

        // Safety-net: apply --only / --exclude path filters to all issues post-walk.
        // The pre-walk filter handles syntax and advisory native rules; this catches
        // engines that don't support pre-walk filtering (fact rules, non-advisory native).
        if !path_filter.is_empty() {
            report
                .issues
                .retain(|issue| path_filter.matches(issue.file.as_str()));
            let unique_files: std::collections::HashSet<&str> =
                report.issues.iter().map(|i| i.file.as_str()).collect();
            report.files_checked = unique_files.len();
        }

        report.sort();

        let error_count = report.count_by_severity(normalize_output::diagnostics::Severity::Error);
        if !no_fail && error_count > 0 {
            let detail = self.display_run(&report);
            return Err(format!("{detail}\n{error_count} error(s) found"));
        }

        Ok(report)
    }

    /// Enable a rule or all rules matching a tag
    ///
    /// Examples:
    ///   normalize rules enable python/bare-except   # enable a specific rule
    ///   normalize rules enable --tag correctness    # enable all correctness rules
    #[cli(display_with = "display_output")]
    pub fn enable(
        &self,
        #[param(positional, help = "Rule ID or tag name")] id_or_tag: String,
        #[param(help = "Preview changes without writing")] dry_run: bool,
        #[param(short = 'r', help = "Root directory (defaults to current directory)")] root: Option<
            String,
        >,
    ) -> Result<RuleShowReport, String> {
        let effective_root = root
            .as_deref()
            .map(std::path::PathBuf::from)
            .map(Ok)
            .unwrap_or_else(std::env::current_dir)
            .map_err(|e| format!("Failed to get current directory: {e}"))?;
        let config = load_rules_config(&effective_root);
        enable_disable(&effective_root, &id_or_tag, true, dry_run, &config).map(|msg| {
            RuleShowReport {
                success: true,
                message: Some(msg),
            }
        })
    }

    /// Disable a rule or all rules matching a tag
    ///
    /// Examples:
    ///   normalize rules disable no-todo-comment     # disable a specific rule
    #[cli(display_with = "display_output")]
    pub fn disable(
        &self,
        #[param(positional, help = "Rule ID or tag name")] id_or_tag: String,
        #[param(help = "Preview changes without writing")] dry_run: bool,
        #[param(short = 'r', help = "Root directory (defaults to current directory)")] root: Option<
            String,
        >,
    ) -> Result<RuleShowReport, String> {
        let effective_root = root
            .as_deref()
            .map(std::path::PathBuf::from)
            .map(Ok)
            .unwrap_or_else(std::env::current_dir)
            .map_err(|e| format!("Failed to get current directory: {e}"))?;
        let config = load_rules_config(&effective_root);
        enable_disable(&effective_root, &id_or_tag, false, dry_run, &config).map(|msg| {
            RuleShowReport {
                success: true,
                message: Some(msg),
            }
        })
    }

    /// Show full documentation for a rule
    ///
    /// Examples:
    ///   normalize rules show rust/unwrap-in-impl    # full docs for a rule
    #[cli(display_with = "display_output")]
    pub fn show(
        &self,
        #[param(positional, help = "Rule ID to show")] id: String,
        #[param(short = 'r', help = "Root directory (defaults to current directory)")] root: Option<
            String,
        >,
        pretty: bool,
        compact: bool,
    ) -> Result<RuleInfoReport, String> {
        let effective_root = root
            .as_deref()
            .map(std::path::PathBuf::from)
            .map(Ok)
            .unwrap_or_else(std::env::current_dir)
            .map_err(|e| format!("Failed to get current directory: {e}"))?;
        self.resolve_format(pretty, compact);
        let config = load_rules_config(&effective_root);
        show_rule_structured(&effective_root, &id, &config)
    }

    /// List all tags and the rules they group
    ///
    /// Examples:
    ///   normalize rules tags                   # list all tags with rule counts
    #[cli(display_with = "display_output")]
    pub fn tags(
        &self,
        #[param(help = "Show only this specific tag")] tag: Option<String>,
        #[param(short = 'r', help = "Root directory (defaults to current directory)")] root: Option<
            String,
        >,
        pretty: bool,
        compact: bool,
    ) -> Result<RulesTagsReport, String> {
        let effective_root = root
            .as_deref()
            .map(std::path::PathBuf::from)
            .map(Ok)
            .unwrap_or_else(std::env::current_dir)
            .map_err(|e| format!("Failed to get current directory: {e}"))?;
        self.resolve_format(pretty, compact);
        let config = load_rules_config(&effective_root);
        list_tags_structured(&effective_root, tag.as_deref(), &config)
    }

    /// Add a rule from a URL
    ///
    /// Examples:
    ///   normalize rules add https://example.com/rule.scm   # import a rule from URL
    #[cli(display_with = "display_output")]
    pub fn add(
        &self,
        #[param(positional, help = "URL to download the rule from")] url: String,
        #[param(help = "Install to global rules instead of project")] global: bool,
    ) -> Result<RuleShowReport, String> {
        add_rule(&url, global).map(|_| RuleShowReport {
            success: true,
            message: None,
        })
    }

    /// Update imported rules from their sources
    #[cli(display_with = "display_output")]
    pub fn update(
        &self,
        #[param(
            positional,
            help = "Specific rule ID to update (updates all if omitted)"
        )]
        rule_id: Option<String>,
    ) -> Result<RuleShowReport, String> {
        update_rules(rule_id.as_deref()).map(|_| RuleShowReport {
            success: true,
            message: None,
        })
    }

    /// Remove an imported rule
    #[cli(display_with = "display_output")]
    pub fn remove(
        &self,
        #[param(positional, help = "Rule ID to remove")] rule_id: String,
    ) -> Result<RuleShowReport, String> {
        remove_rule(&rule_id).map(|_| RuleShowReport {
            success: true,
            message: None,
        })
    }

    /// Interactive setup wizard — run all rules and walk through enable/disable decisions
    ///
    /// Examples:
    ///   normalize rules setup                    # interactive rule configuration
    #[cli(display_with = "display_output")]
    pub fn setup(
        &self,
        #[param(short = 'r', help = "Root directory (defaults to current directory)")] root: Option<
            String,
        >,
    ) -> Result<RuleShowReport, String> {
        let effective_root = root
            .as_deref()
            .map(std::path::PathBuf::from)
            .map(Ok)
            .unwrap_or_else(std::env::current_dir)
            .map_err(|e| format!("Failed to get current directory: {e}"))?;
        let exit_code = crate::setup::run_setup_wizard(&effective_root);
        if exit_code == 0 {
            Ok(RuleShowReport {
                success: true,
                message: None,
            })
        } else {
            Err("Setup wizard failed".to_string())
        }
    }

    /// Validate the rules configuration — check rule IDs, TOML syntax, and report issues
    ///
    /// Examples:
    ///   normalize rules validate               # check rule config for errors
    #[cli(display_with = "display_output")]
    pub fn validate(
        &self,
        #[param(short = 'r', help = "Root directory (defaults to current directory)")] root: Option<
            String,
        >,
        pretty: bool,
        compact: bool,
    ) -> Result<RulesValidateReport, String> {
        let effective_root = root
            .as_deref()
            .map(std::path::PathBuf::from)
            .map(Ok)
            .unwrap_or_else(std::env::current_dir)
            .map_err(|e| format!("Failed to get current directory: {e}"))?;
        self.pretty.set(resolve_pretty(pretty, compact));

        let config_file = effective_root.join(".normalize").join("config.toml");
        let config_path = if config_file.exists() {
            ".normalize/config.toml".to_string()
        } else {
            "(not found — using defaults)".to_string()
        };

        let mut errors: Vec<String> = Vec::new();

        // Check for TOML parse errors directly (load_rules_config silently swallows them)
        if config_file.exists() {
            let raw = std::fs::read_to_string(&config_file)
                .map_err(|e| format!("Failed to read config: {e}"))?;
            if let Err(e) = toml::from_str::<toml::Value>(&raw) {
                errors.push(format!("TOML parse error: {e}"));
                return Ok(RulesValidateReport {
                    config_path,
                    valid: false,
                    errors,
                    warnings: Vec::new(),
                    rule_count: 0,
                    global_allow_count: 0,
                });
            }
        }

        // Load effective config
        let config = load_rules_config(&effective_root);
        let rules_cfg = &config.rules;

        let rule_count = rules_cfg.rules.len();
        let global_allow_count = rules_cfg.global_allow.len();

        // Build list of known rule IDs by querying all rule engines
        let list_report = build_list_report(
            &effective_root,
            &ListFilters {
                type_filter: &RuleKind::All,
                tag: None,
                enabled: false,
                disabled: false,
            },
            &config,
        );
        let known_ids: std::collections::HashSet<String> =
            list_report.rules.iter().map(|r| r.id.clone()).collect();

        // Check each configured rule ID against known rules
        for rule_id in rules_cfg.rules.keys() {
            if !known_ids.contains(rule_id) {
                errors.push(format!(
                    "unknown rule ID \"{rule_id}\" — run 'normalize rules list' to see available rules"
                ));
            }
        }

        let valid = errors.is_empty();

        let report = RulesValidateReport {
            config_path,
            valid,
            errors,
            warnings: Vec::new(),
            rule_count,
            global_allow_count,
        };

        Ok(report)
    }

    /// Validate and "compile" a Datalog rules file — check syntax and relation names
    ///
    /// Parses the `.dl` file, validates that all referenced relations are declared (or
    /// are built-in), and reports errors with file/line context.  Exits with status 1
    /// when errors are found so it can be used in CI pipelines.
    ///
    /// Examples:
    ///   normalize rules compile my-rule.dl       # check a single rule file
    ///   normalize rules compile .normalize/rules/arch.dl --json  # machine-readable output
    #[cli(display_with = "display_output")]
    pub fn compile(
        &self,
        #[param(positional, help = "Path to the .dl file to validate")] path: String,
        #[param(short = 'r', help = "Root directory (defaults to current directory)")] root: Option<
            String,
        >,
        pretty: bool,
        compact: bool,
    ) -> Result<RulesCompileReport, String> {
        use normalize_facts_rules_interpret::{compile_rules_source, parse_rule_content};

        self.resolve_format(pretty, compact);

        let effective_root = root
            .as_deref()
            .map(std::path::PathBuf::from)
            .map(Ok)
            .unwrap_or_else(std::env::current_dir)
            .map_err(|e| format!("Failed to get current directory: {e}"))?;

        let dl_path = if std::path::Path::new(&path).is_absolute() {
            std::path::PathBuf::from(&path)
        } else {
            effective_root.join(&path)
        };

        let content = std::fs::read_to_string(&dl_path)
            .map_err(|e| format!("Failed to read '{}': {e}", dl_path.display()))?;

        // Strip frontmatter to get the Datalog source body
        let default_id = dl_path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("rule");
        let rule = parse_rule_content(&content, default_id, false);
        let source = rule.as_ref().map(|r| r.source.as_str()).unwrap_or(&content);

        let compile_result = compile_rules_source(source);

        let errors: Vec<CompileError> = compile_result
            .errors
            .into_iter()
            .map(|e| CompileError {
                line: e.line,
                col: e.col,
                message: e.message,
            })
            .collect();

        let warnings: Vec<CompileWarning> = compile_result
            .warnings
            .into_iter()
            .map(|w| CompileWarning {
                line: w.line,
                col: w.col,
                message: w.message,
            })
            .collect();

        let valid = errors.is_empty();

        let report = RulesCompileReport {
            path,
            valid,
            errors,
            warnings,
            relations_used: compile_result.relations_used,
        };

        if report.valid {
            Ok(report)
        } else {
            // Signal failure to the CLI via Err so the process exits with status 1.
            // The formatted output is passed as the error string so it appears on stderr.
            Err(self.display_output(&report))
        }
    }

    /// Test a source file against inline `// error[rule-id]` annotations.
    ///
    /// Runs all enabled syntax rules against the file and checks that:
    ///   - Every `// error[rule-id]` annotation has a matching finding on that line
    ///   - Every finding has a corresponding annotation
    ///
    /// Exits with code 1 if any assertion fails.
    ///
    /// Examples:
    ///   normalize rules test src/lib.rs          # test a file
    ///   normalize rules test tests/fixture.rs    # test a fixture file
    #[cli(display_with = "display_output")]
    pub fn test(
        &self,
        #[param(positional, help = "Path to the source file to test")] file: String,
        #[param(short = 'r', help = "Root directory (defaults to current directory)")] root: Option<
            String,
        >,
        pretty: bool,
        compact: bool,
    ) -> Result<RulesTestReport, String> {
        self.resolve_format(pretty, compact);

        let effective_root = root
            .as_deref()
            .map(std::path::PathBuf::from)
            .map(Ok)
            .unwrap_or_else(std::env::current_dir)
            .map_err(|e| format!("Failed to get current directory: {e}"))?;

        let file_path = if std::path::Path::new(&file).is_absolute() {
            std::path::PathBuf::from(&file)
        } else {
            effective_root.join(&file)
        };

        let content = std::fs::read_to_string(&file_path)
            .map_err(|e| format!("Failed to read '{}': {e}", file_path.display()))?;

        // Parse inline annotations: scan for `error[rule-id]` patterns (language-agnostic).
        // Collect (line_number, rule_id) pairs; line numbers are 1-based.
        let mut annotations: Vec<(usize, String)> = Vec::new();
        for (idx, line) in content.lines().enumerate() {
            let line_no = idx + 1;
            let mut search = line;
            loop {
                let Some(pos) = search.find("error[") else {
                    break;
                };
                let after = &search[pos + "error[".len()..];
                let Some(end) = after.find(']') else {
                    break;
                };
                let rule_id = &after[..end];
                if !rule_id.is_empty() {
                    annotations.push((line_no, rule_id.to_string()));
                }
                // Advance past this match to find further annotations on the same line.
                search = &search[pos + "error[".len() + end + 1..];
            }
        }

        let config = load_rules_config(&effective_root);
        let debug_flags = normalize_syntax_rules::DebugFlags::default();
        let path_filter = normalize_rules_config::PathFilter::new(&[], &[]);
        let findings = run_syntax_rules(
            &effective_root,
            &effective_root,
            None,
            None,
            None,
            &config.rules,
            &debug_flags,
            Some(std::slice::from_ref(&file_path)),
            &path_filter,
            &config.walk,
        );

        let annotation_count = annotations.len();
        let finding_count = findings.len();

        // Build sets for bidirectional comparison.
        // Key: (line, rule_id)
        let annotation_set: std::collections::HashSet<(usize, String)> =
            annotations.into_iter().collect();
        let finding_set: std::collections::HashSet<(usize, String)> = findings
            .iter()
            .map(|f| (f.start_line, f.rule_id.clone()))
            .collect();

        let mut mismatches: Vec<TestMismatch> = Vec::new();

        // Findings without a matching annotation → "unexpected finding"
        let mut unexpected: Vec<(usize, String)> = finding_set
            .iter()
            .filter(|k| !annotation_set.contains(*k))
            .cloned()
            .collect();
        unexpected.sort();
        for (line, rule_id) in unexpected {
            mismatches.push(TestMismatch {
                line,
                rule_id,
                kind: "unexpected finding".to_string(),
            });
        }

        // Annotations without a matching finding → "expected finding missing"
        let mut missing: Vec<(usize, String)> = annotation_set
            .iter()
            .filter(|k| !finding_set.contains(*k))
            .cloned()
            .collect();
        missing.sort();
        for (line, rule_id) in missing {
            mismatches.push(TestMismatch {
                line,
                rule_id,
                kind: "expected finding missing".to_string(),
            });
        }

        mismatches.sort_by_key(|m| (m.line, m.rule_id.clone()));

        let passed = mismatches.is_empty();
        let report = RulesTestReport {
            file,
            passed,
            annotations: annotation_count,
            findings: finding_count,
            mismatches,
        };

        if passed {
            Ok(report)
        } else {
            let n = report.mismatches.len();
            let detail = self.display_output(&report);
            Err(format!("{detail}\n{n} test failure(s)"))
        }
    }

    /// Run fixture-based tests for rules.
    ///
    /// Discovers fixture cases under `fixture_dir` (defaults to `.normalize/rule-tests/`).
    ///
    /// **Single-file format** (flat, one file per case):
    /// ```text
    /// <fixture-dir>/
    ///   case-name.input.rs          # input source file
    ///   case-name.expected.json     # expected findings array
    /// ```
    ///
    /// **Multi-file format** (one subdirectory per case):
    /// ```text
    /// <fixture-dir>/
    ///   case-name/
    ///     input/
    ///       main.rs                 # one or more input files
    ///       helper.rs
    ///     expected.json             # expected findings array
    /// ```
    ///
    /// The `expected.json` file is an array of objects:
    /// ```json
    /// [{"rule": "rust/no-todo-comment", "file": "main.rs", "line": 3, "message": "TODO"}]
    /// ```
    ///
    /// `message` is a **substring match** — the actual diagnostic message only needs to
    /// contain the expected string.
    ///
    /// With `--update` the actual findings are written back to `expected.json`, making it
    /// easy to bootstrap a new fixture case.
    ///
    /// Examples:
    ///   normalize rules test-fixtures                           # scan .normalize/rule-tests/
    ///   normalize rules test-fixtures --fixture-dir tests/rules # custom dir
    ///   normalize rules test-fixtures --update                  # overwrite expected.json
    #[cli(display_with = "display_output")]
    pub fn test_fixtures(
        &self,
        #[param(
            short = 'd',
            help = "Directory containing fixture cases (default: .normalize/rule-tests/)"
        )]
        fixture_dir: Option<String>,
        #[param(help = "Overwrite expected.json with actual findings (bootstrap mode)")]
        update: bool,
        #[param(short = 'r', help = "Root directory (defaults to current directory)")] root: Option<
            String,
        >,
        pretty: bool,
        compact: bool,
    ) -> Result<RulesFixtureTestReport, String> {
        self.resolve_format(pretty, compact);

        let effective_root = root
            .as_deref()
            .map(std::path::PathBuf::from)
            .map(Ok)
            .unwrap_or_else(std::env::current_dir)
            .map_err(|e| format!("Failed to get current directory: {e}"))?;

        let fixture_root = match fixture_dir {
            Some(ref d) => {
                let p = std::path::Path::new(d);
                if p.is_absolute() {
                    p.to_path_buf()
                } else {
                    effective_root.join(p)
                }
            }
            None => effective_root.join(".normalize").join("rule-tests"),
        };

        if !fixture_root.exists() {
            return Err(format!(
                "Fixture directory '{}' does not exist. \
                 Create it and add .input.<ext> + .expected.json pairs.",
                fixture_root.display()
            ));
        }

        let config = load_rules_config(&effective_root);
        let cases = discover_fixture_cases(&fixture_root)
            .map_err(|e| format!("Failed to discover fixtures: {e}"))?;

        if cases.is_empty() {
            return Err(format!(
                "No fixture cases found under '{}'. \
                 Add .input.<ext> + .expected.json pairs (single-file format) \
                 or case-name/input/ + case-name/expected.json (multi-file format).",
                fixture_root.display()
            ));
        }

        let mut case_results: Vec<FixtureCaseResult> = Vec::new();

        for case in &cases {
            let result = run_fixture_case(case, &effective_root, &config, update);
            case_results.push(result);
        }

        let passed = case_results.iter().filter(|c| c.passed).count();
        let failed = case_results.iter().filter(|c| !c.passed).count();

        let report = RulesFixtureTestReport {
            fixture_dir: fixture_root.display().to_string(),
            cases: case_results,
            passed,
            failed,
            updated: update,
        };

        if failed > 0 && !update {
            let detail = self.display_output(&report);
            Err(format!("{detail}\n{failed} fixture case(s) failed"))
        } else {
            Ok(report)
        }
    }
}

// ---------------------------------------------------------------------------
// Fixture discovery and execution helpers (not part of the CLI surface)
// ---------------------------------------------------------------------------

/// A discovered fixture case — either single-file or multi-file.
struct FixtureCase {
    /// Human-readable case name (used in output).
    name: String,
    /// Input files: Vec<(filename, absolute_path)>.
    inputs: Vec<(String, std::path::PathBuf)>,
    /// Absolute path to `expected.json`.
    expected_json: std::path::PathBuf,
}

/// Discover all fixture cases under `root`.
///
/// Scans for:
/// 1. `*.input.<ext>` files paired with `*.expected.json` (single-file).
/// 2. Subdirectories containing `input/` + `expected.json` (multi-file).
fn discover_fixture_cases(root: &std::path::Path) -> std::io::Result<Vec<FixtureCase>> {
    let mut cases: Vec<FixtureCase> = Vec::new();
    let mut single_file_stems: std::collections::HashSet<String> = std::collections::HashSet::new();

    let mut entries: Vec<_> = std::fs::read_dir(root)?
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .collect();
    entries.sort();

    // First pass: collect single-file cases (*.input.*)
    for path in &entries {
        let file_name = match path.file_name().and_then(|n| n.to_str()) {
            Some(n) => n.to_string(),
            None => continue,
        };
        // Match pattern: <stem>.input.<ext>
        if let Some(stem) = extract_input_stem(&file_name) {
            let expected = root.join(format!("{stem}.expected.json"));
            // Always discover: expected.json may not exist yet (--update creates it).
            single_file_stems.insert(stem.clone());
            cases.push(FixtureCase {
                name: stem,
                inputs: vec![(file_name.clone(), path.clone())],
                expected_json: expected,
            });
        }
    }

    // Second pass: multi-file cases (subdirectories with input/ + expected.json)
    for path in &entries {
        if !path.is_dir() {
            continue;
        }
        let dir_name = match path.file_name().and_then(|n| n.to_str()) {
            Some(n) => n.to_string(),
            None => continue,
        };
        // Skip if we already handled this as a single-file case
        if single_file_stems.contains(&dir_name) {
            continue;
        }
        let input_dir = path.join("input");
        let expected = path.join("expected.json");
        if input_dir.is_dir() && (expected.exists() || !expected.exists()) {
            // Collect all files under input/
            let mut inputs: Vec<(String, std::path::PathBuf)> = Vec::new();
            collect_input_files(&input_dir, &input_dir, &mut inputs)?;
            inputs.sort_by(|a, b| a.0.cmp(&b.0));
            if !inputs.is_empty() {
                cases.push(FixtureCase {
                    name: dir_name,
                    inputs,
                    expected_json: expected,
                });
            }
        }
    }

    cases.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(cases)
}

/// Extract the stem from a filename matching `<stem>.input.<ext>`.
/// Returns `None` if the pattern doesn't match.
fn extract_input_stem(file_name: &str) -> Option<String> {
    // We need at least two dots: <stem>.input.<ext>
    let parts: Vec<&str> = file_name.splitn(3, '.').collect();
    if parts.len() >= 3 && parts[1] == "input" {
        Some(parts[0].to_string())
    } else {
        None
    }
}

/// Recursively collect files under `dir`, recording paths relative to `base`.
fn collect_input_files(
    dir: &std::path::Path,
    base: &std::path::Path,
    out: &mut Vec<(String, std::path::PathBuf)>,
) -> std::io::Result<()> {
    for entry in std::fs::read_dir(dir)?.filter_map(|e| e.ok()) {
        let path = entry.path();
        if path.is_dir() {
            collect_input_files(&path, base, out)?;
        } else {
            let rel = path.strip_prefix(base).unwrap_or(&path);
            out.push((rel.to_string_lossy().to_string(), path));
        }
    }
    Ok(())
}

/// Run a single fixture case and return the result.
fn run_fixture_case(
    case: &FixtureCase,
    project_root: &std::path::Path,
    config: &crate::runner::RulesRunConfig,
    update: bool,
) -> FixtureCaseResult {
    // Collect the input file paths for the rule runner
    let input_paths: Vec<std::path::PathBuf> = case.inputs.iter().map(|(_, p)| p.clone()).collect();

    // Use a temp directory as the root so relative file paths in findings are clean
    let input_root: std::path::PathBuf = if case.inputs.len() == 1 {
        // Single-file: use the file's parent dir
        case.inputs[0]
            .1
            .parent()
            .unwrap_or(project_root)
            .to_path_buf()
    } else {
        // Multi-file: use the input/ directory (first input's parent)
        case.inputs[0]
            .1
            .parent()
            .unwrap_or(project_root)
            .to_path_buf()
    };

    // Run syntax rules on the input files
    let debug_flags = normalize_syntax_rules::DebugFlags::default();
    let path_filter = normalize_rules_config::PathFilter::new(&[], &[]);
    let findings = run_syntax_rules(
        &input_root,
        project_root,
        None,
        None,
        None,
        &config.rules,
        &debug_flags,
        Some(&input_paths),
        &path_filter,
        &config.walk,
    );

    // Convert findings to FixtureExpectedFinding (sorted for stable comparison)
    let mut actual: Vec<FixtureExpectedFinding> = findings
        .iter()
        .map(|f| {
            let file_rel = f
                .file
                .strip_prefix(&input_root)
                .unwrap_or(&f.file)
                .to_string_lossy()
                .to_string();
            FixtureExpectedFinding {
                rule: f.rule_id.clone(),
                file: file_rel,
                line: f.start_line,
                message: f.message.clone(),
            }
        })
        .collect();
    actual.sort();
    actual.dedup();

    if update {
        // Write actual findings back to expected.json
        let json = serde_json::to_string_pretty(&actual).unwrap_or_else(|_| "[]".to_string());
        if let Err(e) = std::fs::write(&case.expected_json, json) {
            return FixtureCaseResult {
                case: case.name.clone(),
                passed: false,
                diff: vec![format!("Failed to write expected.json: {e}")],
            };
        }
        return FixtureCaseResult {
            case: case.name.clone(),
            passed: true,
            diff: Vec::new(),
        };
    }

    // Load expected findings
    let expected: Vec<FixtureExpectedFinding> = if case.expected_json.exists() {
        match std::fs::read_to_string(&case.expected_json)
            .map_err(|e| e.to_string())
            .and_then(|s| serde_json::from_str(&s).map_err(|e| e.to_string()))
        {
            Ok(v) => v,
            Err(e) => {
                return FixtureCaseResult {
                    case: case.name.clone(),
                    passed: false,
                    diff: vec![format!("Failed to read expected.json: {e}")],
                };
            }
        }
    } else {
        // No expected.json → treat as expecting zero findings
        Vec::new()
    };

    // Compare: expected uses substring match on message
    let mut diff: Vec<String> = Vec::new();

    // Findings in actual but not matched by any expected entry → unexpected
    let mut matched_actuals: Vec<bool> = vec![false; actual.len()];
    let mut matched_expected: Vec<bool> = vec![false; expected.len()];

    for (ei, exp) in expected.iter().enumerate() {
        let found = actual.iter().enumerate().find(|(ai, act)| {
            !matched_actuals[*ai]
                && act.rule == exp.rule
                && act.file == exp.file
                && act.line == exp.line
                && act.message.contains(&exp.message)
        });
        if let Some((ai, _)) = found {
            matched_actuals[ai] = true;
            matched_expected[ei] = true;
        }
    }

    for (ei, exp) in expected.iter().enumerate() {
        if !matched_expected[ei] {
            diff.push(format!(
                "missing: {}:{} [{}] {:?}",
                exp.file, exp.line, exp.rule, exp.message
            ));
        }
    }

    for (ai, act) in actual.iter().enumerate() {
        if !matched_actuals[ai] {
            diff.push(format!(
                "unexpected: {}:{} [{}] {:?}",
                act.file, act.line, act.rule, act.message
            ));
        }
    }

    diff.sort();

    FixtureCaseResult {
        case: case.name.clone(),
        passed: diff.is_empty(),
        diff,
    }
}

/// Load `RulesRunConfig` from the project config files.
///
/// This mirrors the structure of `NormalizeConfig` but only pulls out the
/// fields needed by the rules machinery, avoiding a circular dependency on the
/// main `normalize` crate.
pub fn load_rules_config(root: &Path) -> RulesRunConfig {
    // We parse a minimal subset of normalize.toml — just the rules-related sections.
    let project_path = root.join(".normalize").join("config.toml");
    let content = match std::fs::read_to_string(&project_path) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => {
            tracing::warn!("failed to read config at {:?}: {}", project_path, e);
            String::new()
        }
    };

    #[derive(serde::Deserialize, Default)]
    #[serde(default)]
    struct RulesOnlyConfig {
        rules: crate::runner::RulesConfig,
        #[serde(rename = "rule-tags")]
        rule_tags: std::collections::HashMap<String, Vec<String>>,
        walk: Option<normalize_rules_config::WalkConfig>,
    }

    // Load global config first
    let global_content = dirs::config_dir()
        .map(|d| d.join("normalize").join("config.toml"))
        .map(|p| match std::fs::read_to_string(&p) {
            Ok(s) => s,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
            Err(e) => {
                tracing::warn!("failed to read config at {:?}: {}", p, e);
                String::new()
            }
        })
        .unwrap_or_default();

    let global: RulesOnlyConfig = toml::from_str(&global_content).unwrap_or_else(|e| {
        eprintln!("warning: failed to parse global rules config: {e}");
        eprintln!("  Rule overrides, severity settings, and allow patterns will not apply.");
        RulesOnlyConfig::default()
    });
    let project: RulesOnlyConfig = toml::from_str(&content).unwrap_or_else(|e| {
        eprintln!(
            "warning: failed to parse rules config at {}: {e}",
            project_path.display()
        );
        eprintln!("  Rule overrides, severity settings, and allow patterns will not apply.");
        RulesOnlyConfig::default()
    });

    let rule_tags = {
        let mut merged = global.rule_tags;
        merged.extend(project.rule_tags);
        merged
    };

    // Merge: start with global, overlay project on top.  Using normalize_core::Merge
    // ensures per-rule overrides from global config are preserved when the project
    // config only overrides a subset of rules.
    use normalize_core::Merge as _;
    let rules = global.rules.merge(project.rules);
    // Walk config: project overrides global if specified.
    let walk = match (global.walk, project.walk) {
        (_, Some(p)) => p,
        (Some(g), None) => g,
        (None, None) => normalize_rules_config::WalkConfig::default(),
    };
    RulesRunConfig {
        rule_tags,
        rules,
        walk,
    }
}