alint 0.14.1

Language-agnostic linter for repository structure, file existence, filename conventions, and file content rules.
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
//! alint — language-agnostic repository linter.
//!
//! See `docs/design/ARCHITECTURE.md` for the rule model, DSL, and execution
//! model. User-facing docs are in the root `README.md`.

use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use alint_core::{Engine, RuleRegistry, WalkOptions, walk};
use alint_output::{ColorChoice, Format, GlyphSet, HumanOptions};
use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};

mod export_agents_md;
mod init;
mod progress;
mod rules;
mod suggest;

/// Long-form `alint --version` output: workspace version, git short
/// SHA, and build date. Bug reports paste this verbatim and a
/// maintainer can pinpoint the exact commit. The SHA + date come
/// from `crates/alint/build.rs` via `cargo:rustc-env`; both fall
/// back to `unknown` when built from a published tarball without
/// a git tree.
const ALINT_LONG_VERSION: &str = concat!(
    env!("CARGO_PKG_VERSION"),
    " (",
    env!("ALINT_GIT_SHA"),
    ", built ",
    env!("ALINT_BUILD_DATE"),
    ")",
);

#[derive(Parser, Debug)]
#[command(
    name = "alint",
    version,
    long_version = ALINT_LONG_VERSION,
    about = "Language-agnostic linter for repository structure, existence, naming, and content rules",
    long_about = None,
)]
// Several independent boolean flags are the natural shape of the
// CLI surface — `--ascii`, `--compact`, `--fail-on-warning`,
// `--no-gitignore`. Collapsing them into a state-machine enum
// would obscure, not clarify.
#[allow(clippy::struct_excessive_bools)]
struct Cli {
    /// Path to a config file.
    #[arg(long, short = 'c', global = true)]
    config: Vec<PathBuf>,

    /// Output format.
    #[arg(long, short = 'f', global = true, default_value = "human")]
    format: String,

    /// Disable .gitignore handling (overrides config).
    #[arg(long, global = true)]
    no_gitignore: bool,

    /// Treat warnings as errors for exit-code purposes.
    #[arg(long, global = true)]
    fail_on_warning: bool,

    /// List informational notes (non-violation findings, e.g. entries
    /// a rule skipped rather than failed on) in full on stderr. By
    /// default only a one-line count is shown.
    #[arg(long, global = true)]
    show_notes: bool,

    /// When to emit ANSI color codes in human output. `auto` (the
    /// default) inspects TTY + `NO_COLOR` + `CLICOLOR_FORCE`.
    /// Only affects the `human` format; `json` / `sarif` /
    /// `github` / `markdown` / `junit` / `gitlab` / `agent` are
    /// always plain bytes.
    #[arg(
        long,
        global = true,
        value_name = "WHEN",
        default_value = "auto",
        value_parser = clap::builder::PossibleValuesParser::new(["auto", "always", "never"]),
    )]
    color: String,

    /// Force ASCII glyphs in human output (e.g. `x` instead of `✗`).
    /// Auto-enabled when `TERM=dumb`.
    #[arg(long, global = true)]
    ascii: bool,

    /// Compact one-line-per-violation human output, suitable for
    /// piping into editors / grep / `wc -l`. Format:
    /// `path:line:col: level: rule-id: message` (the `:line:col` is
    /// omitted for findings with no specific location).
    #[arg(long, global = true)]
    compact: bool,

    /// Override the human-output column width. Default: detected
    /// terminal width (TTY only) or 80. Useful for reproducible
    /// captures (asciinema/screen recordings) and for piping into
    /// fixed-width log viewers. Clamped to [40, 120].
    #[arg(long, global = true, value_name = "COLS")]
    width: Option<usize>,

    /// Suppress per-violation `docs:` URLs in human output. Useful
    /// for narrow terminals, screen recordings, and CI logs where
    /// long URLs disrupt visual alignment. URLs remain in JSON /
    /// SARIF / GitHub / markdown output regardless.
    #[arg(long, global = true)]
    no_docs: bool,

    /// When to render progress on stderr for slow operations
    /// (currently `alint suggest`). `auto` (the default)
    /// renders when stderr is a TTY; `always` forces; `never`
    /// silences. Progress always lives on stderr — `--format`
    /// JSON output on stdout stays byte-clean.
    #[arg(
        long,
        global = true,
        value_name = "WHEN",
        default_value = "auto",
        value_parser = clap::builder::PossibleValuesParser::new(["auto", "always", "never"]),
    )]
    progress: String,

    /// Suppress progress and any stderr summary lines. Alias
    /// for `--progress=never` plus suppression of the
    /// "found N proposals in Ts" footer that `suggest` prints.
    #[arg(long, short = 'q', global = true)]
    quiet: bool,

    /// Suppress violations recorded in the given baseline file (see
    /// `alint baseline`), reporting only new ones. Pre-existing
    /// findings are grandfathered so `check` can gate a legacy repo on
    /// new violations only. A missing or unreadable baseline is an
    /// error (never a silent no-op). The path is resolved relative to
    /// the current directory (not the checked PATH); the `baseline:`
    /// config key, by contrast, resolves against the repo root.
    #[arg(long, global = true, value_name = "FILE")]
    baseline: Option<PathBuf>,

    /// With `--baseline`, fail (exit 1) when the baseline has stale
    /// entries (recorded findings that no longer fire — usually because
    /// they were fixed). Forces the committed baseline to stay exactly
    /// accurate. Off by default: fixing things never fails the build.
    #[arg(long, global = true)]
    strict_baseline: bool,

    /// With `--baseline`, list the suppressed (baselined) findings on
    /// stderr in full, rather than just a one-line count. Parallels
    /// `--show-notes`.
    #[arg(long, global = true)]
    show_baselined: bool,

    /// Restrict the run to the named rule id(s) from the effective config
    /// (repeatable). Other rules are skipped entirely. An id that matches no
    /// loaded rule is an error, so typos fail loudly rather than silently
    /// linting nothing. Applies to `check` and `fix` (the `agent` format emits
    /// `fix --only <rule-id>`); rejected on any other subcommand. Global so the
    /// bare `alint --only <id>` lints the current directory like
    /// `alint check --only <id>` — to lint a different path, use the explicit
    /// form `alint check --only <id> <path>`.
    #[arg(long, global = true, value_name = "RULE_ID")]
    only: Vec<String>,

    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand, Debug)]
enum Command {
    /// Run linters against the current (or given) directory. Default command.
    Check {
        /// Root of the repository to lint. Defaults to the current directory.
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Restrict the check to files in the working-tree diff.
        /// Without `--base`, uses
        /// `git ls-files --modified --others --exclude-standard`
        /// (right shape for pre-commit). With `--base`, uses
        /// `git diff --name-only <base>...HEAD` (right shape for
        /// PR checks). Cross-file rules (`pair`, `for_each_dir`,
        /// `every_matching_has`, `unique_by`, `dir_contains`,
        /// `dir_only_contains`) and existence rules (`file_exists`
        /// et al.) still consult the full tree by definition.
        #[arg(long)]
        changed: bool,
        /// Base ref for `--changed` (uses three-dot
        /// `<base>...HEAD`, i.e. merge-base diff). Implies
        /// `--changed`.
        #[arg(long, value_name = "REF")]
        base: Option<String>,
    },
    /// List the rules loaded from THIS repo's effective config. To browse the
    /// full catalog of rule kinds alint ships, use `alint rules list`.
    List {
        /// Only rules whose kind is in this category (slug; see
        /// `alint rules categories`).
        #[arg(long)]
        category: Option<String>,
    },
    /// Show a rule's definition.
    Explain {
        /// Rule id to describe.
        rule_id: String,
    },
    /// Apply automatic fixes for violations whose rules declare one.
    Fix {
        /// Root of the repository to operate on.
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Print what would be done without writing anything.
        #[arg(long)]
        dry_run: bool,
        /// Restrict the fix pass to files in the working-tree
        /// diff (see `alint check --changed`). Cross-file +
        /// existence rules still see the full tree.
        #[arg(long)]
        changed: bool,
        /// Base ref for `--changed`. Implies `--changed`.
        #[arg(long, value_name = "REF")]
        base: Option<String>,
    },
    /// Snapshot the current violations into a baseline file, so a later
    /// `alint check --baseline <file>` fails only on NEW violations.
    /// The one-step way to adopt alint as a blocking gate on a legacy
    /// repo: `alint baseline` (commit it), then gate on the delta. The
    /// baseline is whole-tree; `--changed` is not accepted.
    Baseline {
        /// Root of the repository to snapshot. Defaults to the current
        /// directory.
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Where to write the baseline. Default: `.alint-baseline.json`
        /// at the repo root.
        #[arg(long, value_name = "FILE")]
        output: Option<PathBuf>,
        /// Allow the regenerated baseline to grandfather violations not
        /// already present in the existing file. Without it, `alint
        /// baseline` refuses to ADD new entries (and prints a `+N / -M`
        /// summary) so re-running it to prune fixed entries can't
        /// silently accept new debt. Stale-entry removal never needs it.
        #[arg(long)]
        accept_new: bool,
    },
    /// Evaluate every `facts:` entry in the effective config and
    /// print the resolved value. Debugging aid for `when:` clauses.
    Facts {
        /// Root of the repository to evaluate facts against.
        #[arg(default_value = ".")]
        path: PathBuf,
    },
    /// Scaffold a starter `.alint.yml` based on the repo's
    /// detected ecosystem (and optionally workspace shape).
    /// Refuses to overwrite an existing config — delete the
    /// existing one first if you really mean it.
    Init {
        /// Root of the repository to write the config into.
        /// Defaults to the current directory.
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Detect workspace shape (Cargo `[workspace]`,
        /// pnpm-workspace.yaml, or `package.json` `workspaces`)
        /// and add the corresponding `monorepo@v1` +
        /// `monorepo/<flavor>-workspace@v1` overlays.
        /// `nested_configs: true` is set on the generated
        /// config so each subdirectory can layer its own
        /// `.alint.yml` on top.
        #[arg(long)]
        monorepo: bool,
    },
    /// Generate (or maintain a section of) `AGENTS.md` from
    /// the active rule set, so the agent's pre-prompt
    /// directives stay in sync with the lint config. Outputs
    /// to stdout by default; use `--output PATH` to write a
    /// file or `--inline --output PATH` to splice between
    /// `<!-- alint:start -->` / `<!-- alint:end -->` markers.
    ExportAgentsMd {
        /// Output destination. Without `--inline`, the file is
        /// overwritten. Omit for stdout.
        #[arg(long, value_name = "PATH")]
        output: Option<PathBuf>,
        /// Splice the generated section between
        /// `<!-- alint:start -->` and `<!-- alint:end -->`
        /// markers in `--output PATH`. Markers are auto-
        /// created (with a stderr warning) when the target
        /// file lacks them.
        #[arg(long, requires = "output")]
        inline: bool,
        /// Heading text for the generated section. Default:
        /// "Lint rules enforced by alint".
        #[arg(long, value_name = "TEXT")]
        section_title: Option<String>,
        /// Include `level: info` rules. Default omits them —
        /// info-level rules are nudges, not directives.
        #[arg(long)]
        include_info: bool,
        /// Output format. `markdown` (default) is the canonical
        /// `AGENTS.md` shape; `json` is parallel to `suggest`'s
        /// JSON envelope for agent consumption.
        #[arg(
            long,
            short = 'f',
            value_name = "FORMAT",
            default_value = "markdown",
            value_parser = clap::builder::PossibleValuesParser::new(["markdown", "json"]),
        )]
        format: String,
    },
    /// Scan the repo for known antipatterns and propose rules
    /// that would catch them. Prints proposals to stdout for
    /// review — never edits the user's config. Pairs naturally
    /// with `alint init` for a smarter cold-start adoption flow.
    Suggest {
        /// Root of the repository to scan. Defaults to the
        /// current directory.
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Output format. `human` (default) is colorised for
        /// terminals; `yaml` is a paste-ready config snippet;
        /// `json` is a stable shape suitable for agent
        /// consumption.
        #[arg(
            long,
            short = 'f',
            value_name = "FORMAT",
            default_value = "human",
            value_parser = clap::builder::PossibleValuesParser::new(["human", "yaml", "json"]),
        )]
        format: String,
        /// Lower bound on signal strength for proposals. `low`
        /// is broadest (helpful when prospecting); `high` is
        /// strict (only ecosystem-marker hits and equivalents).
        #[arg(
            long,
            value_name = "LEVEL",
            default_value = "medium",
            value_parser = clap::builder::PossibleValuesParser::new(["low", "medium", "high"]),
        )]
        confidence: String,
        /// Include bundled-ruleset suggestions even if the
        /// existing `.alint.yml` already extends them.
        #[arg(long)]
        include_bundled: bool,
        /// Print one-line file-level evidence under each
        /// proposal so reviewers can decide quickly.
        #[arg(long)]
        explain: bool,
    },
    /// Parse-validate an `.alint.yml` (resolves `extends:`, builds
    /// every rule, parses every `when:`) and report any errors —
    /// without walking the tree. For editor LSP, pre-commit hooks,
    /// and fail-fast CI steps that just want to know "is the config
    /// loadable?". Exit 0 on success; exit 1 on validation failure.
    ValidateConfig {
        /// Path to the config file to validate. Defaults to the
        /// `.alint.yml` discovered upward from the current
        /// directory (same discovery rules as `alint check`).
        path: Option<PathBuf>,
        /// Output format. `human` prints a one-line success or a
        /// rich error trace; `json` emits a stable
        /// `{"valid": bool, "rule_count": N, "config_path": ...,
        /// "error": "...?"}` envelope for editor / CI consumption.
        #[arg(
            long,
            short = 'f',
            value_name = "FORMAT",
            default_value = "human",
            value_parser = clap::builder::PossibleValuesParser::new(["human", "json"]),
        )]
        format: String,
    },
    /// Start the alint language server, speaking LSP over stdio.
    /// Editor integrations (VS Code, Zed, Neovim, and others) spawn
    /// this and drive it via the Language Server Protocol; it is not
    /// meant to be run interactively. Publishes diagnostics for the
    /// workspace's `.alint.yml` rules on document open and save.
    Lsp,
    /// Browse the catalog of rule kinds alint ships (config-independent).
    /// Use `alint list` for the rules configured in THIS repo; `alint rules`
    /// never reads a config and works anywhere.
    Rules {
        #[command(subcommand)]
        command: RulesCommand,
    },
}

/// Subcommands of `alint rules` (catalog discovery). See ADR-0009.
#[derive(Subcommand, Debug)]
enum RulesCommand {
    /// List rule kinds in the catalog, optionally filtered. Reads no config.
    List {
        /// Only kinds in this category (slug, e.g. `security-unicode-sanity`;
        /// run `alint rules categories` for the list).
        #[arg(long)]
        category: Option<String>,
        /// Case-insensitive substring filter on the kind name (and its aliases).
        #[arg(long)]
        search: Option<String>,
    },
    /// List the rule categories: slug, title, and how many kinds each holds.
    Categories,
}

fn main() -> ExitCode {
    init_panic_hook();
    init_tracing();
    let cli = Cli::parse();
    match run(cli) {
        Ok(code) => code,
        Err(e) => {
            eprintln!("alint: {e:#}");
            // Exit 3 for an internal alint error (a bug), 2 for a config /
            // CLI-usage error the user can fix (M11).
            if error_is_internal(&e) {
                ExitCode::from(3)
            } else {
                ExitCode::from(2)
            }
        }
    }
}

/// Whether the error chain carries an `alint_core::Error::Internal` — an alint
/// bug, which the CLI reports as exit code `3` rather than the `2` used for a
/// fixable config / usage error (M11).
fn error_is_internal(err: &anyhow::Error) -> bool {
    err.chain().any(|cause| {
        cause
            .downcast_ref::<alint_core::Error>()
            .is_some_and(alint_core::Error::is_internal)
    })
}

/// Install a custom panic hook that prints a pre-filled GitHub-issue
/// URL for the bug report. Skipped when `RUST_BACKTRACE` is set so
/// developers running with `RUST_BACKTRACE=1` keep the standard
/// backtrace path.
fn init_panic_hook() {
    if std::env::var_os("RUST_BACKTRACE").is_some() {
        return;
    }
    std::panic::set_hook(Box::new(|info| {
        let location = info.location().map_or_else(
            || "(unknown)".to_string(),
            |l| format!("{}:{}", l.file(), l.line()),
        );
        let payload = info
            .payload()
            .downcast_ref::<&str>()
            .copied()
            .or_else(|| info.payload().downcast_ref::<String>().map(String::as_str))
            .unwrap_or("(non-string panic payload)");
        let title = format!("alint panic: {payload}");
        let body = format!(
            "alint version: {ver}\n\
             OS: {os}\n\
             Panic location: {location}\n\
             Panic message: {payload}\n\n\
             Steps to reproduce:\n\
             1. ...\n\
             2. ...\n\
             3. ...\n\n\
             Expected behaviour:\n\n\
             Actual behaviour:\n",
            ver = ALINT_LONG_VERSION,
            os = std::env::consts::OS,
        );
        let url = format!(
            "https://github.com/asamarts/alint/issues/new?title={}&body={}",
            url_encode(&title),
            url_encode(&body),
        );
        eprintln!("\nalint crashed unexpectedly. This is a bug — please file a report:");
        eprintln!("  {url}\n");
        eprintln!("Panic: {payload}");
        eprintln!("Location: {location}");
        eprintln!("Re-run with `RUST_BACKTRACE=1` for the full backtrace.");
    }));
}

/// Minimal RFC 3986 percent-encoder for the panic-hook URL's query
/// string. Hand-rolled so the panic hook stays dependency-free —
/// pulling in `urlencoding` for one call site would expand the
/// blast radius on a code path that runs only when alint is
/// already in trouble.
fn url_encode(s: &str) -> String {
    use std::fmt::Write as _;
    let mut out = String::with_capacity(s.len());
    for b in s.as_bytes() {
        let c = *b;
        if c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.' | b'~') {
            out.push(c as char);
        } else {
            // Writing into a `String` via `write!` cannot fail — the
            // io::Write impl on String is infallible.
            let _ = write!(out, "%{c:02X}");
        }
    }
    out
}

fn init_tracing() {
    use tracing_subscriber::{EnvFilter, fmt};
    let filter = EnvFilter::try_from_env("ALINT_LOG").unwrap_or_else(|_| EnvFilter::new("warn"));
    let _ = fmt().with_env_filter(filter).with_target(false).try_init();
}

fn run(mut cli: Cli) -> Result<ExitCode> {
    let command = cli.command.take().unwrap_or(Command::Check {
        path: PathBuf::from("."),
        changed: false,
        base: None,
    });
    // `--only` is global so the bare default `alint --only <id>` (= check)
    // works, but it only has meaning for check/fix. On any other subcommand a
    // (possibly typo'd) `--only` was silently ignored; reject it loudly, matching
    // the flag's own "typos fail loudly" contract.
    if !cli.only.is_empty() && !matches!(command, Command::Check { .. } | Command::Fix { .. }) {
        bail!("`--only` only applies to `check` and `fix`");
    }
    // `--config` is single-valued in effect: every consumer reads the first
    // entry, so a second `-c` was silently dropped while the help text wrongly
    // promised "later overrides earlier". Reject multiple rather than silently
    // pick one — layering configs is what `extends:` is for.
    if cli.config.len() > 1 {
        bail!(
            "`--config` may be given at most once (got {}); compose configs with an \
             `extends:` chain instead of repeating `-c`",
            cli.config.len()
        );
    }
    // The baseline flags only affect `check`; on every other subcommand they
    // were silently ignored, breaking the flag's own "a missing baseline is an
    // error, never a silent no-op" contract. Reject them loudly off `check`,
    // matching `--only`. (The `baseline` subcommand writes via its own
    // `--output`, not this flag.)
    if (cli.baseline.is_some() || cli.strict_baseline || cli.show_baselined)
        && !matches!(command, Command::Check { .. })
    {
        bail!(
            "`--baseline`, `--strict-baseline`, and `--show-baselined` apply only to \
             `check` (the `baseline` subcommand writes via `--output`)"
        );
    }
    match command {
        Command::Check {
            path,
            changed,
            base,
        } => cmd_check(&path, &ChangedMode::new(changed, base), &cli.only, &cli),
        Command::List { category } => cmd_list(category.as_deref(), &cli),
        Command::Explain { rule_id } => cmd_explain(&rule_id, &cli),
        Command::Fix {
            path,
            dry_run,
            changed,
            base,
        } => cmd_fix(
            &path,
            dry_run,
            &ChangedMode::new(changed, base),
            &cli.only,
            &cli,
        ),
        Command::Baseline {
            path,
            output,
            accept_new,
        } => cmd_baseline(&path, output.as_deref(), accept_new, &cli),
        Command::Facts { path } => cmd_facts(&path, &cli),
        Command::Init { path, monorepo } => {
            reject_non_human_format(&cli, "init")?;
            cmd_init(&path, monorepo)
        }
        Command::ExportAgentsMd {
            output,
            inline,
            section_title,
            include_info,
            format,
        } => cmd_export_agents_md(
            &ExportAgentsMdOptions {
                output,
                inline,
                section_title,
                include_info,
                format,
            },
            &cli,
        ),
        Command::Suggest {
            path,
            format,
            confidence,
            include_bundled,
            explain,
        } => cmd_suggest(
            &path,
            &SuggestOptions {
                format,
                confidence,
                include_bundled,
                explain,
            },
            &cli,
        ),
        Command::ValidateConfig { path, format } => cmd_validate_config(path, &format, &cli),
        Command::Lsp => {
            reject_non_human_format(&cli, "lsp")?;
            cmd_lsp()
        }
        Command::Rules { command } => rules::run(&command, &cli),
    }
}

/// Fail loudly when a subcommand that produces no formatted report is given a
/// non-default `--format` (M13 contract: never silently ignore the flag). Used
/// by `init` and `lsp`, which — unlike `check`/`list`/`baseline`/… — take no
/// `&cli` of their own.
fn reject_non_human_format(cli: &Cli, cmd: &str) -> anyhow::Result<()> {
    if cli.format != "human" {
        anyhow::bail!(
            "`{cmd}` does not support `--format {}` — it produces no formatted report; drop `--format`",
            cli.format
        );
    }
    Ok(())
}

/// Start the LSP server over stdio. Blocks (running its own async
/// runtime inside `alint-lsp`) until the client disconnects.
fn cmd_lsp() -> Result<ExitCode> {
    alint_lsp::run_stdio().context("running language server")?;
    Ok(ExitCode::SUCCESS)
}

#[derive(Debug)]
struct ExportAgentsMdOptions {
    output: Option<PathBuf>,
    inline: bool,
    section_title: Option<String>,
    include_info: bool,
    format: String,
}

fn cmd_export_agents_md(opts: &ExportAgentsMdOptions, cli: &Cli) -> Result<ExitCode> {
    use export_agents_md::{OutputFormat, RunOptions};
    let format: OutputFormat = opts
        .format
        .parse()
        .map_err(|e: String| anyhow::anyhow!(e))?;
    let section_title = opts
        .section_title
        .clone()
        .unwrap_or_else(|| "Lint rules enforced by alint".to_string());
    let run_opts = RunOptions {
        format,
        output: opts.output.clone(),
        inline: opts.inline,
        section_title,
        include_info: opts.include_info,
    };
    export_agents_md::run(cli.config.first().map(PathBuf::as_path), &run_opts)
}

#[derive(Debug)]
struct SuggestOptions {
    format: String,
    confidence: String,
    include_bundled: bool,
    explain: bool,
}

fn cmd_suggest(path: &Path, opts: &SuggestOptions, cli: &Cli) -> Result<ExitCode> {
    use suggest::{Confidence, OutputFormat};
    let format: OutputFormat = opts
        .format
        .parse()
        .map_err(|e: String| anyhow::anyhow!(e))?;
    let confidence: Confidence = opts
        .confidence
        .parse()
        .map_err(|e: String| anyhow::anyhow!(e))?;
    let progress_mode = if cli.quiet {
        progress::ProgressMode::Never
    } else {
        cli.progress
            .parse()
            .map_err(|e: String| anyhow::anyhow!(e))?
    };
    let progress = progress::Progress::new(progress_mode);
    let (mut out, _opts) = render_env(cli)?;
    suggest::run(
        path,
        &suggest::RunOptions {
            format,
            confidence,
            include_bundled: opts.include_bundled,
            explain: opts.explain,
            quiet: cli.quiet,
            width: cli.width,
        },
        &progress,
        &mut out,
    )
}

fn cmd_init(path: &Path, monorepo: bool) -> Result<ExitCode> {
    // Refuse to overwrite an existing `.alint.yml` (or any of
    // the other names the loader recognises). The user-visible
    // contract is: `alint init` is a one-shot scaffold; if a
    // config already exists, the user knows their setup better
    // than we do.
    for name in [".alint.yml", ".alint.yaml", "alint.yml", "alint.yaml"] {
        let candidate = path.join(name);
        if candidate.is_file() {
            bail!(
                "{} already exists; refusing to overwrite. Delete it first if you really \
                 want to regenerate, or edit it directly.",
                candidate.display()
            );
        }
    }

    let detection = init::detect(path, monorepo);
    let body = init::render(&detection);
    let target = path.join(".alint.yml");
    std::fs::write(&target, &body).with_context(|| format!("writing {}", target.display()))?;

    let summary = init::render_summary(&detection);
    if summary.is_empty() {
        println!(
            "Wrote {} — extends `oss-baseline@v1` only.",
            target.display()
        );
        println!(
            "  No language manifests detected. Add an `extends:` line for your stack \
             (`alint://bundled/rust@v1`, `node@v1`, …) when ready."
        );
    } else {
        println!("Wrote {} — detected: {}.", target.display(), summary);
        println!("  Run `alint check` to lint against the generated config.");
    }
    Ok(ExitCode::SUCCESS)
}

/// Resolved `--changed` / `--base` state. `--base` implies
/// `--changed`; both together identify the diff source.
#[derive(Debug)]
struct ChangedMode {
    enabled: bool,
    base: Option<String>,
}

impl ChangedMode {
    fn new(changed_flag: bool, base: Option<String>) -> Self {
        // `--base=<ref>` without `--changed` is treated as if
        // `--changed` was passed. The flag is the verb; the ref
        // is its argument. Surfacing `--base` on its own as an
        // error would be pedantic.
        let enabled = changed_flag || base.is_some();
        Self { enabled, base }
    }

    /// Resolve the changed-set from git, or `None` when the user
    /// didn't ask for `--changed`. Hard-errors when the user DID
    /// ask but git can't deliver — silently falling back to a
    /// full check would violate the user's intent.
    fn resolve(&self, root: &Path) -> Result<Option<std::collections::HashSet<PathBuf>>> {
        if !self.enabled {
            return Ok(None);
        }
        let set = alint_core::git::collect_changed_paths(root, self.base.as_deref()).ok_or_else(
            || {
                let what = self.base.as_deref().map_or_else(
                    || "git ls-files --modified --others --exclude-standard".to_string(),
                    |r| format!("git diff --name-only {r}...HEAD"),
                );
                anyhow::anyhow!(
                    "--changed requires a git repository (and `git` on PATH); \
                     `{what}` failed at {}. Run without --changed for a full check.",
                    root.display()
                )
            },
        )?;
        Ok(Some(set))
    }
}

/// Filter loaded rule entries to the ids named in `--only` (a no-op
/// when `only` is empty). Every `--only` id must match a loaded rule;
/// an unmatched id is an error so a typo fails loudly instead of
/// silently selecting nothing. Shared by `check` and `fix`.
fn apply_only_filter(
    entries: Vec<alint_core::RuleEntry>,
    only: &[String],
) -> Result<Vec<alint_core::RuleEntry>> {
    if only.is_empty() {
        return Ok(entries);
    }
    let wanted: std::collections::HashSet<&str> = only.iter().map(String::as_str).collect();
    let present: std::collections::HashSet<&str> = entries.iter().map(|e| e.rule.id()).collect();
    let mut missing: Vec<&str> = wanted
        .iter()
        .copied()
        .filter(|id| !present.contains(id))
        .collect();
    if !missing.is_empty() {
        missing.sort_unstable();
        bail!(
            "no rule with id {} found in the effective config (passed via --only)",
            missing
                .iter()
                .map(|id| format!("{id:?}"))
                .collect::<Vec<_>>()
                .join(", ")
        );
    }
    Ok(entries
        .into_iter()
        .filter(|e| wanted.contains(e.rule.id()))
        .collect())
}

/// Reject a PATH that isn't a directory. `check`/`fix`/`baseline` operate on a
/// repository ROOT (a directory); given a single file they would walk nothing
/// and exit 0 — a silent false "all passed". Fail loudly instead.
fn require_directory(path: &Path) -> Result<()> {
    if !path.is_dir() {
        bail!(
            "{} is {}, but `check`/`fix`/`baseline` take a repository root (a \
             directory), not a single file",
            path.display(),
            if path.exists() { "a file" } else { "not found" },
        );
    }
    Ok(())
}

/// The baseline file's path relative to the lint `root`, as a walk-exclude
/// pattern — so a broad-glob content rule can't lint alint's own committed
/// JSON-Lines baseline artifact as a spurious "new" violation. Returns `None`
/// when the baseline lives outside the lint root (then it isn't walked anyway)
/// or doesn't exist yet (the missing-baseline error surfaces at load time).
fn baseline_walk_exclude(root: &Path, baseline: &Path) -> Option<String> {
    let root_abs = root.canonicalize().ok()?;
    let base_abs = baseline.canonicalize().ok()?;
    let rel = base_abs.strip_prefix(&root_abs).ok()?;
    // Root-anchored (leading `/`): the walker turns this into an override
    // `!/…` that matches ONLY the baseline at the repo root, never a same-named
    // file in a subdirectory. Without the anchor a separator-less pattern
    // matches at any depth, silently dropping a real violation in e.g.
    // `sub/.alint-baseline.json`.
    Some(format!("/{}", rel.to_string_lossy().replace('\\', "/")))
}

/// Append the [`baseline_walk_exclude`] pattern for `baseline` (when set) to
/// `extra_ignores`, so `check` / `baseline` / `fix` all keep alint's own
/// committed JSON-Lines artifact out of the walk. A broad-glob content rule
/// (`**/*.json`, `line_max_width`, `no_trailing_whitespace`, …) would otherwise
/// flag it — breaking the adopt-flow for `check`, making `baseline`
/// regeneration see the artifact as fresh debt, and letting `fix` rewrite it.
fn exclude_baseline_from_walk(
    extra_ignores: &mut Vec<String>,
    root: &Path,
    baseline: Option<&Path>,
) {
    if let Some(bp) = baseline
        && let Some(rel) = baseline_walk_exclude(root, bp)
    {
        extra_ignores.push(rel);
    }
}

fn cmd_check(path: &Path, changed: &ChangedMode, only: &[String], cli: &Cli) -> Result<ExitCode> {
    require_directory(path)?;
    let loaded = load_rules(path, cli)?;
    // The `baseline:` config key, resolved against the repo root being checked.
    // The `--baseline` flag (used as given) overrides it; either one turns on
    // baseline suppression. No silent auto-detect of `.alint-baseline.json`.
    let config_baseline = loaded.baseline.as_ref().map(|b| path.join(b));
    // Resolved early (was below the walk) so the baseline file can be excluded
    // from the walk. The `--baseline` flag (used as given) overrides the key.
    let effective_baseline = cli.baseline.clone().or(config_baseline);
    let entries = apply_only_filter(loaded.entries, only)?;
    let rule_count = entries.len();
    let mut engine = Engine::from_entries(entries, loaded.registry)
        .with_facts(loaded.facts)
        .with_vars(loaded.vars);
    let changed_active = match changed.resolve(path)? {
        Some(set) => {
            engine = engine.with_changed_paths(set);
            true
        }
        None => false,
    };

    let effective_gitignore = if cli.no_gitignore {
        false
    } else {
        loaded.respect_gitignore
    };
    // Keep alint's own baseline artifact out of the walk (see the helper).
    let mut extra_ignores = loaded.extra_ignores;
    exclude_baseline_from_walk(&mut extra_ignores, path, effective_baseline.as_deref());
    let walk_opts = WalkOptions {
        respect_gitignore: effective_gitignore,
        extra_ignores,
    };

    let index = walk(path, &walk_opts).context("walking repository")?;
    tracing::debug!(files = index.entries.len(), "walk complete");

    let report = engine.run(path, &index).context("running rules")?;

    let format: Format = cli.format.parse().map_err(|e: String| anyhow::anyhow!(e))?;

    // Baseline suppression (when --baseline is in effect): grandfather
    // recorded violations, leaving only new ones to format + gate on.
    let mut strict_stale_fail = false;
    let (report, baseline_marks) = if let Some(baseline_path) = &effective_baseline {
        let baseline = load_baseline(baseline_path)?;
        let mut reader = FileReader::new(path);
        let applied =
            alint_core::baseline::apply(&report, &baseline, |rid, v| reader.fingerprint(rid, v));
        // Stale-entry detection is only valid on a FULL run. When `--changed`
        // or `--only` restricts what was evaluated, a baseline entry for an
        // out-of-scope file/rule legitimately "doesn't fire this run" but is
        // NOT stale (the finding still exists, it just wasn't checked).
        // Reporting/failing on those red-lights the documented
        // `--changed --baseline --strict-baseline` PR-gate recipe.
        let scoped = changed_active || !only.is_empty();
        report_baseline_summary(&applied, cli, !scoped);
        if cli.strict_baseline && !scoped && !applied.stale.is_empty() {
            strict_stale_fail = true;
        }
        // Only SARIF and JSON consume the marks; building them clones every
        // suppressed finding, so skip that work for the formats that ignore
        // the baseline and emit only the live (new) findings.
        let marks =
            matches!(format, Format::Sarif | Format::Json).then(|| build_baseline_marks(&applied));
        (applied.live, marks)
    } else {
        (report, None)
    };

    let (mut out, opts) = render_env(cli)?;
    // SARIF and JSON render baselined findings (marked / counted) so Code
    // Scanning dismisses rather than re-opens them; every other format ignores
    // the baseline and emits only the live (new) findings.
    match (format, baseline_marks.as_ref()) {
        (Format::Sarif, Some(marks)) => {
            alint_output::write_sarif_with_baseline(&report, Some(marks), &mut out)
        }
        (Format::Json, Some(marks)) => alint_output::write_json_with_baseline(
            &report,
            Some(marks),
            cli.show_baselined,
            &mut out,
        ),
        (Format::Gitlab, _) => {
            // Unify GitLab Code Quality's `fingerprint` with the baseline/SARIF
            // identity (was a self-contained occurrence hash): compute the
            // canonical per-violation `violation_fingerprint` (file-content-aware,
            // cached reads) and pass it in, so a finding has ONE fingerprint
            // across GitLab, SARIF, and baseline mode.
            let mut reader = FileReader::new(path);
            let fps: Vec<Vec<String>> = report
                .results
                .iter()
                .map(|r| {
                    r.violations
                        .iter()
                        .map(|v| reader.fingerprint(&r.rule_id, v))
                        .collect()
                })
                .collect();
            alint_output::write_gitlab(&report, Some(&fps), &mut out)
        }
        _ => format.write_with_options(&report, &mut out, opts),
    }
    .context("writing output")?;
    out.flush().ok();

    // Informational notes (non-violation findings) — surfaced on
    // stderr for the human format so stdout stays clean. JSON carries
    // them in its `notes` array instead. A one-line count by default;
    // the full list with `--show-notes`.
    if format == Format::Human {
        report_notes_to_stderr(&report, cli.show_notes);
    }

    tracing::debug!(rules = rule_count, "done");

    let exit = if report.has_errors()
        || (cli.fail_on_warning && report.has_warnings())
        || strict_stale_fail
    {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    };
    Ok(exit)
}

/// Caches file reads while fingerprinting a report's violations: the
/// line-content discriminator ([`alint_core::baseline`]) needs the
/// offending file's bytes, and a file usually carries several
/// violations.
struct FileReader<'a> {
    root: &'a Path,
    cache: std::collections::HashMap<PathBuf, Option<Vec<u8>>>,
}

impl<'a> FileReader<'a> {
    fn new(root: &'a Path) -> Self {
        Self {
            root,
            cache: std::collections::HashMap::new(),
        }
    }

    fn fingerprint(&mut self, rule_id: &str, v: &alint_core::Violation) -> String {
        let bytes = match v.path.as_ref() {
            Some(p) => self
                .cache
                .entry(p.to_path_buf())
                .or_insert_with(|| {
                    // Cap the fingerprint read (M3): a pathological >256 MiB
                    // file must not OOM the fingerprint path. Over-cap → None →
                    // the fingerprint degrades to its non-content identity
                    // rather than reading unbounded bytes.
                    let full = self.root.join(p);
                    let size = std::fs::metadata(&full).map_or(0, |m| m.len());
                    alint_core::read_capped_or_skip(&full, size)
                })
                .as_deref(),
            None => None,
        };
        alint_core::baseline::fingerprint(rule_id, v, bytes)
    }
}

/// Build the per-result baseline marks the SARIF/JSON formatters consume:
/// each live violation's fingerprint (parallel to the result's `violations`)
/// and the suppressed findings grouped onto their producing rule.
fn build_baseline_marks(
    applied: &alint_core::baseline::AppliedBaseline,
) -> alint_output::BaselineMarks {
    use std::collections::HashMap;

    let mut by_rule: HashMap<&str, Vec<alint_output::SuppressedFinding>> = HashMap::new();
    for s in &applied.suppressed {
        by_rule
            .entry(s.rule_id.as_ref())
            .or_default()
            .push(alint_output::SuppressedFinding {
                violation: s.violation.clone(),
                fingerprint: s.fingerprint.clone(),
            });
    }
    let per_result = applied
        .live
        .results
        .iter()
        .enumerate()
        .map(|(i, rr)| alint_output::ResultMarks {
            live_fingerprints: applied
                .live_fingerprints
                .get(i)
                .cloned()
                .unwrap_or_default(),
            suppressed: by_rule.remove(rr.rule_id.as_ref()).unwrap_or_default(),
        })
        .collect();
    alint_output::BaselineMarks {
        per_result,
        suppressed_total: applied.suppressed_total,
    }
}

/// Load + parse a baseline file. A missing file or a parse / schema
/// error is a hard error (exit 2), never a silent "suppress nothing".
fn load_baseline(path: &Path) -> Result<alint_core::baseline::Baseline> {
    let text = std::fs::read_to_string(path).with_context(|| {
        format!(
            "reading baseline file {} (run `alint baseline` to create it)",
            path.display()
        )
    })?;
    alint_core::baseline::Baseline::load(&text)
        .map_err(|e| anyhow::anyhow!("invalid baseline file {}: {e}", path.display()))
}

/// Stderr summary for a baseline-applied run: the suppressed count (or
/// the full list with `--show-baselined`) and any stale-entry warning.
/// `report_stale` is false on a scoped (`--changed`/`--only`) run, where
/// out-of-scope entries can't be judged stale (see `cmd_check`).
fn report_baseline_summary(
    applied: &alint_core::baseline::AppliedBaseline,
    cli: &Cli,
    report_stale: bool,
) {
    if !cli.quiet && applied.suppressed_total > 0 {
        eprintln!(
            "alint: {} baselined violation(s) suppressed",
            applied.suppressed_total
        );
    }
    if cli.show_baselined {
        for s in &applied.suppressed {
            match &s.violation.path {
                Some(p) => eprintln!(
                    "  baselined: {}: [{}] {}",
                    p.display(),
                    s.rule_id,
                    s.violation.message
                ),
                None => eprintln!("  baselined: [{}] {}", s.rule_id, s.violation.message),
            }
        }
    }
    if report_stale && !cli.quiet && !applied.stale.is_empty() {
        let n = applied.stale.len();
        eprintln!(
            "alint: {n} baseline entr{} no longer fire{}; run `alint baseline` to re-tighten{}",
            if n == 1 { "y" } else { "ies" },
            if n == 1 { "s" } else { "" },
            if cli.strict_baseline {
                " (failing build: --strict-baseline)"
            } else {
                ""
            }
        );
    }
}

/// `alint baseline`: snapshot the current violations into a baseline
/// file. Whole-tree only (the subcommand doesn't accept `--changed`).
fn cmd_baseline(
    path: &Path,
    output: Option<&Path>,
    accept_new: bool,
    cli: &Cli,
) -> Result<ExitCode> {
    use alint_core::baseline::{Baseline, FingerprintedViolation};

    require_directory(path)?;
    // `baseline` writes the baseline file plus a human summary; it has no
    // machine-readable report output, so a non-default `--format` would be
    // silently ignored. Reject it rather than no-op (the same fail-loudly
    // contract `--only` follows on subcommands that don't honor it).
    if cli.format != "human" {
        anyhow::bail!(
            "`baseline` does not support `--format {}` — it writes the baseline file and a \
             human summary; drop `--format` (use `--quiet` to silence the summary)",
            cli.format
        );
    }
    let loaded = load_rules(path, cli)?;

    // Output path precedence: --output (as given) > `baseline:` config key
    // (resolved against the repo root) > the default `.alint-baseline.json`.
    // So `alint baseline` and `alint check` agree on the same file by default.
    // Resolved up front so it can be excluded from the walk below — otherwise
    // a regeneration re-lints the existing artifact and reports it as new debt.
    let out_path = output.map_or_else(
        || {
            loaded
                .baseline
                .as_ref()
                .map_or_else(|| path.join(".alint-baseline.json"), |b| path.join(b))
        },
        Path::to_path_buf,
    );

    let engine = Engine::from_entries(loaded.entries, loaded.registry)
        .with_facts(loaded.facts)
        .with_vars(loaded.vars);
    let mut extra_ignores = loaded.extra_ignores;
    exclude_baseline_from_walk(&mut extra_ignores, path, Some(&out_path));
    let walk_opts = WalkOptions {
        respect_gitignore: if cli.no_gitignore {
            false
        } else {
            loaded.respect_gitignore
        },
        extra_ignores,
    };
    let index = walk(path, &walk_opts).context("walking repository")?;
    let report = engine.run(path, &index).context("running rules")?;

    let mut reader = FileReader::new(path);
    let mut items: Vec<FingerprintedViolation> = Vec::new();
    for result in &report.results {
        for v in &result.violations {
            items.push(FingerprintedViolation {
                rule_id: result.rule_id.to_string(),
                path: v
                    .path
                    .as_ref()
                    .map(|p| p.to_string_lossy().replace('\\', "/")),
                fingerprint: reader.fingerprint(&result.rule_id, v),
                message: Some(v.message.to_string()),
            });
        }
    }
    let new_baseline =
        Baseline::from_fingerprints(Some(env!("CARGO_PKG_VERSION").to_string()), items);

    // Regeneration guard: refuse to grandfather NEW debt without
    // --accept-new. Pruning stale entries is always allowed.
    if out_path.exists() && !accept_new {
        use std::collections::HashMap;
        let existing = load_baseline(&out_path)?;
        // Compare by OCCURRENCE, not just fingerprint identity: a higher count
        // on an already-baselined finding is fresh debt too, and must not slip
        // in silently. Both baselines are dup-free (load + from_fingerprints
        // dedup), so each fingerprint maps to exactly one count.
        let old_counts: HashMap<&str, u32> = existing
            .entries
            .iter()
            .map(|e| (e.fingerprint.as_str(), e.count))
            .collect();
        let new_counts: HashMap<&str, u32> = new_baseline
            .entries
            .iter()
            .map(|e| (e.fingerprint.as_str(), e.count))
            .collect();
        let added: u64 = new_counts
            .iter()
            .map(|(fp, &c)| u64::from(c.saturating_sub(old_counts.get(fp).copied().unwrap_or(0))))
            .sum();
        let removed: u64 = old_counts
            .iter()
            .map(|(fp, &c)| u64::from(c.saturating_sub(new_counts.get(fp).copied().unwrap_or(0))))
            .sum();
        if added > 0 {
            bail!(
                "regenerating {} would grandfather {added} new violation(s) (+{added} / -{removed}); \
                 fix them, or pass --accept-new to accept them into the baseline",
                out_path.display()
            );
        }
    }

    std::fs::write(&out_path, new_baseline.to_jsonl())
        .with_context(|| format!("writing baseline {}", out_path.display()))?;
    if !cli.quiet {
        let n = new_baseline.entries.len();
        let total = new_baseline.total();
        eprintln!(
            "alint: wrote {} ({n} entr{}, {total} occurrence{})",
            out_path.display(),
            if n == 1 { "y" } else { "ies" },
            if total == 1 { "" } else { "s" },
        );
    }
    Ok(ExitCode::SUCCESS)
}

/// Surface informational notes (non-violation findings) on stderr so
/// stdout stays clean. A one-line count by default; the full
/// `path: message` list when `show_notes` is set. No output when there
/// are no notes.
fn report_notes_to_stderr(report: &alint_core::Report, show_notes: bool) {
    let total: usize = report.results.iter().map(|r| r.notes.len()).sum();
    if total == 0 {
        return;
    }
    if show_notes {
        eprintln!("alint: {total} informational note(s):");
        for result in &report.results {
            for note in &result.notes {
                match &note.path {
                    Some(p) => eprintln!("  note: {}: {}", p.display(), note.message),
                    None => eprintln!("  note: {}", note.message),
                }
            }
        }
    } else {
        eprintln!("alint: {total} informational note(s); run with --show-notes to list.");
    }
}

fn cmd_fix(
    path: &Path,
    dry_run: bool,
    changed: &ChangedMode,
    only: &[String],
    cli: &Cli,
) -> Result<ExitCode> {
    require_directory(path)?;
    // Gate the output format *before* touching the tree: `fix` mutates files,
    // so a format we can't render must fail here, not after the write. Only
    // `human`, `json`, and `markdown` have dedicated fix-report renderers. The
    // finding-oriented formats (SARIF / GitHub / JUnit / GitLab) and the
    // check-side `agent` format would otherwise degrade *silently* to human
    // output with exit 0 — a machine consumer asking for `sarif` and getting
    // human text is the same trap M13 closed for `validate-config`. Fail loudly
    // instead, and point `agent` at its real home: `check --format agent`
    // (whose per-violation `fix_command` drives the agentic fix loop; `fix`
    // itself has no agent report).
    let format: Format = cli.format.parse().map_err(|e: String| anyhow::anyhow!(e))?;
    if !matches!(format, Format::Human | Format::Json | Format::Markdown) {
        bail!(
            "`alint fix` supports only `--format human`, `--format json`, or \
             `--format markdown` (got {fmt:?}); the SARIF/GitHub/JUnit/GitLab/agent \
             formats describe findings, not fixes — run `alint check --format {fmt}` \
             for those",
            fmt = cli.format,
        );
    }
    let loaded = load_rules(path, cli)?;
    let entries = apply_only_filter(loaded.entries, only)?;
    let mut engine = Engine::from_entries(entries, loaded.registry)
        .with_facts(loaded.facts)
        .with_vars(loaded.vars)
        .with_fix_size_limit(loaded.fix_size_limit);
    if let Some(set) = changed.resolve(path)? {
        engine = engine.with_changed_paths(set);
    }

    let effective_gitignore = if cli.no_gitignore {
        false
    } else {
        loaded.respect_gitignore
    };
    // Keep the baseline artifact out of the walk so a broad content-fixer can't
    // rewrite alint's own committed JSON-Lines file (mirrors `check`/`baseline`).
    let effective_baseline = cli
        .baseline
        .clone()
        .or_else(|| loaded.baseline.as_ref().map(|b| path.join(b)));
    let mut extra_ignores = loaded.extra_ignores;
    exclude_baseline_from_walk(&mut extra_ignores, path, effective_baseline.as_deref());
    let walk_opts = WalkOptions {
        respect_gitignore: effective_gitignore,
        extra_ignores,
    };

    let index = walk(path, &walk_opts).context("walking repository")?;
    let report = engine
        .fix(path, &index, dry_run)
        .context("applying fixes")?;

    let (mut out, opts) = render_env(cli)?;
    format
        .write_fix_with_options(&report, &mut out, opts)
        .context("writing output")?;
    out.flush().ok();

    let exit = if report.has_unfixable_errors()
        || (cli.fail_on_warning && report.has_unfixable_warnings())
    {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    };
    Ok(exit)
}

fn cmd_list(category: Option<&str>, cli: &Cli) -> Result<ExitCode> {
    use alint_core::{Category, Level};
    use alint_output::style;

    // Validate the category slug BEFORE building the config, so a typo fails fast
    // with a clear error instead of surfacing an unrelated config-build failure.
    if let Some(slug) = category
        && Category::from_slug(slug).is_none()
    {
        let known: Vec<&str> = Category::ALL.iter().map(|c| c.slug()).collect();
        bail!(
            "unknown category {slug:?}. Known categories: {}",
            known.join(", ")
        );
    }

    let mut loaded = load_rules(Path::new("."), cli)?;
    let loaded_any = !loaded.entries.is_empty();

    // Config-scoped category filter: keep only the loaded rules whose kind is in
    // the given category, resolved through the same in-crate bridge `alint rules`
    // uses. `alint list --category X` answers "which of MY rules are X"; the
    // catalog view (all kinds alint ships) is `alint rules list --category X`.
    if let Some(slug) = category {
        loaded
            .entries
            .retain(|e| rules::categories_for_kind(&e.kind).contains(&slug));
    }

    // `list` honours --format for machine consumers: `json` emits a
    // stable rule-inventory envelope (the effective rule set, post
    // extends/overrides). Any other machine format is an explicit
    // error rather than a silent fall-through to human output.
    let format: Format = cli.format.parse().map_err(|e: String| anyhow::anyhow!(e))?;
    match format {
        Format::Human => {}
        Format::Json => return list_json(&loaded),
        _ => bail!(
            "`alint list` supports only `--format human` or `--format json` (got {:?})",
            cli.format
        ),
    }

    let (mut out, opts) = render_env(cli)?;
    if loaded.entries.is_empty() {
        // Distinguish "config defines no rules" from "the category matched none".
        match category {
            Some(slug) if loaded_any => {
                writeln!(out, "(no loaded rules are in category '{slug}')")?;
            }
            _ => writeln!(out, "(no rules loaded from config)")?,
        }
        out.flush().ok();
        return Ok(ExitCode::SUCCESS);
    }
    let dim = style::DIM;
    let docs = style::DOCS;
    for entry in &loaded.entries {
        let rule = &entry.rule;
        let level_style = match rule.level() {
            Level::Error => style::ERROR,
            Level::Warning => style::WARNING,
            Level::Info => style::INFO,
            Level::Off => style::DIM,
        };
        let label = rule.level().as_str();
        // Pad to 8 cols *after* the SGR reset so the alignment
        // is on visible glyph count, not byte count.
        let pad = " ".repeat(8usize.saturating_sub(label.len()));
        write!(
            out,
            "{level_style}{label}{level_style:#}{pad} {}",
            rule.id()
        )?;
        if entry.when.is_some() {
            write!(out, " {dim}[when]{dim:#}")?;
        }
        if opts.show_docs
            && let Some(url) = rule.policy_url()
        {
            write!(out, "  {dim}({dim:#}{docs}{url}{docs:#}{dim}){dim:#}")?;
        }
        writeln!(out)?;
    }
    out.flush().ok();
    Ok(ExitCode::SUCCESS)
}

/// Stable machine-readable rule inventory for `alint list --format json`.
/// Carries the effective rule set (after `extends:`/overrides) so fleet
/// tooling can diff "what rules are effective here" across repos. The
/// Shares the integer `schema_version: 1` with the other JSON envelopes but is
/// a DISTINCT shape — the `kind` field discriminates so a consumer can tell a
/// rule inventory from a rule definition or a check report.
fn list_json(loaded: &LoadedConfig) -> Result<ExitCode> {
    let rules: Vec<serde_json::Value> = loaded
        .entries
        .iter()
        .map(|entry| {
            serde_json::json!({
                "id": entry.rule.id(),
                "kind": entry.kind,
                "categories": rules::categories_for_kind(&entry.kind),
                "level": entry.rule.level().as_str(),
                "policy_url": entry.rule.policy_url(),
                "conditional": entry.when.is_some(),
                "fixable": entry.rule.fixer().is_some(),
            })
        })
        .collect();
    let doc = serde_json::json!({ "schema_version": 1, "kind": "rule-inventory", "rules": rules });
    let mut out = std::io::stdout().lock();
    writeln!(out, "{}", serde_json::to_string_pretty(&doc)?)?;
    out.flush().ok();
    Ok(ExitCode::SUCCESS)
}

fn cmd_facts(path: &Path, cli: &Cli) -> Result<ExitCode> {
    let loaded = load_rules(path, cli)?;
    let effective_gitignore = if cli.no_gitignore {
        false
    } else {
        loaded.respect_gitignore
    };
    let walk_opts = WalkOptions {
        respect_gitignore: effective_gitignore,
        extra_ignores: loaded.extra_ignores,
    };
    let index = walk(path, &walk_opts).context("walking repository")?;
    let values =
        alint_core::evaluate_facts(&loaded.facts, path, &index).context("evaluating facts")?;

    let format: Format = cli.format.parse().map_err(|e: String| anyhow::anyhow!(e))?;
    // `facts` has only a human and a json shape; reject other formats rather
    // than silently degrading them to human (matching `list`/`explain`).
    match format {
        Format::Human | Format::Json => {}
        _ => bail!(
            "`alint facts` supports only `--format human` or `--format json` (got {:?})",
            cli.format
        ),
    }
    let (mut out, _opts) = render_env(cli)?;
    render_facts(&loaded.facts, &values, format, &mut out)?;
    out.flush().ok();
    Ok(ExitCode::SUCCESS)
}

/// Render the resolved fact values in the requested format. Split out
/// from `cmd_facts` so the rendering logic is unit-testable without
/// standing up a full CLI invocation.
fn render_facts(
    facts: &[alint_core::FactSpec],
    values: &alint_core::FactValues,
    format: Format,
    out: &mut dyn Write,
) -> Result<()> {
    match format {
        Format::Json => render_facts_json(facts, values, out),
        // `human` is the default; `sarif` and `github` don't have a
        // natural facts shape — fall back to human rather than
        // surface a confusing empty document.
        _ => render_facts_human(facts, values, out),
    }
}

fn render_facts_human(
    facts: &[alint_core::FactSpec],
    values: &alint_core::FactValues,
    out: &mut dyn Write,
) -> Result<()> {
    use alint_output::style;

    if facts.is_empty() {
        writeln!(out, "(no facts declared in config)")?;
        return Ok(());
    }
    let id_width = facts.iter().map(|f| f.id.len()).max().unwrap_or(0);
    let kind_width = facts.iter().map(|f| f.kind.name().len()).max().unwrap_or(0);
    let dim = style::DIM;
    for spec in facts {
        let value_str = values
            .get(&spec.id)
            .map_or_else(|| "(unresolved)".to_string(), fact_value_display);
        // The kind column is the schema/type label (always
        // dimmed); value gets a tonal cue too — `true` reads
        // as success, `false` / `(unresolved)` as muted.
        let value_style = match value_str.as_str() {
            "true" => style::SUCCESS,
            "false" | "(unresolved)" => style::DIM,
            _ => style::PATH, // typed values like strings/numbers — bold but uncolored
        };
        let kind_name = spec.kind.name();
        let kind_pad = " ".repeat(kind_width.saturating_sub(kind_name.len()));
        writeln!(
            out,
            "{:<id_width$}  {dim}{kind_name}{dim:#}{kind_pad}  {value_style}{value_str}{value_style:#}",
            spec.id,
        )?;
    }
    Ok(())
}

fn render_facts_json(
    facts: &[alint_core::FactSpec],
    values: &alint_core::FactValues,
    out: &mut dyn Write,
) -> Result<()> {
    let entries: Vec<serde_json::Value> = facts
        .iter()
        .map(|spec| {
            let value = values
                .get(&spec.id)
                .map_or(serde_json::Value::Null, fact_value_json);
            serde_json::json!({
                "id": spec.id,
                "kind": spec.kind.name(),
                "value": value,
            })
        })
        .collect();
    let doc = serde_json::json!({ "schema_version": 1, "kind": "facts", "facts": entries });
    writeln!(out, "{}", serde_json::to_string_pretty(&doc)?)?;
    Ok(())
}

fn fact_value_display(v: &alint_core::FactValue) -> String {
    match v {
        alint_core::FactValue::Bool(b) => b.to_string(),
        alint_core::FactValue::Int(n) => n.to_string(),
        alint_core::FactValue::String(s) => {
            // Quote strings so an empty value doesn't render as a
            // blank column and so leading/trailing whitespace is
            // visible.
            format!("{s:?}")
        }
    }
}

fn fact_value_json(v: &alint_core::FactValue) -> serde_json::Value {
    match v {
        alint_core::FactValue::Bool(b) => serde_json::Value::Bool(*b),
        alint_core::FactValue::Int(n) => serde_json::Value::Number((*n).into()),
        alint_core::FactValue::String(s) => serde_json::Value::String(s.clone()),
    }
}

fn cmd_explain(rule_id: &str, cli: &Cli) -> Result<ExitCode> {
    use alint_core::Level;
    use alint_output::style;

    let loaded = load_rules(Path::new("."), cli)?;
    let Some(entry) = loaded.entries.iter().find(|e| e.rule.id() == rule_id) else {
        bail!("no rule with id {rule_id:?} found in the effective config");
    };
    let rule = &entry.rule;

    // `explain` honours --format for machine consumers, matching `list`:
    // `json` emits the rule's wire-shape; any other machine format is an
    // explicit error rather than silently printing the human block.
    let format: Format = cli.format.parse().map_err(|e: String| anyhow::anyhow!(e))?;
    match format {
        Format::Human => {}
        Format::Json => return explain_json(entry),
        _ => bail!(
            "`alint explain` supports only `--format human` or `--format json` (got {:?})",
            cli.format
        ),
    }

    let (mut out, opts) = render_env(cli)?;
    let dim = style::DIM;
    let docs = style::DOCS;
    let level_style = match rule.level() {
        Level::Error => style::ERROR,
        Level::Warning => style::WARNING,
        Level::Info => style::INFO,
        Level::Off => style::DIM,
    };
    writeln!(out, "{dim}id:        {dim:#} {}", rule.id())?;
    writeln!(
        out,
        "{dim}level:     {dim:#} {level_style}{}{level_style:#}",
        rule.level().as_str(),
    )?;
    // v0.9.20: honour --no-docs by suppressing the policy_url line.
    // URLs remain in machine-readable formats regardless.
    if opts.show_docs
        && let Some(url) = rule.policy_url()
    {
        writeln!(out, "{dim}policy_url:{dim:#} {docs}{url}{docs:#}")?;
    }
    if let Some(when) = &entry.when {
        writeln!(out, "{dim}when:      {dim:#} {when:?}")?;
    }
    out.flush().ok();
    // v0.9.20: dropped the `debug: {rule:?}` line. The internal Debug
    // repr dumped per-rule-kind state (regex automaton, compiled
    // matchers, etc.) — useful for alint developers, noise for end
    // users (24+ KB for some rule kinds). Use `--format json` (here or
    // on `alint check`) if you need the wire-shape, or read the rule's
    // YAML config block.
    Ok(ExitCode::SUCCESS)
}

/// Machine-readable single-rule shape for `alint explain <id> --format
/// json`. Parallels each entry of the `list --format json` inventory.
fn explain_json(entry: &alint_core::RuleEntry) -> Result<ExitCode> {
    let doc = serde_json::json!({
        "schema_version": 1,
        "kind": "rule",
        "id": entry.rule.id(),
        "level": entry.rule.level().as_str(),
        "policy_url": entry.rule.policy_url(),
        "conditional": entry.when.is_some(),
        "fixable": entry.rule.fixer().is_some(),
    });
    let mut out = std::io::stdout().lock();
    writeln!(out, "{}", serde_json::to_string_pretty(&doc)?)?;
    out.flush().ok();
    Ok(ExitCode::SUCCESS)
}

/// Build the stdout writer + human-format options from the
/// user's `--color` / `--ascii` flags.
///
/// The returned writer is an `anstream::AutoStream` that strips
/// ANSI SGR codes automatically when the underlying stream isn't
/// a TTY (or when `NO_COLOR` is set, or when `--color=never` was
/// passed). Formatters can therefore emit styled output
/// unconditionally.
fn render_env(
    cli: &Cli,
) -> Result<(
    anstream::AutoStream<std::io::StdoutLock<'static>>,
    HumanOptions,
)> {
    let choice: ColorChoice = cli.color.parse().map_err(|e: String| anyhow::anyhow!(e))?;
    // Pre-resolve `Auto` against CLICOLOR_FORCE before handing
    // off to anstream — anstream's Auto honors NO_COLOR + TTY
    // but doesn't consult CLICOLOR_FORCE on its own.
    let choice = choice.resolve();
    let stdout = io::stdout();
    let is_tty = stdout.is_terminal();
    let lock = stdout.lock();
    let stream = anstream::AutoStream::new(lock, choice.to_anstream());

    // Hyperlink detection needs a TTY to matter; piped output that
    // happens to survive (because `--color=always`) still won't be
    // rendered as a link by anything downstream. The
    // `ALINT_FORCE_HYPERLINKS=1` escape hatch overrides both checks:
    // used by the asciinema demo capture (stdout redirected to a
    // file, so `is_tty=false`, but the cast is replayed inside an
    // OSC-8-supporting terminal emulator and should carry the
    // hyperlink semantic). Empty / `0` values do NOT force.
    let force_hyperlinks =
        std::env::var_os("ALINT_FORCE_HYPERLINKS").is_some_and(|v| !v.is_empty() && v != *"0");
    let hyperlinks = force_hyperlinks
        || (is_tty && supports_hyperlinks::on(supports_hyperlinks::Stream::Stdout));

    // Only ask the kernel for columns when we know we're on a TTY.
    // Pipes have no useful width; let the formatter fall back to
    // its DEFAULT_WIDTH constant. `--width` always wins when set
    // (reproducible captures, narrow CI, manual overrides).
    let width = cli.width.or_else(|| {
        if is_tty {
            terminal_size::terminal_size().map(|(w, _)| usize::from(w.0))
        } else {
            None
        }
    });

    let opts = HumanOptions {
        glyphs: GlyphSet::detect(cli.ascii),
        hyperlinks,
        width,
        compact: cli.compact,
        show_docs: !cli.no_docs,
    };
    Ok((stream, opts))
}

struct LoadedConfig {
    entries: Vec<alint_core::RuleEntry>,
    registry: RuleRegistry,
    facts: Vec<alint_core::FactSpec>,
    vars: std::collections::HashMap<String, String>,
    respect_gitignore: bool,
    extra_ignores: Vec<String>,
    fix_size_limit: Option<u64>,
    /// The `baseline:` config key (the raw repo-root-relative path), if set.
    baseline: Option<PathBuf>,
}

/// Load the effective config from disk and instantiate every rule,
/// parsing any `when:` clauses into AST at build time.
/// `alint validate-config <path>` — Phase 6 of v0.9.15.
///
/// Runs the same load + build + when-parse path as `check`, but
/// stops before the engine spins up. Editor LSP, pre-commit hooks,
/// and fail-fast CI steps want to know "is the config loadable?"
/// without paying for a tree walk.
///
/// Exit codes:
/// - `0` — config valid, all N rules built cleanly
/// - `1` — config invalid (load / build / when-parse error). The
///   underlying error message includes the v0.9.15 Phase 3 +
///   Phase 4 enrichments (did-you-mean, `JSONPath` dashed-key hints,
///   `&&` → `and` keyword hints, etc.)
/// - `2` — invocation error (file missing, etc.) — propagated by
///   `main`'s top-level error handler.
/// - `3` — internal error (e.g. a bundled ruleset shipped inside the binary
///   fails to parse) — classified by `error_is_internal`, distinguishing an
///   alint bug from a user-fixable config problem (M11).
fn cmd_validate_config(path: Option<PathBuf>, format: &str, cli: &Cli) -> Result<ExitCode> {
    // Fail loudly on a format this subcommand can't render, rather than
    // silently falling through to human output (M13) — mirroring how
    // `list` / `facts` / `explain` gate their format. This catches the value
    // regardless of position (a global `--format sarif` before the subcommand
    // is merged into this `format` by clap). validate-config has only a human
    // and a json renderer.
    let fmt: Format = format.parse().map_err(|e: String| anyhow::anyhow!(e))?;
    if !matches!(fmt, Format::Human | Format::Json) {
        bail!(
            "`alint validate-config` supports only `--format human` or `--format json` (got {format:?})"
        );
    }

    // Resolve the config path. Three sources, in priority order:
    // 1. positional `path` arg — file path or directory (most explicit;
    //    editor LSP invocations pass the YAML file directly, while
    //    `validate-config .` is a natural shorthand for "validate the
    //    config in this repo")
    // 2. `--config` global flag (carried via `cli.config`)
    // 3. discovery from the current directory (same as `check`)
    let config_path: PathBuf = if let Some(p) = path {
        if p.is_dir() {
            if let Some(found) = alint_dsl::discover(&p) {
                found
            } else {
                let err = anyhow::anyhow!(
                    "no .alint.yml found under directory {} \
                     (run `alint init` there to scaffold one)",
                    p.display()
                );
                return emit_validate_failure(&err, None, format);
            }
        } else {
            p
        }
    } else if let Some(first) = cli.config.first() {
        first.clone()
    } else if let Some(p) = alint_dsl::discover(Path::new(".")) {
        p
    } else {
        let err = anyhow::anyhow!(
            "no .alint.yml found (searched from {}) \
             (run `alint init` to scaffold one)",
            Path::new(".").display()
        );
        return emit_validate_failure(&err, None, format);
    };

    if !config_path.exists() {
        let err = anyhow::anyhow!("config file not found: {}", config_path.display());
        return emit_validate_failure(&err, Some(&config_path), format);
    }

    // Same load + build + when-parse path as `check`, with the
    // failures plumbed back as a Result for the validate handler
    // rather than aborting the run.
    match validate_config_inner(&config_path) {
        Ok(rule_count) => emit_validate_success(rule_count, &config_path, format),
        Err(e) => emit_validate_failure(&e, Some(&config_path), format),
    }
}

fn validate_config_inner(config_path: &Path) -> Result<usize> {
    let config = alint_dsl::load(config_path)?;
    let registry: alint_core::RuleRegistry = alint_rules::builtin_registry();
    let mut count = 0usize;
    for spec in &config.rules {
        if matches!(spec.level, alint_core::Level::Off) {
            continue;
        }
        let rule = registry
            .build(spec)
            .with_context(|| format!("building rule {:?}", spec.id))?;
        // Structurally validate any nested `require:` sub-rules (unknown
        // kind / option / missing field) — the cross-file iteration rules
        // build these lazily, so without this they slip past validate-config.
        rule.validate_nested(&registry)
            .with_context(|| format!("building rule {:?}", spec.id))?;
        if let Some(when_src) = &spec.when {
            alint_core::when::parse(when_src)
                .with_context(|| format!("rule {:?}: parsing `when`", spec.id))?;
        }
        count += 1;
    }
    Ok(count)
}

fn emit_validate_success(rule_count: usize, config_path: &Path, format: &str) -> Result<ExitCode> {
    if format == "json" {
        let envelope = serde_json::json!({
            "valid": true,
            "rule_count": rule_count,
            "config_path": config_path.display().to_string(),
            "error": serde_json::Value::Null,
        });
        println!("{}", serde_json::to_string(&envelope)?);
    } else {
        // human format
        println!(
            "✓ Config valid: {rule_count} rule(s) loaded from {}",
            config_path.display()
        );
    }
    Ok(ExitCode::SUCCESS)
}

fn emit_validate_failure(
    err: &anyhow::Error,
    config_path: Option<&Path>,
    format: &str,
) -> Result<ExitCode> {
    if format == "json" {
        // Render the error chain as a single string so editors get
        // the full context including did-you-mean hints.
        let chain = format!("{err:#}");
        let envelope = serde_json::json!({
            "valid": false,
            "rule_count": 0,
            "config_path": config_path.map(|p| p.display().to_string()),
            "error": chain,
        });
        println!("{}", serde_json::to_string(&envelope)?);
    } else {
        // Human format prints to stderr to stay out of the way of
        // stdout consumers, then a one-line summary on stdout so
        // terminals show something either way.
        eprintln!("alint: {err:#}");
        println!("✗ Config invalid");
    }
    // An internal error (an alint bug — e.g. a shipped bundled ruleset that
    // fails to parse) is not the user's config being "invalid"; surface it as
    // exit 3 to match main()'s classification, not the exit 1 used for a
    // genuinely-invalid config (M11-F1). The error text (above) already names
    // it as internal.
    if error_is_internal(err) {
        Ok(ExitCode::from(3))
    } else {
        Ok(ExitCode::from(1))
    }
}

fn load_rules(cwd: &Path, cli: &Cli) -> Result<LoadedConfig> {
    let config_path = if let Some(first) = cli.config.first() {
        first.clone()
    } else {
        alint_dsl::discover(cwd).ok_or_else(|| {
            anyhow::anyhow!(
                "no .alint.yml found (searched from {}) \
                 (run `alint init` to scaffold one)",
                cwd.display()
            )
        })?
    };
    tracing::debug!(?config_path, "loading config");
    let config = alint_dsl::load(&config_path)?;

    let registry: RuleRegistry = alint_rules::builtin_registry();

    let mut entries: Vec<alint_core::RuleEntry> = Vec::with_capacity(config.rules.len());
    for spec in &config.rules {
        if matches!(spec.level, alint_core::Level::Off) {
            continue;
        }
        let mut rule = registry
            .build(spec)
            .with_context(|| format!("building rule {:?}", spec.id))?;
        // Structurally validate nested `require:` sub-rules at load, so a
        // typo'd nested kind/option fails here rather than lazily mid-walk
        // (or never, when the selector matches no entries).
        rule.validate_nested(&registry)
            .with_context(|| format!("building rule {:?}", spec.id))?;
        // Apply the top-level `allow_out_of_root:` policy (parsed from
        // the user's own config only — never from `extends:`). A rule
        // not opted in stays confined (the setter is a no-op for every
        // kind that doesn't honor the flag).
        let allow_out_of_root = config.allow_out_of_root.allows(&spec.id, &spec.kind);
        rule.set_allow_out_of_root(allow_out_of_root);
        let mut entry = alint_core::RuleEntry::new(rule)
            .with_kind(spec.kind.clone())
            .with_allow_out_of_root(allow_out_of_root);
        if let Some(when_src) = &spec.when {
            let expr = alint_core::when::parse(when_src)
                .with_context(|| format!("rule {:?}: parsing `when`", spec.id))?;
            entry = entry.with_when(expr);
        }
        entries.push(entry);
    }
    Ok(LoadedConfig {
        entries,
        registry,
        facts: config.facts,
        vars: config.vars,
        respect_gitignore: config.respect_gitignore,
        extra_ignores: config.ignore,
        fix_size_limit: config.fix_size_limit,
        baseline: config.baseline,
    })
}

#[cfg(test)]
mod tests;