mds-cli 0.4.4

MDS (Markdown Script) compiler — command-line interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
//! `lint` subcommand — static analysis of MDS templates beyond `mds check` (issue #61).
//!
//! # Input modes
//!
//! - File path: lint a single `.mds` file (base_dir = file's parent).
//! - Directory: recursively lint every `.mds` file INCLUDING partials, accumulate
//!   and continue past per-file failures, exit = max severity across all files.
//! - `-` (stdin): read from stdin, report diagnostics to stderr, exit by severity.
//!   With `--fix`: fixed source → stdout, diagnostics → stderr.
//!
//! # Channel discipline
//!
//! - Human diagnostics → **stderr** via miette Report.
//! - `--format json` output → **stdout** only (single JSON object, trailing newline).
//! - `--quiet` suppresses warning+info human diagnostics and summaries, NOT errors.
//!
//! # `--quiet` status-message contract (#216, decision D4)
//!
//! Every *status* message on stderr is gated on `!quiet` wherever it is emitted.
//! Per-mode scope (PF-015: scoped claim rather than vacuously-true absolute).
//! Directory mode has two separate emitters (`lint_one_file_human` for --format
//! human and `lint_one_file_accumulating` for --format json), giving four emitter
//! sites in total. `Partially fixed:`, `Would fix:`, `fix rejected:`, and the
//! diagnostic-cap notice are gated at all four sites (single-file, directory-human,
//! directory-JSON, stdin). `Fixed:` is emitted in single-file and both directory
//! modes (both human and JSON); stdin emits `Partially fixed:` but no `Fixed:` —
//! the fixed source on stdout is the signal. `Clean:` is single-file mode only;
//! the directory summary is directory mode only.
//! PF-004: these are separate emitters; a gate on one is not inherited by the others
//! (the #43/#173 divergence class).
//!
//! Two messages deliberately bypass `--quiet` because they signal a silent-CI-green-pass
//! hazard rather than status: the all-excluded diagnostic in [`run_lint_directory`] and
//! the directory summary when any file is in the error or resource-limited bucket.
//! A third emitter also bypasses `--quiet`: `output::collect_mds_files_inner`'s
//! depth-limit warning (fires on trees deeper than MAX_DEPTH=64) accepts no quiet
//! parameter — documented limitation per AC-Q05/PF-015, mirroring `build.rs`.
//!
//! # Diagnostic path anchors (directory-mode divergence, R3 / CWE-209)
//!
//! Two path families appear in lint output and deliberately use different
//! anchor directories in directory mode:
//!
//! - **Rule diagnostics** display *walk-root-relative* paths: `diag.file` is
//!   overwritten via [`set_diag_display_path`] with the path relative to the
//!   linted directory (the walk root), keeping per-file output stable and
//!   sortable within one run.
//! - **Analysis-failure frames** (parse/resolve/IO/config-load errors) display
//!   *project-root-relative* paths: mds-core relativizes `NamedSource` names and
//!   message paths at construction time against the `.mdsroot` / `.git` walk-up
//!   root (R3), and [`read_source_file`] anchors the same root for raw-read
//!   errors.
//!
//! The two anchors differ, but both are safe: neither surface ever shows an
//! absolute path (basename fallback outside the root).
//!
//! # Exit codes (via direct `std::process::exit`, NEVER via `exit_code()`)
//!
//! - 0: clean (no Warn/Error findings)
//! - 1: warning-severity findings only, no errors
//! - 2: any error-severity finding OR analysis failure (parse/resolve/IO/config-load)
//!   OR usage error
//! - 3: ResourceLimit
//!
//! With `--fix`, residual post-fix findings determine the exit code.

use std::cell::RefCell;
use std::collections::HashMap;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::rc::Rc;

use mds::{effective_parent, FileSystem, MdsError, NativeFs, Severity};
use miette::Result;

use crate::build::{
    build_runtime_vars, emit_duplicate_var_warnings, ensure_existing_mds_file, load_config,
    read_stdin, resolve_input, RuntimeVarArgs,
};
use crate::output::{
    atomic_write_file, collect_mds_files_detailed, eprint_error, eprint_warning,
    relabel_stdin_error, render_unified_diff, safe_file_display, safe_inline, safe_path,
    Durability, STDIN_DISPLAY_LABEL,
};

// AC-224-15: No local rule-name list. The single source of truth is
// mds::KNOWN_LINT_RULES (composed from each rule module's own RULE const).
// No rule-name string literals from the registry appear in this directory.

pub(crate) struct LintArgs {
    pub(crate) input: Option<PathBuf>,
    /// Apply fixes automatically (Tier A always, Tier B when standalone).
    pub(crate) fix: bool,
    /// Preview --fix: exit 1 if any file would change; never writes.
    pub(crate) check: bool,
    /// Preview --fix: print unified diff; never writes.
    pub(crate) diff: bool,
    pub(crate) quiet: bool,
    pub(crate) format: LintFormat,
    pub(crate) vars: Option<PathBuf>,
    pub(crate) set_vars: Vec<(String, String)>,
    pub(crate) set_string_vars: Vec<(String, String)>,
}

/// Output format for lint diagnostics.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum LintFormat {
    Human,
    Json,
}

/// Bundled mode flags to avoid positional-bool transposition hazard.
#[derive(Clone, Copy)]
struct LintFlags {
    fix: bool,
    check: bool,
    diff: bool,
    quiet: bool,
    format: LintFormat,
}

/// Entry point for `mds lint`. Always returns `Ok(())`; exits are via
/// `std::process::exit()` for lint-specific codes, or via the outer `run()`
/// error handler for setup failures (which also exit 2 via this function's catch).
pub(crate) fn run_lint(args: LintArgs) -> Result<()> {
    match do_lint(args) {
        Ok(()) => Ok(()),
        Err(e) => {
            // Route through the single render choke point (avoids PF-004 /
            // architecture-6: hand-rolled sanitize_control_chars bypass).
            eprint_error(e);
            std::process::exit(2);
        }
    }
}

/// Inner runner — all setup errors propagate as `Err`; `run_lint` catches and exits 2.
fn do_lint(args: LintArgs) -> Result<()> {
    let LintArgs {
        input,
        fix,
        check,
        diff,
        quiet,
        format,
        vars,
        set_vars,
        set_string_vars,
    } = args;

    let flags = LintFlags {
        fix,
        check,
        diff,
        quiet,
        format,
    };

    let resolved = match build_runtime_vars(RuntimeVarArgs {
        vars,
        set_vars,
        set_string_vars,
    }) {
        Ok(r) => r,
        Err(e) => {
            // R4 carve-out — scope: EXACTLY this one variant, nothing wider.
            // A --set/--set-string collision is a usage error over runtime
            // VARIABLES, not an analysis failure: build/check/watch exit 1 for
            // it via `exit_code()`, so lint must not blanket-exit 2 for the
            // same mistake.  Downcast BEFORE any render call (`eprint_error`
            // consumes the report).  Routing through
            // emit_analysis_failure_json_or_stderr also gives --format json
            // consumers the structured `mds::var_conflict` envelope (AC-F-14).
            // Every OTHER setup error deliberately keeps the blanket exit 2
            // in run_lint's catch.
            if let Some(mds_err @ MdsError::VarConflict { .. }) = e.downcast_ref::<MdsError>() {
                emit_analysis_failure_json_or_stderr(mds_err, format, None);
                std::process::exit(1);
            }
            return Err(e);
        }
    };
    emit_duplicate_var_warnings(&resolved, quiet);
    let runtime_vars = resolved.vars;

    let (input, _auto_detected) = resolve_input(input, "lint")?;

    // USAGE ERROR: --fix + --format json + stdin (AC-F-22b).
    // DELIBERATE EXCEPTION (AC-F-14): the JSON envelope is deferred for this 3-way combo;
    // it stays a plain stderr usage message. All other top-level analysis failures route
    // through emit_analysis_failure_json_or_stderr when --format json is active.
    if fix && format == LintFormat::Json && input == Path::new("-") {
        eprintln!(
            "error: --fix --format json with stdin input is not supported; \
             use `mds lint --fix -` for filter mode or `mds lint --format json` for JSON output"
        );
        std::process::exit(2);
    }

    // Stdin mode.
    if input == Path::new("-") {
        return run_lint_stdin(flags, runtime_vars);
    }

    // Directory mode.
    if input.is_dir() {
        // Reject a symlinked directory root (build/check/fmt parity).
        if input
            .symlink_metadata()
            .map(|m| m.file_type().is_symlink())
            .unwrap_or(false)
        {
            // Directory-root symlink → JSON envelope in --format json mode (AC-F-14).
            let mds_err = MdsError::Io {
                message: format!(
                    "directory argument must not be a symlink: {}",
                    input.display()
                ),
            };
            emit_analysis_failure_json_or_stderr(&mds_err, format, None);
            std::process::exit(2);
        }
        return run_lint_directory(&input, flags, runtime_vars);
    }

    // Single-file mode.
    // Check existence first, then extension (C4/F6): a non-existent path must report
    // mds::file_not_found, not mds::not_mds_file, regardless of the extension.
    // Route through emit_analysis_failure_json_or_stderr so --format json produces the
    // correct error envelope (L-CLI-JSON4 / AC-F-14). Do NOT use `?` here.
    if let Err(mds_err) = ensure_existing_mds_file(&input) {
        emit_analysis_failure_json_or_stderr(&mds_err, format, None);
        std::process::exit(mds_error_exit_code(&mds_err));
    }
    run_lint_file(&input, flags, runtime_vars)
}

// ── Config helpers ────────────────────────────────────────────────────────────

/// Load mds.json and extract the core `LintConfig`, warning about unknown rule names.
///
/// AD-224-1 (2026-08-12 ruling): an unknown rule name WARNS and lint CONTINUES.
/// The domain is asymmetric — severities are a closed set but rule names grow
/// every release — so hard-failing would break configs naming rules from a newer
/// mds when run with an older binary.
///
/// AD-224-5 (AC-224-21, AC-224-22): the warning goes to STDERR only (never
/// stdout — `--format json` stdout must remain valid parseable JSON), and is
/// SUPPRESSED under `--quiet` (AC-224-22, coordination point with PR4 D4): the
/// unknown-rule warning is never the causal reason for a non-zero exit — an
/// unknown rule has no enforcement and does not affect `result_exit_code`, which
/// counts actual lint findings, not config anomalies. A `--quiet` consumer who
/// receives a non-zero exit will always have a visible, causal lint finding.
/// `crates/mds-cli/src/main.rs:30` documents `--quiet` as suppressing
/// *"status and diagnostic output"*; this warning is status, not an error.
fn load_lint_config(dir: &Path, quiet: bool) -> Result<mds::LintConfig> {
    let config_opt = load_config(dir)?;
    match config_opt {
        None => Ok(mds::LintConfig::default()),
        Some((mds_config, _config_dir)) => {
            // into_core_config returns (config, Option<UnknownRuleNames>) in one step —
            // structurally forcing the caller to handle the unknowns report so detection
            // cannot be accidentally skipped (review finding at config.rs:104).
            // The safe_inline / print-discipline contract (AD-224-3, AC-224-6) and the
            // --quiet gate (AD-224-5, AC-224-22) are documented at `emit_unknown_rule_warning`.
            let (lint_config, unknown) = mds_config.lint.into_core_config();
            if let Some(unknown) = unknown {
                emit_unknown_rule_warning(&unknown, quiet);
            }
            Ok(lint_config)
        }
    }
}

/// Emit the unknown-rule warning for one config load, suppressed under `--quiet`.
///
/// Both `load_lint_config` (stdin/single-file path) and `LintDirCtx::config_for`
/// (directory path) call this function. One definition prevents the duplication
/// that already drifted once inside this PR on the CWE-117 escape path (PF-009:
/// the same work set represented twice drifts; ADR-008: the escape contract is
/// per-file, so every call site is equally security-relevant).
///
/// AC-224-3 (amended criterion, repo-owner ruling 2026-08-16): the criterion requires
/// a shared message body, a shared recognised-rules list, and a shared sort order
/// across all five surfaces. The CLI prefix `"warning: in mds.json: "` is permitted
/// by the amended criterion; it carries source-file provenance that the bindings
/// cannot provide because their rules arrive in the caller's options object, not a
/// config file. One formatter ([`mds::format_unknown_rule_names_warning`]) produces
/// the shared body; the CLI adds the provenance prefix before emitting on stderr.
///
/// AD-224-3 (AC-224-6): every value interpolated inside `eprint_warning`'s
/// `format!` must be a WHOLE-EXPRESSION `safe_inline` call — the one shape that
/// `print_discipline.rs`'s trace accepts without an allowlist entry. Keeping the
/// `eprint_warning` call here (in a named function inside `crates/mds-cli/src/`)
/// preserves that machine-checked coverage: the scanner enumerates every `.rs`
/// file under `src/` and checks every `eprint_warning(…)` call site it finds.
/// `safe_inline(&core_msg)` satisfies that constraint; the call is idempotent
/// because names are already wire-escaped inside `format_unknown_rule_names_warning`.
///
/// AD-224-5 (AC-224-22): no-op when `quiet` is true.
fn emit_unknown_rule_warning(unknown: &mds::UnknownRuleNames, quiet: bool) {
    if quiet {
        return;
    }
    // AC-224-3: shared message body; "in mds.json:" prefix carries source provenance.
    let core_msg = mds::format_unknown_rule_names_warning(unknown);
    eprint_warning(&format!("warning: in mds.json: {}", safe_inline(&core_msg)));
}

// ── Display-path remap ────────────────────────────────────────────────────────

/// Remap the `file` field in every diagnostic in `result` to `display`.
///
/// `mds::lint(path, …)` sets each diagnostic's `file` to the file's basename
/// (via `path.file_name()`). In directory mode the same basename appears for
/// every file, so the JSON output groups all findings under the same key.
/// This function replaces the field with the caller-supplied relative path so
/// the JSON output uses distinct, navigable paths.
///
/// **AD-211-4 (stdin relabel):** also used for stdin mode — called with
/// `STDIN_DISPLAY_LABEL` immediately after every `mds::lint_str_with` call so
/// that `diag.file` in the JSON wire output reads `"<stdin>"` rather than the
/// internal VFS key `"input.mds"` (`STRING_SOURCE_MAP_LABEL`).
///
/// Call this immediately after every `mds::lint` / `mds::lint_str_with` call.
fn set_diag_display_path(result: &mut mds::LintResult, display: &str) {
    for diag in &mut result.diagnostics {
        diag.file = Some(display.to_string());
    }
}

/// Returns the path of `path` relative to `root`, normalised to forward-slash
/// separators by joining path components with `/`.
///
/// Using `Path::components()` is the correct platform-aware join: on Windows a
/// backslash is a path separator, so each component is a directory or filename
/// segment; on Unix a backslash is an ordinary filename byte (POSIX forbids
/// only `/` and NUL), so a single component carries the whole
/// `\`-containing filename intact.  The naive `.replace('\\', "/")` alternative
/// would manufacture a path separator from an ordinary filename byte on Unix,
/// turning `sub/..\..\etc\evil.mds` into `sub/../../../etc/evil.mds` and
/// providing a directory-traversal vector (CWE-22/CWE-41).
///
/// The directory-mode sort applies `sanitize_control_chars_wire` on top of
/// this function's output so that the sort key matches the sanitized
/// `files[].file` value emitted by `to_canonical_json` for diagnostic entries,
/// keeping array position consistent with the emitted key order (AC-P1-10).
/// Error-only entries (`{"file": …, "error": …}`) bypass `to_canonical_json`
/// and therefore its own `sanitize_control_chars_wire` pass; they are instead
/// pre-sanitized at the push site via `file_key` — so both diagnostic and
/// error-only entry types carry identically-sanitized `file` values (ADR-008).
///
/// Forward slashes (`/`, 0x2F) are used instead of
/// the native backslash separator (`\`, 0x5C) because bytes in the range
/// 0x30–0x5B (digits `0`–`9`, uppercase letters `A`–`Z`, and `[`) sort between
/// `/` and `\`; on Windows a flat file like `sub[abc.mds` would sort BEFORE a
/// nested path `sub\d.mds` using the native separator (0x5B < 0x5C), but AFTER
/// it with the emitted forward slash (0x5B > 0x2F), reversing the array order
/// relative to the emitted key order.
///
/// # Fail-closed contract (#217)
///
/// The returned string is the directory-mode `files[].file` key and the sort key.
/// A path that is not under `root`, that yields a non-`Normal` component after
/// the strip, or that is not valid UTF-8 is an `Io` error — never a lossy
/// (U+FFFD) or absolute key.
fn relative_display(path: &Path, root: &Path) -> std::result::Result<String, MdsError> {
    let escapes = || MdsError::Io {
        message: format!(
            "path escapes lint root {}: {}",
            root.display(),
            path.display()
        ),
    };
    let rel = path.strip_prefix(root).map_err(|_| escapes())?;
    let mut out = String::new();
    for c in rel.components() {
        // Only `Normal` can follow a successful strip of a read_dir entry; RootDir /
        // Prefix / ParentDir here means the invariant above is broken — reject rather
        // than join them into `//foo` (Unix) or `C:/\/foo` (Windows) or drop a `..`.
        let std::path::Component::Normal(name) = c else {
            return Err(escapes());
        };
        // Same wording as `read_source_file`'s non-UTF-8 rejection, which is what a
        // per-file read of this entry would have produced before the run-level check.
        let name = name.to_str().ok_or_else(|| MdsError::Io {
            message: format!("path is not valid UTF-8: {}", path.display()),
        })?;
        if !out.is_empty() {
            out.push('/');
        }
        out.push_str(name);
    }
    Ok(out)
}

// ── Read source file ──────────────────────────────────────────────────────────

/// Read raw source of `path`: symlink-checked and size-capped (mirrors fmt.rs).
///
/// Returns `MdsError` (not `miette::Error`) so callers can feed the error into
/// `emit_analysis_failure_json_or_stderr` without downcasting (AC-F-14).
fn read_source_file(path: &Path) -> std::result::Result<String, MdsError> {
    let canonical = NativeFs::check_symlink(path)?;
    let path_str = canonical.to_str().ok_or_else(|| MdsError::Io {
        message: format!("path is not valid UTF-8: {}", path.display()),
    })?;
    let fs = NativeFs::new();
    // R3 / CWE-209: anchor the display root (project-root walk-up from the
    // file's directory) BEFORE read(), so read-error messages show a
    // project-root-relative path instead of falling back to the bare basename.
    // Best-effort like the resolver's defense-in-depth guard: on failure the
    // display degrades to the basename fallback, which is still never absolute.
    let _ = fs.set_root(&effective_parent(&canonical).display().to_string());
    fs.read(path_str)
}

// ── stdout write ──────────────────────────────────────────────────────────────

/// Write `s` to stdout, treating a broken pipe as a clean early exit rather
/// than an error — matches Unix filter conventions (e.g. `mds lint --fix - | head
/// -n1` closing the pipe early must not surface as a crash or failure).
/// Flushes explicitly so a fixed source not ending in `\n` is never silently
/// truncated before the `std::process::exit` that may follow immediately.
fn write_stdout(s: &str) -> Result<()> {
    let mut stdout = std::io::stdout();
    if let Err(e) = stdout.write_all(s.as_bytes()) {
        if e.kind() == std::io::ErrorKind::BrokenPipe {
            return Ok(());
        }
        return Err(miette::miette!("cannot write to stdout: {e}"));
    }
    if let Err(e) = stdout.flush() {
        if e.kind() != std::io::ErrorKind::BrokenPipe {
            return Err(miette::miette!("cannot flush stdout: {e}"));
        }
    }
    Ok(())
}

// ── Human diagnostic rendering ────────────────────────────────────────────────

/// Render one lint diagnostic to stderr. All user-controlled text — message, help,
/// filename, and source — is sanitized at the input boundary so miette renders from
/// safe inputs; the frame itself is not post-processed (PF-014).
///
/// `--quiet` suppresses Warn and Info; Error always renders.
/// `named_source`: `(filename, source_text)` pair for span context rendering.
///
/// Sanitization strategy (PF-014):
/// - message/help: HUMAN-mode `sanitize_control_chars` → \\uXXXX escapes. `\n` is
///   preserved so a multi-line diagnostic frame keeps rendering.
/// - filename + source: `mds::named_source_for_render`, the shared boundary
///   `MdsError::at()` and the formatter also use — WIRE-mode escaping for the
///   single-line filename, byte-length-preserving neutralization for the span-indexed
///   source so miette's byte-offset slices stay valid.
///
/// The rendered miette frame is NOT post-processed, so miette's own SGR colour codes
/// are never corrupted.
fn render_diag_human(diag: &mds::LintDiagnostic, quiet: bool, named_source: (&str, &str)) {
    if quiet && matches!(diag.severity, Severity::Info | Severity::Warn) {
        return;
    }
    // Sanitize message and help at the input boundary via the core method.
    // fix_removals/fix_edits are set to None inside sanitized_for_render to avoid
    // unnecessary allocations (architecture-3 / rust-1).
    let sanitized = diag.sanitized_for_render();
    let (filename, src) = named_source;
    let report = miette::Report::from(sanitized)
        .with_source_code(mds::named_source_for_render(filename, src));
    eprint_error(report);
}

/// Render all diagnostics in a `LintResult` to stderr.
///
/// `named_source` is forwarded to `render_diag_human` for span context rendering.
fn render_result_human(result: &mds::LintResult, quiet: bool, named_source: (&str, &str)) {
    for diag in &result.diagnostics {
        render_diag_human(diag, quiet, named_source);
    }
}

// ── Exit code helpers ─────────────────────────────────────────────────────────

/// Compute the lint exit code from a `LintResult` (not considering analysis failures).
///
/// - 2: at least one Error-severity finding
/// - 1: at least one Warn-severity finding (no errors)
/// - 0: clean (Info/Off only, or empty)
fn result_exit_code(result: &mds::LintResult) -> i32 {
    let has_error = result
        .diagnostics
        .iter()
        .any(|d| d.severity == Severity::Error);
    let has_warn = result
        .diagnostics
        .iter()
        .any(|d| d.severity == Severity::Warn);
    if has_error {
        2
    } else if has_warn {
        1
    } else {
        0
    }
}

/// Compute exit code for an `MdsError` from the lint pipeline.
///
/// - 3: ResourceLimit
/// - 2: everything else (parse, resolve, IO, usage, etc.)
fn mds_error_exit_code(err: &MdsError) -> i32 {
    match err {
        MdsError::ResourceLimit { .. } => 3,
        _ => 2,
    }
}

/// Exit the process with the severity-derived lint exit code when non-zero;
/// no-op for clean (`exit == 0`) results.
///
/// Exit codes: 0 clean / 1 warn-only / 2 error-or-analysis-failure / 3 resource-limit.
fn exit_by_severity(result: &mds::LintResult) {
    let exit = result_exit_code(result);
    if exit != 0 {
        std::process::exit(exit);
    }
}

/// Exit code for a preview (`--fix --check` / `--fix --diff`) that WOULD change
/// the file: `max(1, residual severity)` (R1, binding rule).
///
/// The floor of 1 signals "fixes pending" (the `--check` CI contract); residual
/// error-severity findings that `--fix` could not remove raise it to 2, so the
/// preview never reports success-shaped exit codes for a tree the real `--fix`
/// would leave failing.  The residual can never EXCEED the pre-fix severity —
/// the reverify gate refuses edits that add findings — so the pre-fix body the
/// preview emits and the residual-derived exit cannot contradict each other.
fn preview_exit_code(residual: &mds::LintResult) -> i32 {
    result_exit_code(residual).max(1)
}

// ── Fix pipeline helpers ──────────────────────────────────────────────────────

/// Outcome of the `--fix` pipeline for one file.
enum FixFileOutcome {
    Fixed {
        new_source: String,
        residual: mds::LintResult,
    },
    /// Some edits applied, some individually rejected by the per-edit reverify gate.
    ///
    /// Produced when `apply_fixes_incremental` falls back to the per-edit path and not
    /// all edits pass. The `new_source` is the partially-fixed text; `residual` carries
    /// remaining diagnostics (from the last successful per-edit reverify).
    /// `applied_count` / `total_count` are used for the summary line.
    PartiallyFixed {
        new_source: String,
        residual: mds::LintResult,
        applied_count: usize,
        total_count: usize,
    },
    Rejected {
        reason: String,
        original: mds::LintResult,
    },
    NothingToFix {
        original: mds::LintResult,
    },
}

/// Run the `--fix` pipeline for a single file's lint result.
///
/// `base_dir` is the file's parent (for reverify recompile).
///
/// `display_label` is the caller-supplied display path (relative, forward-slash-normalised)
/// written into every `diag.file` in residual results via `set_diag_display_path`; it
/// becomes the `files[].file` wire key after `to_canonical_json` applies
/// `sanitize_control_chars_wire`.  This is the value that appears in the JSON wire output
/// and must be pre-sanitized by the caller for error-envelope entries that bypass
/// `to_canonical_json`.
///
/// ## Reverify gate (AC-F-20)
///
/// The reverify closure checks three conditions:
/// 1. Recompile-success — fixed source must still compile.
/// 2. No-new-untargeted-diagnostics — edit must not introduce new problems.
/// 3. Output byte-equality — when the original source is standalone-compilable,
///    compiled output of the fixed source must be byte-identical to the original.
///
/// If the original source does not compile (e.g. missing runtime vars), the
/// output-diff is skipped — conditions 1 and 2 still apply, and Tier B is
/// already suggestion-only (non-standalone) in that scenario.
fn plan_and_apply_fixes(
    result: mds::LintResult,
    source: &str,
    base_dir: &Path,
    runtime_vars: Option<std::collections::HashMap<String, mds::Value>>,
    config: &mds::LintConfig,
    display_label: &str,
) -> FixFileOutcome {
    let is_standalone = result.is_standalone;
    let plan = mds::fix::plan_fixes_with_options(&result, source, is_standalone);

    // Treat overlap_rejected as "something to do" — don't short-circuit as NothingToFix
    // when edits were rejected due to overlap.  The incremental fallback (per-edit retry)
    // handles individual edits that survive the overlap check.
    if plan.edits.is_empty() && !plan.overlap_rejected {
        return FixFileOutcome::NothingToFix { original: result };
    }

    // Capture total edit count before moving plan into apply_fixes_incremental.
    // Used to compute the "{applied} of {total}" summary for PartiallyFixed output.
    let total_edits = plan.edits.len();

    // `legacy-interpolation` edits intentionally change compiled output (they migrate
    // `{x}` plain-text to `{{x}}` interpolation).  When the plan contains any such
    // edit, the output byte-equality gate below must be skipped — it only applies to
    // output-neutral fixes (dup-import removal, empty-block removal, etc.).
    let all_output_neutral = plan
        .edits
        .iter()
        .all(|e| mds::fix::is_output_neutral(&e.rule));

    // AC-F-20 output-delta baseline: compile the original source once.
    // If it fails (e.g. missing runtime vars at eval time), skip the output-diff —
    // existing gates (recompile-success, no-new-diagnostics) still apply.
    let original_output =
        mds::compile_str_collecting_warnings(source, Some(base_dir), runtime_vars.clone())
            .ok()
            .map(|r| r.output);

    let base_dir_owned = base_dir.to_path_buf();
    let config_clone = config.clone();
    // apply_fixes_incremental requires F: Fn (not FnOnce) — the reverify closure
    // may be called up to plan.edits.len()+1 times (batch attempt + per-edit fallback).
    // All captured variables are either borrowed (&) or cloned inside, so the closure
    // satisfies Fn without any extra effort.
    let outcome = mds::fix::apply_fixes_incremental(source, plan, &result, |fixed| {
        let residual = mds::lint_str_with(
            fixed,
            Some(&base_dir_owned),
            runtime_vars.clone(),
            &config_clone,
        )?;

        // AC-F-20 output byte-equality gate: refuse if the fix changes compiled output.
        // Skipped when the plan contains any output-changing rule (currently only
        // `legacy-interpolation`) — those fixes intentionally alter compiled output
        // and the gate would always reject them.
        if all_output_neutral {
            if let Some(ref orig_out) = original_output {
                match mds::compile_str_collecting_warnings(
                    fixed,
                    Some(&base_dir_owned),
                    runtime_vars.clone(),
                ) {
                    Ok(fixed_compile) if fixed_compile.output != *orig_out => {
                        return Err(MdsError::Io {
                            message: "lint --fix would change compiled output; \
                                      edit reverted to preserve template semantics"
                                .to_string(),
                        });
                    }
                    _ => {} // outputs match, or fixed source didn't compile (lint_str_with caught it)
                }
            }
        }

        Ok(residual)
    });

    match outcome {
        mds::fix::FixOutcome::Fixed {
            source: new_source,
            mut residual,
        } => {
            set_diag_display_path(&mut residual, display_label);
            FixFileOutcome::Fixed {
                new_source,
                residual,
            }
        }
        mds::fix::FixOutcome::PartiallyFixed {
            source: new_source,
            mut residual,
            rejected,
        } => {
            set_diag_display_path(&mut residual, display_label);
            FixFileOutcome::PartiallyFixed {
                new_source,
                residual,
                applied_count: total_edits - rejected.len(),
                total_count: total_edits,
            }
        }
        mds::fix::FixOutcome::Rejected { source: _, reason } => FixFileOutcome::Rejected {
            reason,
            original: result,
        },
        mds::fix::FixOutcome::NothingToFix => FixFileOutcome::NothingToFix { original: result },
        // FixOutcome is #[non_exhaustive]: a wildcard arm is required when
        // matching from outside mds-core.  New variants added in future
        // releases should be plumbed here; until then, treat them as no-ops.
        _ => FixFileOutcome::NothingToFix { original: result },
    }
}

/// Outcome of the preview fix pipeline (`--fix --check` / `--fix --diff`).
///
/// Distinguishes "would fix", "rejected by reverify gate", and "nothing to fix"
/// so that callers can surface rejection reasons in `--fix --check` output
/// (PF-004: preview must use the same gated pipeline as apply and be equally honest
/// about outcomes).
enum PreviewOutcome {
    /// At least one edit would be applied.  Carries the would-be fixed source
    /// (for `--diff` rendering) and the residual post-fix [`mds::LintResult`]
    /// (for the R1 preview exit code — `preview_exit_code(&residual)`).
    WouldFix {
        fixed: String,
        residual: mds::LintResult,
    },
    /// Every edit was refused by the reverify gate (overlap or recompile failure);
    /// contains the human-readable rejection reason.
    Rejected(String),
    /// No fixable edits exist or the plan is empty with no overlap.
    NothingToFix,
}

/// Run the fix pipeline in preview mode (for `--fix --check` / `--fix --diff`).
///
/// Routes through the same gated pipeline as the write path — plan, reverify, and
/// apply — but does NOT write to disk.  Returns [`PreviewOutcome::WouldFix`] with
/// the would-be fixed source AND the residual post-fix result when at least one
/// edit would be applied; [`PreviewOutcome::Rejected`] with the rejection reason
/// when the reverify gate refused every edit; [`PreviewOutcome::NothingToFix`]
/// when the plan is empty.
///
/// `display_label` mirrors the `plan_and_apply_fixes` contract: it is written
/// into every residual `diag.file` via `set_diag_display_path` so the residual
/// carries the same display path as the write path's residual would (R1) —
/// without it the residual would leak the basename / `STRING_SOURCE_MAP_LABEL`
/// that `mds::lint_str_with` sets internally.
///
/// ADR-004 / PF-004: preview must use the same gated pipeline as apply so that
/// `--diff` shows exactly what `--fix` would write, and the preview exit code
/// reflects what a real `--fix` run would leave behind (R1:
/// `max(1 if fixes pending, residual severity)` — see [`preview_exit_code`]).
/// The `Rejected` variant gives `--fix --check` the same honesty as `--fix`
/// (which prints "fix rejected: …" on refusal).
fn preview_fixes(
    result: &mds::LintResult,
    source: &str,
    base_dir: &Path,
    runtime_vars: Option<std::collections::HashMap<String, mds::Value>>,
    config: &mds::LintConfig,
    display_label: &str,
) -> PreviewOutcome {
    let is_standalone = result.is_standalone;
    let plan = mds::fix::plan_fixes_with_options(result, source, is_standalone);

    if plan.edits.is_empty() && !plan.overlap_rejected {
        return PreviewOutcome::NothingToFix;
    }

    // Same output-neutral check as plan_and_apply_fixes: skip the equality gate when
    // the plan contains any output-changing rule (e.g. legacy-interpolation).
    let all_output_neutral = plan
        .edits
        .iter()
        .all(|e| mds::fix::is_output_neutral(&e.rule));

    let original_output =
        mds::compile_str_collecting_warnings(source, Some(base_dir), runtime_vars.clone())
            .ok()
            .map(|r| r.output);

    let base_dir_owned = base_dir.to_path_buf();
    let config_clone = config.clone();
    let outcome = mds::fix::apply_fixes_incremental(source, plan, result, |fixed| {
        let residual = mds::lint_str_with(
            fixed,
            Some(&base_dir_owned),
            runtime_vars.clone(),
            &config_clone,
        )?;

        // Output byte-equality gate — skipped for output-changing rules.
        if all_output_neutral {
            if let Some(ref orig_out) = original_output {
                match mds::compile_str_collecting_warnings(
                    fixed,
                    Some(&base_dir_owned),
                    runtime_vars.clone(),
                ) {
                    Ok(fixed_compile) if fixed_compile.output != *orig_out => {
                        return Err(MdsError::Io {
                            message: "lint --fix would change compiled output; \
                                      edit reverted to preserve template semantics"
                                .to_string(),
                        });
                    }
                    _ => {}
                }
            }
        }

        Ok(residual)
    });

    match outcome {
        mds::fix::FixOutcome::Fixed {
            source: new_source,
            mut residual,
        }
        | mds::fix::FixOutcome::PartiallyFixed {
            source: new_source,
            mut residual,
            ..
        } => {
            set_diag_display_path(&mut residual, display_label);
            PreviewOutcome::WouldFix {
                fixed: new_source,
                residual,
            }
        }
        mds::fix::FixOutcome::Rejected { reason, .. } => PreviewOutcome::Rejected(reason),
        mds::fix::FixOutcome::NothingToFix => PreviewOutcome::NothingToFix,
        // FixOutcome is #[non_exhaustive]: wildcard required from outside mds-core.
        _ => PreviewOutcome::NothingToFix,
    }
}

// ── Stdin mode ────────────────────────────────────────────────────────────────

fn run_lint_stdin(
    flags: LintFlags,
    runtime_vars: Option<std::collections::HashMap<String, mds::Value>>,
) -> Result<()> {
    // Bind all five flags explicitly — `..` would silently drop unbound flags to
    // their defaults, which breaks `--fix --check` semantics (avoids PF-004).
    let LintFlags {
        fix,
        check,
        diff,
        quiet,
        format,
    } = flags;

    let (source, cwd) = read_stdin()?;
    // mds.json load/parse failure → JSON envelope in --format json mode (AC-F-14).
    let config = match load_lint_config(&cwd, quiet) {
        Ok(c) => c,
        Err(e) => {
            let mds_err = MdsError::Io {
                message: format!("{e}"),
            };
            // AD-211-5: config errors (MdsError::Io) carry no embedded NamedSource,
            // so the relabel is a no-op here. Passed anyway so the envelope rule holds
            // for EVERY stdin failure path — a future error variant routed here that
            // does carry a source inherits the sentinel instead of needing a new call.
            emit_analysis_failure_json_or_stderr(&mds_err, format, Some(&source));
            std::process::exit(2);
        }
    };

    let mut result = match mds::lint_str_with(&source, Some(&cwd), runtime_vars.clone(), &config) {
        Ok(r) => r,
        Err(e) => {
            // AD-211-5: relabel <source> → <stdin> in the rendered failure envelope.
            emit_analysis_failure_json_or_stderr(&e, format, Some(&source));
            std::process::exit(mds_error_exit_code(&e));
        }
    };

    // AD-211-4 / AD-211-1: relabel diag.file from STRING_SOURCE_MAP_LABEL →
    // STDIN_DISPLAY_LABEL at the CLI output boundary.  fix.rs never reads diag.file
    // (verified: zero reads in fix.rs), so this relabel is safe upstream of both
    // preview_fixes and plan_and_apply_fixes.  This single call ensures
    // "files[].file" emits "<stdin>" across all code paths (AC-P1-01); for the
    // write path, plan_and_apply_fixes relabels its internally produced residual
    // before returning.
    set_diag_display_path(&mut result, STDIN_DISPLAY_LABEL);

    // D4 (AD-216-11): status message, not an error — suppress under --quiet.
    // PF-004: stdin is a separate emitter from file/directory mode; the cap notice
    // must reach this path too (avoids the #43/#173 divergence class).
    if result.truncated && fix && !quiet {
        eprintln!(
            "diagnostic cap ({}) reached; further findings were suppressed — \
             re-run --fix to continue",
            mds::MAX_DIAGNOSTICS
        );
    }

    if fix {
        // ── Preview path: --fix --check and/or --fix --diff (never writes source) ───
        // Mirrors run_lint_file's preview path so stdin honours --check / --diff the
        // same way file targets do (PF-004: same gated pipeline as the write path).
        if check || diff {
            let preview = preview_fixes(
                &result,
                &source,
                &cwd,
                runtime_vars.clone(),
                &config,
                STDIN_DISPLAY_LABEL,
            );
            // AD-211-1: pass STDIN_DISPLAY_LABEL so span context renders "<stdin>", not
            // the internal STRING_SOURCE_MAP_LABEL ("input.mds").
            let named_source = if format == LintFormat::Human {
                Some((STDIN_DISPLAY_LABEL, source.as_str()))
            } else {
                None
            };
            match preview {
                // ONE arm for both --check and --diff (R1): the emitted body stays
                // PRE-fix — the preview reports what is wrong NOW — and the exit
                // code comes from the residual, floored at 1 because a fix is
                // pending.  Emit-before-exit: diagnostics render before the exit
                // (the old --check arm exited without rendering them).
                PreviewOutcome::WouldFix {
                    ref fixed,
                    ref residual,
                } => {
                    if diff {
                        let diff_str = render_unified_diff(&source, fixed, STDIN_DISPLAY_LABEL);
                        let _ = write_stdout(&diff_str);
                    }
                    if check && !quiet {
                        eprintln!("Would fix: {STDIN_DISPLAY_LABEL}");
                    }
                    emit_result(format, &result, quiet, named_source);
                    std::process::exit(preview_exit_code(residual));
                }
                PreviewOutcome::Rejected(ref reason) => {
                    if !quiet {
                        eprintln!("fix rejected: {}", safe_inline(reason));
                    }
                }
                PreviewOutcome::NothingToFix => {}
            }
            // When nothing would change / fix rejected: render diagnostics of the
            // original result and exit by severity.
            emit_result(format, &result, quiet, named_source);
            exit_by_severity(&result);
            return Ok(());
        }

        // ── Write path: apply fixes, emit fixed source to stdout ─────────────────
        let fix_outcome = plan_and_apply_fixes(
            result,
            &source,
            &cwd,
            runtime_vars,
            &config,
            STDIN_DISPLAY_LABEL,
        );
        let (output_src, diag_result) = match fix_outcome {
            FixFileOutcome::Fixed {
                new_source,
                residual,
            } => (new_source, residual),
            FixFileOutcome::PartiallyFixed {
                new_source,
                residual,
                applied_count,
                total_count,
            } => {
                if !quiet {
                    eprintln!(
                        "Partially fixed: {STDIN_DISPLAY_LABEL} ({applied_count} of {total_count} fixes applied)"
                    );
                }
                (new_source, residual)
            }
            FixFileOutcome::Rejected { reason, original } => {
                // D4 (AD-216-11): "fix rejected" is a status message — the safety
                // gate fired and the original diagnostics are unmodified.  Suppress under
                // --quiet, matching this function's own `PreviewOutcome::Rejected` arm and
                // the directory-mode emitters in `lint_one_file_accumulating` /
                // `lint_one_file_human`.  PF-004: stdin is a separate emitter from
                // directory mode and must not bypass the gate (the #43/#173 divergence
                // class).  Exit code is unaffected; error-severity residual diagnostics
                // still print through `render_result_human`.
                if !quiet {
                    eprintln!("fix rejected: {}", safe_inline(&reason));
                }
                (source, original)
            }
            FixFileOutcome::NothingToFix { original } => (source, original),
        };
        // Stdin diagnostics: pass source text for span context rendering.
        // AD-211-1: use STDIN_DISPLAY_LABEL so source frame header reads "<stdin>".
        let named_source = (STDIN_DISPLAY_LABEL, output_src.as_str());
        render_result_human(&diag_result, quiet, named_source);
        let _ = write_stdout(&output_src);
        exit_by_severity(&diag_result);
        return Ok(());
    }

    // Report-only mode: pass stdin source for span context rendering.
    // AD-211-1: use STDIN_DISPLAY_LABEL so span source frame reads "<stdin>".
    let named_source = if format == LintFormat::Human {
        Some((STDIN_DISPLAY_LABEL, source.as_str()))
    } else {
        None
    };
    emit_result(format, &result, quiet, named_source);
    exit_by_severity(&result);
    Ok(())
}

// ── Single-file mode ──────────────────────────────────────────────────────────

fn run_lint_file(
    path: &Path,
    flags: LintFlags,
    runtime_vars: Option<std::collections::HashMap<String, mds::Value>>,
) -> Result<()> {
    let LintFlags {
        fix,
        check,
        diff,
        quiet,
        format,
    } = flags;

    // effective_parent maps "" (bare filename) to "." — avoids PF-006.
    let base_dir = effective_parent(path);
    // mds.json load/parse failure → JSON envelope in --format json mode (AC-F-14).
    let config = match load_lint_config(base_dir, quiet) {
        Ok(c) => c,
        Err(e) => {
            let mds_err = MdsError::Io {
                message: format!("{e}"),
            };
            emit_analysis_failure_json_or_stderr(&mds_err, format, None);
            std::process::exit(2);
        }
    };
    // File read failure (not found, symlink, I/O) → JSON envelope in --format json mode (AC-F-14).
    let source = match read_source_file(path) {
        Ok(s) => s,
        Err(e) => {
            emit_analysis_failure_json_or_stderr(&e, format, None);
            std::process::exit(mds_error_exit_code(&e));
        }
    };
    let filename = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("<file>");

    let mut result = match mds::lint(path, runtime_vars.clone(), &config) {
        Ok(r) => r,
        Err(e) => {
            emit_analysis_failure_json_or_stderr(&e, format, None);
            std::process::exit(mds_error_exit_code(&e));
        }
    };
    // Remap the basename-only `file` label that mds::lint() sets → the display
    // filename so all four FixFileOutcome arms carry a consistent label.
    // Matches the explicit relabel in lint_one_file_accumulating and
    // lint_one_file_human; without this call the Rejected and NothingToFix
    // arms rely on mds::lint independently deriving the same basename — correct
    // today, but a silent coupling that would break if the two derivations ever
    // diverged.  Centralising the relabel here is the explicit invariant:
    // every FixFileOutcome carries `filename` as its display path.
    set_diag_display_path(&mut result, filename);

    // D4 (AD-216-11): status message, not an error — suppress under --quiet
    // (the global `--quiet` help text: "Suppress status and diagnostic output; errors
    // always print").  PF-004: single-file mode is a separate emitter from directory
    // mode; gating only the directory copy would re-create the #43/#173 divergence.
    if result.truncated && fix && !quiet {
        eprintln!(
            "diagnostic cap ({}) reached; further findings were suppressed — \
             re-run --fix to continue",
            mds::MAX_DIAGNOSTICS
        );
    }

    // Named source for span rendering: (display filename, source text).
    let named_source = Some((filename, source.as_str()));

    // ── Write path: --fix without preview ────────────────────────────────────
    if fix && !check && !diff {
        let fix_outcome =
            plan_and_apply_fixes(result, &source, base_dir, runtime_vars, &config, filename);
        match fix_outcome {
            FixFileOutcome::Fixed {
                new_source,
                residual,
            } => {
                emit_result(format, &residual, quiet, named_source);
                atomic_write_file(path, &new_source, Durability::Fsync)?;
                if !quiet {
                    eprintln!("Fixed: {}", safe_path(path));
                }
                exit_by_severity(&residual);
            }
            FixFileOutcome::PartiallyFixed {
                new_source,
                residual,
                applied_count,
                total_count,
            } => {
                emit_result(format, &residual, quiet, named_source);
                atomic_write_file(path, &new_source, Durability::Fsync)?;
                // Print status AFTER write succeeds so "Partially fixed:" never
                // precedes "error writing" for a file that was never modified.
                if !quiet {
                    eprintln!(
                        "Partially fixed: {} ({applied_count} of {total_count} fixes applied)",
                        safe_path(path)
                    );
                }
                exit_by_severity(&residual);
            }
            FixFileOutcome::Rejected { reason, original } => {
                // D4 (AD-216-11): status message — suppress under --quiet,
                // matching this function's own `PreviewOutcome::Rejected` arm and the
                // directory-mode emitters.  PF-004: single-file mode is a separate
                // emitter and must honour the same gate.
                if !quiet {
                    eprintln!("fix rejected: {}", safe_inline(&reason));
                }
                emit_result(format, &original, quiet, named_source);
                exit_by_severity(&original);
            }
            FixFileOutcome::NothingToFix { original } => {
                emit_result(format, &original, quiet, named_source);
                if !quiet && format == LintFormat::Human && original.diagnostics.is_empty() {
                    eprintln!("Clean: {}", safe_file_display(filename));
                }
                exit_by_severity(&original);
            }
        }
        return Ok(());
    }

    // ── Preview path: --fix --check and/or --fix --diff ─────────────────
    // Route preview through the same gated pipeline as the write path.
    // Previously called apply_plan_unchecked directly, bypassing the reverify gate —
    // a diff or check result could misrepresent what --fix would actually do.
    if fix && (check || diff) {
        let preview = preview_fixes(&result, &source, base_dir, runtime_vars, &config, filename);
        match preview {
            // ONE arm for both --check and --diff (R1): the emitted body stays
            // PRE-fix — the preview reports what is wrong NOW — and the exit code
            // comes from the residual, floored at 1 because a fix is pending.
            PreviewOutcome::WouldFix {
                ref fixed,
                ref residual,
            } => {
                if diff {
                    let label = safe_path(path);
                    let diff_str = render_unified_diff(&source, fixed, &label);
                    let _ = write_stdout(&diff_str);
                }
                if check && !quiet {
                    eprintln!("Would fix: {}", safe_path(path));
                }
                // AC-F-14 emit-before-exit: emit the (pre-fix) result BEFORE the
                // exit so consumers always receive parseable output regardless of
                // exit code.  Mirrors directory mode, which emits the envelope
                // before its preview-floor exit.
                emit_result(format, &result, quiet, named_source);
                std::process::exit(preview_exit_code(residual));
            }
            PreviewOutcome::Rejected(ref reason) => {
                // Surface the rejection reason so --fix --check is as honest as --fix.
                if !quiet {
                    eprintln!("fix rejected: {}", safe_inline(reason));
                }
            }
            PreviewOutcome::NothingToFix => {}
        }
        // When nothing would change / fix rejected: render diagnostics and exit
        // by severity.
        emit_result(format, &result, quiet, named_source);
        exit_by_severity(&result);
        return Ok(());
    }

    // ── Report-only mode (no --fix) ───────────────────────────────────────────
    emit_result(format, &result, quiet, named_source);
    if !quiet && format == LintFormat::Human && result.diagnostics.is_empty() {
        eprintln!("Clean: {}", safe_file_display(filename));
    }
    exit_by_severity(&result);
    Ok(())
}

// ── Directory mode ────────────────────────────────────────────────────────────

/// Compile-time context for directory-mode lint.
///
/// Groups the parameters resolved once at the start of a directory lint run and
/// threaded into every per-file call — removes the `#[allow(clippy::too_many_arguments)]`
/// suppressions on `lint_one_file_accumulating` and `lint_one_file_human`
/// (issue #6 / zero-warnings policy). Pattern mirrors `FileCompileCtx` / `DirWatchCtx`
/// in watch.rs.
///
/// Two caches serve two independent fast paths into the config resolution logic.
/// They are kept SEPARATE so the key namespaces never collide: a directory that
/// happens to contain an `mds.json` would appear as a `base_dir` key in one run
/// and as a `config_dir` key in another, and a single map would conflate them.
///
/// - **Fast path 1** (`base_dir_cache`): if a file's parent directory has already
///   been resolved, return the cached config without re-walking the ancestor chain.
/// - **Fast path 2** (`config_dir_cache`): if a DIFFERENT `base_dir` resolves to
///   the SAME `mds.json`, return the cached config and skip emitting a duplicate
///   warning (AC-224-19: "at most once per distinct config directory").
///
/// NOTE: `load_config(base_dir)` is called BEFORE consulting `config_dir_cache`,
/// so the file I/O and ancestor walk still happen for each new `base_dir` — fast
/// path 2 prevents the DUPLICATE WARNING, not the re-parse. For a tree of N files
/// under one directory, fast path 1 amortises the cost to a single read (the common
/// case). The AC-224-19 threshold (200 files, one directory) is met by fast path 1.
///
/// The `RefCell` provides interior mutability so per-file helpers can populate the
/// caches through a shared `&LintDirCtx` reference.
struct LintDirCtx<'a> {
    flags: LintFlags,
    runtime_vars: &'a Option<HashMap<String, mds::Value>>,
    /// Fast-path-1 cache: `base_dir → config`. Every directory whose files have
    /// been linted at least once is recorded here; a second file in the same
    /// directory returns immediately without calling `load_config`.
    base_dir_cache: RefCell<HashMap<PathBuf, Rc<mds::LintConfig>>>,
    /// Fast-path-2 cache: `config_dir → config`. Keyed by the RESOLVED directory
    /// that contains `mds.json`, not the file's parent. Prevents a duplicate
    /// unknown-rule warning when multiple `base_dir`s share one root `mds.json`.
    config_dir_cache: RefCell<HashMap<PathBuf, Rc<mds::LintConfig>>>,
}

impl<'a> LintDirCtx<'a> {
    /// Return the `LintConfig` for the directory `base_dir`.
    ///
    /// Consults `base_dir_cache` (fast path 1) and `config_dir_cache` (fast path 2)
    /// before loading from disk; see the struct doc for the two-cache design and the
    /// AC-224-19 rationale. On config-load failure returns `Err(MdsError::Io{..})` so
    /// the caller can record a per-file error and continue linting the rest of the tree.
    fn config_for(&self, base_dir: &Path) -> Result<Rc<mds::LintConfig>, MdsError> {
        // Fast path 1: base_dir was already resolved in a previous call (common case
        // for multiple files in the same directory — avoids the ancestor walk).
        {
            let cache = self.base_dir_cache.borrow();
            if let Some(cfg) = cache.get(base_dir) {
                return Ok(Rc::clone(cfg));
            }
        }

        // Walk the ancestor chain to find the mds.json governing this directory.
        // We call `load_config` directly (not `load_lint_config`) so we can inspect
        // the RESOLVED config directory before deciding whether to emit the warning:
        // multiple subdirectories can resolve to the same root mds.json, and
        // AC-224-19 requires the warning fires at most once per distinct config dir.
        let raw = load_config(base_dir).map_err(|e| MdsError::Io {
            message: format!("{e}"),
        })?;

        match raw {
            None => {
                // No mds.json found: use the default config, keyed by base_dir only.
                let rc = Rc::new(mds::LintConfig::default());
                self.base_dir_cache
                    .borrow_mut()
                    .insert(base_dir.to_path_buf(), Rc::clone(&rc));
                Ok(rc)
            }
            Some((mds_config, config_dir)) => {
                // Fast path 2: a different base_dir already resolved to this same
                // config directory (e.g. a/file.mds and b/file.mds both governed by
                // root/mds.json). Return the cached config without emitting a
                // duplicate warning (AC-224-19). Note: load_config above still ran
                // — fast path 2 suppresses the duplicate WARNING, not the re-parse.
                //
                // `config_dir_cache` and `base_dir_cache` are different RefCells, so
                // holding the shared borrow on `config_dir_cache` through the body is
                // safe — the body only mutably borrows `base_dir_cache`.
                if let Some(rc) = self
                    .config_dir_cache
                    .borrow()
                    .get(&config_dir)
                    .map(Rc::clone)
                {
                    // Alias base_dir → cached config so fast path 1 fires on the
                    // next call for a file in this same directory.
                    self.base_dir_cache
                        .borrow_mut()
                        .insert(base_dir.to_path_buf(), Rc::clone(&rc));
                    return Ok(rc);
                }

                // First load for this config_dir: build the config and emit the warning.
                // Contract documentation (safe_inline, --quiet, AC-224-3) lives at
                // `emit_unknown_rule_warning` — the single emitter shared with
                // load_lint_config (PF-009).
                let (lint_config, unknown) = mds_config.lint.into_core_config();
                if let Some(unknown) = unknown {
                    emit_unknown_rule_warning(&unknown, self.flags.quiet);
                }

                // Populate BOTH caches. `config_dir_cache` enables fast path 2 for
                // future base_dirs that resolve to this same mds.json; `base_dir_cache`
                // enables fast path 1 for future files in this same directory.
                let rc = Rc::new(lint_config);
                self.base_dir_cache
                    .borrow_mut()
                    .insert(base_dir.to_path_buf(), Rc::clone(&rc));
                self.config_dir_cache
                    .borrow_mut()
                    .insert(config_dir, Rc::clone(&rc));
                Ok(rc)
            }
        }
    }
}

/// Aggregate exit-code category for directory mode.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum FileTally {
    Clean = 0,
    WarnOnly = 1,
    Error = 2,
    ResourceLimit = 3,
}

impl FileTally {
    fn exit_code(self) -> i32 {
        self as i32
    }
}

fn tally_from_result(result: &mds::LintResult) -> FileTally {
    match result_exit_code(result) {
        2 => FileTally::Error,
        1 => FileTally::WarnOnly,
        _ => FileTally::Clean,
    }
}

/// Lint every `.mds` file under `dir`, INCLUDING `_`-prefixed partials.
///
/// Accumulate-and-continue past per-file failures. Exit = max severity across files.
/// Output is path-sorted (F1 — `collect_mds_files` does NOT sort).
///
/// **Directory summary (AD-216-3):** after processing all files, emits one summary
/// line to stderr in the form
/// `{clean} clean, {warn} with warnings, {error} with errors, {limit} resource-limited`.
/// "With errors" covers both error-severity lint findings AND per-file analysis failures
/// (read error, config error, lint call failure) — the same conflation `mds build`'s
/// "failed" bucket makes (D3-a).  "Resource-limited" counts files where `mds::lint`
/// returned `MdsError::ResourceLimit` — distinct from lint findings.
///
/// **Summary / quiet contract (AD-216-6):** the summary is suppressed under `--quiet`
/// unless at least one file is in the `error` or `resource-limited` bucket.  Warn-only
/// runs are silent under `--quiet` (mirrors `mds fmt`, which does not force its summary
/// on a `changed_count`-only run).  Exit codes are unaffected (AD-216-2).
///
/// **D1 decision (AC-Q14):** `mds lint --quiet <dir>` on a warn-only tree exits 1 with
/// no output.  `mds lint --fix --check --quiet <dir>` with pending fixes exits 1 with
/// no output.  Both are intentional: warnings are status output, which `main.rs:30`
/// says `--quiet` suppresses.
///
/// **D2 decision (AC-Q16):** the JSON stdout envelope (`{"files":…,"truncated":…,"version":1}`)
/// is unchanged — no `"summary"` key is added.  The summary is emitted to stderr only,
/// keeping stdout a single clean JSON document in all non-`--diff` modes.  (`--fix --diff`
/// is a legal invocation that writes the unified diff to stdout ahead of the envelope,
/// so `--fix --diff --format json` produces non-JSON-parseable stdout by design.)
///
/// **Channel discipline (AD-216-8):** the summary is emitted in BOTH human and JSON
/// format modes — format governs where machine-readable output goes (stdout), not
/// whether status output (stderr) appears.  JSON consumers using `--format json`
/// (without `--fix --diff`) continue to receive valid parseable JSON on stdout
/// regardless of stderr content; `--fix --diff` writes unified diffs to stdout
/// before the JSON envelope and is incompatible with JSON-consumer pipelines.
fn run_lint_directory(
    dir: &Path,
    flags: LintFlags,
    runtime_vars: Option<std::collections::HashMap<String, mds::Value>>,
) -> Result<()> {
    const MAX_DEPTH: usize = 64;
    let LintFlags { quiet, format, .. } = flags;

    // A6/D20: config is now discovered per-file (each file walks up to its nearest
    // mds.json). The single root config load is removed; base_dir_cache and
    // config_dir_cache in LintDirCtx amortise repeated loads for files in the same
    // directory and across subdirectories sharing one root mds.json.

    let walk = collect_mds_files_detailed(dir, MAX_DEPTH, None);
    let files = walk.files;

    // AD-216-9: neither early exit below emits a summary — the per-file loop never
    // runs, so all four counters stay at zero and there is nothing meaningful to
    // print.  Both diagnostics bypass --quiet and exit 2 (lint's usage-error code;
    // build/check/fmt use 1): the all-excluded arm, and since #204 the empty-tree
    // arm — a silent non-zero exit here would be a bug, and a silent ZERO exit on an
    // empty tree was the CI green-pass hole #204 closes.
    if files.is_empty() {
        if walk.excluded_by_default > 0 {
            // Always emit — not suppressed by --quiet (avoids silent CI green pass).
            // Exit 2: usage error consistent with lint's exit-code table.
            eprintln!(
                "{} .mds file(s) found but all are under default-excluded directories \
                 (hidden dirs, node_modules); nothing was linted",
                walk.excluded_by_default
            );
            std::process::exit(2);
        }
        // #204: an empty tree is "nothing to lint", not success (mirrors build.rs).
        // Emitted even under --quiet.  Exit 2 is lint's usage-error code (module doc),
        // matching the all-excluded arm above; build/check/fmt use 1.
        eprintln!(
            "no .mds files found in {}; nothing was linted",
            safe_path(dir)
        );
        std::process::exit(2);
    }

    // #217: compute every display key BEFORE the sort, so a path that cannot be
    // named relative to `dir` fails the whole run instead of contributing a lossy
    // or absolute key.  Ordering matters twice over:
    //   * before the sort — the sort key IS the display key, so a lossy key that
    //     only fails later would already have been built and compared here;
    //   * before the per-file loop — nothing is linted, so no `files[]` entry can
    //     carry a key that names no file under `dir`.
    // The failure is NOT propagated with `?`: the caller returns `miette::Result`,
    // and a bare `?` would render a human diagnostic and drop the JSON
    // analysis-failure envelope that `--format json` consumers parse.  Same shape
    // as the symlinked-root rejection at the top of `run_lint`.
    let mut keyed: Vec<(PathBuf, String)> = Vec::with_capacity(files.len());
    for p in files {
        match relative_display(&p, dir) {
            Ok(display) => keyed.push((p, display)),
            Err(e) => {
                emit_analysis_failure_json_or_stderr(&e, format, None);
                std::process::exit(mds_error_exit_code(&e));
            }
        }
    }

    // F1: sort by (sanitized_display_key, raw_os_path) so that:
    // 1. Array position is consistent with the sanitized `files[].file` key
    //    emitted by `to_canonical_json` for diagnostic entries (AC-P1-10).
    // 2. An OsString secondary key breaks any ties when two distinct paths produce
    //    the same sanitized display key — rare in practice, but ensures
    //    deterministic order regardless of readdir enumeration order.
    //
    // `Path::Ord` (component-wise) diverges from byte-order when a path-separator
    // character appears WITHIN a filename component — e.g. `api-utils.mds` sorts
    // AFTER `api/x.mds` under Path::Ord ("api" < "api-utils"), but BEFORE under
    // byte-wise string order ('-' = 0x2D < '/' = 0x2F).  Sorting on the relative
    // display string keeps the CLI wire contract consistent with the BTreeMap
    // ordering that `to_canonical_json` applies on the binding surfaces (PF-007).
    //
    // `relative_display` normalises to forward slashes so byte-wise order is
    // identical on Unix and Windows — the sort key and the emitted JSON `file`
    // key are the same String by construction, so array position matches key
    // order on both platforms.  `sanitize_control_chars_wire` is
    // then applied so the sort key matches the emitted key produced by
    // `to_canonical_json`: POSIX filenames may legally contain control bytes
    // (e.g. 0x01), and sorting on the raw (unsanitized) string would place a
    // control-byte filename at a position inconsistent with its `\uXXXX`-escaped
    // emitted key, violating AC-P1-10.  For the vast majority of paths (no control
    // bytes), `sanitize_control_chars_wire` returns `Cow::Borrowed` — no extra
    // heap allocation beyond the String conversion.
    //
    // `sort_by_cached_key` computes each key once — O(n) allocations, not O(n log n)
    // (AC-P1-22).
    keyed.sort_by_cached_key(|(p, display)| {
        (
            mds::sanitize_control_chars_wire(display).into_owned(),
            p.as_os_str().to_os_string(),
        )
    });

    let mut max_tally = FileTally::Clean;
    let mut json_files: Vec<serde_json::Value> = Vec::new();
    let mut any_truncated = false;

    let mut any_would_fix = false;

    // AD-216-3/5: four counters for the directory summary, one per FileTally variant.
    // Names are file-unique (print_discipline.rs limit 2, :106-110): `clean_count`,
    // `warn_file_count`, `error_file_count`, `limit_file_count` — none reuse an already-
    // exempted name from another summary line in this file.
    let mut clean_count: usize = 0;
    let mut warn_file_count: usize = 0;
    let mut error_file_count: usize = 0;
    let mut limit_file_count: usize = 0;

    let ctx = LintDirCtx {
        flags,
        runtime_vars: &runtime_vars,
        base_dir_cache: RefCell::new(HashMap::new()),
        config_dir_cache: RefCell::new(HashMap::new()),
    };

    for (file, display_path) in &keyed {
        let tally = if format == LintFormat::Json {
            lint_one_file_accumulating(
                file,
                display_path,
                &ctx,
                &mut json_files,
                &mut any_truncated,
                &mut any_would_fix,
            )
        } else {
            lint_one_file_human(
                file,
                display_path,
                &ctx,
                &mut any_truncated,
                &mut any_would_fix,
            )
        };
        // AD-216-5: exhaustive match — a future FileTally variant becomes a compile
        // error here rather than being silently uncounted in the summary.
        match tally {
            FileTally::Clean => clean_count += 1,
            FileTally::WarnOnly => warn_file_count += 1,
            FileTally::Error => error_file_count += 1,
            FileTally::ResourceLimit => limit_file_count += 1,
        }
        if tally > max_tally {
            max_tally = tally;
        }
    }
    // AD-216-5: dev-only tripwire for the four-counter partition invariant (avoids PF-005
    // in intent, not in substance — debug_assert_eq! compiles away in release mode).
    // A future early-continue in the per-file loop would silently undercount in shipped
    // binaries; release consequence: a miscounted status line or spurious --quiet
    // suppression, never data corruption.
    debug_assert_eq!(
        clean_count + warn_file_count + error_file_count + limit_file_count,
        keyed.len(),
        "AD-216-5: FileTally partition invariant violated"
    );

    // Emit JSON envelope BEFORE any early exit so consumers always receive parseable
    // output regardless of exit code (AC-F-14 / issue #36).
    if format == LintFormat::Json {
        let json = serde_json::json!({
            "version": 1,
            "files": json_files,
            "truncated": any_truncated,
        });
        let _ = write_stdout(&format!(
            "{}\n",
            serde_json::to_string(&json).expect("canonical lint JSON is always serializable")
        ));
    }

    // AD-216-7: emit the summary AFTER the JSON envelope (so consumers always get a
    // parseable JSON object on stdout) and BEFORE the --fix --check exit (so a
    // --fix --check run that would exit 1 still prints the summary on the way out).
    //
    // AD-216-6: suppress under --quiet unless error- or resource-limited files are
    // present.  Warn-only runs are silent under --quiet (D1-a — mirrors fmt.rs:342:
    // `changed_count` does not force the summary under --quiet).
    //
    // AD-216-8: emitted in both human and JSON format modes.  --format governs the
    // machine-readable channel (stdout); the summary is status output (stderr) and is
    // governed only by --quiet.
    //
    // AD-216-4: format — `{clean} clean, {warn} with warnings, {error} with errors,
    // {limit} resource-limited`.  Fixed arity, comma-separated.  Lint uses
    // deliberately distinct vocabulary from the sibling subcommands (`build`/`check`/
    // `fmt` all end in "N failed"): the four-bucket partition expresses distinct failure
    // modes (warn-only vs error vs resource-limit) not captured by a single "failed"
    // count.  The format is pinned by spec §7.5 and tests.
    if !quiet || error_file_count > 0 || limit_file_count > 0 {
        eprintln!(
            "{clean_count} clean, {warn_file_count} with warnings, \
             {error_file_count} with errors, {limit_file_count} resource-limited"
        );
    }

    // R1 preview exit rule: exit = max(residual severity across files, 1 if any
    // file would fix).  In preview mode (--fix --check / --fix --diff) the
    // per-file tallies feeding max_tally are RESIDUAL-derived (see the preview
    // arms in lint_one_file_accumulating / lint_one_file_human), so a tree whose
    // fixes would leave error-severity findings behind exits 2 even though every
    // file "would fix".  The former `if flags.check && any_would_fix { exit(1) }`
    // early exit SHADOWED max_tally — residual errors exited 1.
    // `any_would_fix` can only be set in preview mode, so no mode guard is needed.
    let mut exit = max_tally.exit_code();
    if any_would_fix {
        exit = exit.max(1);
    }
    if exit != 0 {
        std::process::exit(exit);
    }
    Ok(())
}

/// Lint one file in directory mode, accumulating results into a JSON array.
fn lint_one_file_accumulating(
    file: &Path,
    display_path: &str,
    ctx: &LintDirCtx<'_>,
    json_files: &mut Vec<serde_json::Value>,
    any_truncated: &mut bool,
    any_would_fix: &mut bool,
) -> FileTally {
    // Bind quiet so the PartiallyFixed arm can honour it (issue #43 / #173).
    let LintFlags {
        fix,
        check,
        diff,
        quiet,
        ..
    } = ctx.flags;

    // `display_path` is the lint-root-relative key computed once by
    // `run_lint_directory`'s pre-pass (#217) — it is never recomputed here, so a
    // path this helper could not name has already failed the whole run.  It is
    // navigable and unique across the whole directory tree (not just basenames)
    // and normalised to forward slashes.  `to_canonical_json` then sanitizes the
    // key via `sanitize_control_chars_wire`; `run_lint_directory` sorts on that
    // same sanitized string, so emitted array order and emitted file key order
    // are consistent for all inputs including control-byte filenames (AC-P1-10).
    //
    // Error-only entries (`{"file": …, "error": …}`) bypass `to_canonical_json`
    // and therefore bypass its `sanitize_control_chars_wire` pass.  Pre-sanitize
    // here so the `file` key in error entries is treated identically to the `file`
    // key in diagnostic entries — hostile filenames cannot inject control, bidi,
    // or separator characters into either entry type (spec.md §lint-json `file`
    // contract; ADR-008).
    let file_key = mds::sanitize_control_chars_wire(display_path).into_owned();

    // `source` is only consumed in the fix branch (below); the report-only/JSON
    // path does not need it — mds::lint() reads the file independently (I-06).
    // effective_parent maps "" (bare filename) to "." — avoids PF-006.
    let base_dir = effective_parent(file);

    // A6: per-file config discovery — load (and cache) the nearest mds.json for
    // this file's directory. A config-load failure is a per-file error; the rest
    // of the tree continues linting.
    let config = match ctx.config_for(base_dir) {
        Ok(c) => c,
        Err(ref e) => {
            json_files.push(serde_json::json!({
                "file": file_key,
                "error": e.serialize()
            }));
            return FileTally::Error;
        }
    };

    let mut result = match mds::lint(file, ctx.runtime_vars.clone(), &config) {
        Ok(r) => r,
        Err(ref e) => {
            json_files.push(serde_json::json!({
                "file": file_key,
                "error": e.serialize()
            }));
            return if matches!(e, MdsError::ResourceLimit { .. }) {
                FileTally::ResourceLimit
            } else {
                FileTally::Error
            };
        }
    };
    // Remap basename-only file field → relative display path.
    set_diag_display_path(&mut result, display_path);

    if result.truncated {
        *any_truncated = true;
        // D4 (AD-216-11): this is a status message, not an error — suppress
        // under --quiet (main.rs:30 "Suppress status and diagnostic output").
        if fix && !quiet {
            eprintln!(
                "{}: diagnostic cap ({}) reached; further findings were suppressed — \
                 re-run --fix to continue",
                safe_path(file),
                mds::MAX_DIAGNOSTICS
            );
        }
    }

    if fix && !check && !diff {
        // Read source here only (not earlier) — the report-only path does not need
        // it. On a read error at this point (rare: lint just succeeded above),
        // surface the same error format as other per-file I/O failures and bail.
        let source = match read_source_file(file) {
            Ok(s) => s,
            Err(e) => {
                // Per-file I/O failure in directory mode: accumulate structured error (AC-F-14).
                json_files.push(serde_json::json!({
                    "file": file_key,
                    "error": e.serialize()
                }));
                return FileTally::Error;
            }
        };
        let fix_outcome = plan_and_apply_fixes(
            result,
            &source,
            base_dir,
            ctx.runtime_vars.clone(),
            &config,
            display_path,
        );
        match fix_outcome {
            FixFileOutcome::Fixed {
                new_source,
                residual,
            } => {
                // Write first (AC-F-14): on failure push a structured error entry so
                // the JSON envelope truthfully reflects what happened rather than
                // accumulating the clean post-fix result before the write is attempted.
                if let Err(e) = atomic_write_file(file, &new_source, Durability::Fsync) {
                    json_files.push(serde_json::json!({
                        "file": file_key,
                        "error": MdsError::Io { message: format!("{e}") }.serialize()
                    }));
                    return FileTally::Error;
                }
                accumulate_result_json(&residual, json_files);
                // PF-004: parity with lint_one_file_human — same quiet gate, same text.
                if !quiet {
                    eprintln!("Fixed: {}", safe_path(file));
                }
                tally_from_result(&residual)
            }
            FixFileOutcome::PartiallyFixed {
                new_source,
                residual,
                applied_count,
                total_count,
            } => {
                // Write first (AC-F-14 + print-after-write): on failure push a
                // structured error entry; only accumulate and print on success.
                if let Err(e) = atomic_write_file(file, &new_source, Durability::Fsync) {
                    json_files.push(serde_json::json!({
                        "file": file_key,
                        "error": MdsError::Io { message: format!("{e}") }.serialize()
                    }));
                    return FileTally::Error;
                }
                accumulate_result_json(&residual, json_files);
                // Unified message + quiet guard (#173).
                if !quiet {
                    eprintln!(
                        "Partially fixed: {} ({applied_count} of {total_count} fixes applied)",
                        safe_path(file)
                    );
                }
                tally_from_result(&residual)
            }
            FixFileOutcome::Rejected { reason, original } => {
                // D4 (AD-216-11): "fix rejected" is a status message — the safety
                // gate fired, the original diagnostics remain unmodified.  Suppress under
                // --quiet (main.rs:30).  The residual lint findings (and the exit code)
                // are unaffected: this message describes the --fix attempt, not the findings.
                if !quiet {
                    eprintln!(
                        "{}: fix rejected: {}",
                        safe_path(file),
                        safe_inline(&reason)
                    );
                }
                accumulate_result_json(&original, json_files);
                tally_from_result(&original)
            }
            FixFileOutcome::NothingToFix { original } => {
                accumulate_result_json(&original, json_files);
                tally_from_result(&original)
            }
        }
    } else if fix && (check || diff) {
        // Directory-mode preview — route through gated pipeline.
        let source = match read_source_file(file) {
            Ok(s) => s,
            Err(e) => {
                json_files.push(serde_json::json!({
                    "file": file_key,
                    "error": e.serialize()
                }));
                return FileTally::Error;
            }
        };
        // R1: in the WouldFix arm the per-file tally comes from the RESIDUAL
        // (what a real --fix would leave behind); the JSON body stays PRE-fix.
        // run_lint_directory floors the aggregate exit at 1 via any_would_fix.
        let tally = match preview_fixes(
            &result,
            &source,
            base_dir,
            ctx.runtime_vars.clone(),
            &config,
            display_path,
        ) {
            PreviewOutcome::WouldFix {
                ref fixed,
                ref residual,
            } => {
                *any_would_fix = true;
                if diff {
                    let label = safe_path(file);
                    let diff_str = render_unified_diff(&source, fixed, &label);
                    let _ = write_stdout(&diff_str);
                }
                // PF-004: parity with lint_one_file_human — same quiet gate, same text.
                if check && !quiet {
                    eprintln!("Would fix: {}", safe_path(file));
                }
                tally_from_result(residual)
            }
            PreviewOutcome::Rejected(ref reason) => {
                // D4 (AD-216-11): status message — suppress under --quiet.
                if !quiet {
                    eprintln!("{}: fix rejected: {}", safe_path(file), safe_inline(reason));
                }
                tally_from_result(&result)
            }
            PreviewOutcome::NothingToFix => tally_from_result(&result),
        };
        accumulate_result_json(&result, json_files);
        tally
    } else {
        accumulate_result_json(&result, json_files);
        tally_from_result(&result)
    }
}

/// Lint one file in directory mode, rendering diagnostics to stderr (human mode).
fn lint_one_file_human(
    file: &Path,
    display_path: &str,
    ctx: &LintDirCtx<'_>,
    any_truncated: &mut bool,
    any_would_fix: &mut bool,
) -> FileTally {
    let LintFlags {
        fix,
        check,
        diff,
        quiet,
        ..
    } = ctx.flags;

    // `display_path` is the lint-root-relative key computed once by
    // `run_lint_directory`'s pre-pass (#217), normalised to forward slashes and
    // identical to the unsanitized base used by that pre-pass's sort (AC-P1-10).
    // Human rendering shows the real filename bytes rather than sanitized
    // `\uXXXX` escapes.

    let source = match read_source_file(file) {
        Ok(s) => s,
        Err(e) => {
            eprint_error(miette::Report::from(e));
            return FileTally::Error;
        }
    };

    // effective_parent maps "" (bare filename) to "." — avoids PF-006.
    let base_dir = effective_parent(file);

    // A6: per-file config discovery — load (and cache) the nearest mds.json for
    // this file's directory. A config-load failure is a per-file error; the rest
    // of the tree continues linting.
    let config = match ctx.config_for(base_dir) {
        Ok(c) => c,
        Err(e) => {
            eprint_error(miette::Report::from(e));
            return FileTally::Error;
        }
    };

    // Named source for span rendering: relative display path + source text.
    let named_source = (display_path, source.as_str());

    let mut result = match mds::lint(file, ctx.runtime_vars.clone(), &config) {
        Ok(r) => r,
        Err(ref e) => {
            eprint_error(miette::Report::from(e.clone()));
            return if matches!(e, MdsError::ResourceLimit { .. }) {
                FileTally::ResourceLimit
            } else {
                FileTally::Error
            };
        }
    };
    // Remap basename-only file field → relative display path.
    set_diag_display_path(&mut result, display_path);

    if result.truncated {
        *any_truncated = true;
        // D4 (AD-216-11): this is a status message, not an error — suppress
        // under --quiet (main.rs:30 "Suppress status and diagnostic output").
        if fix && !quiet {
            eprintln!(
                "{}: diagnostic cap ({}) reached; further findings were suppressed — \
                 re-run --fix to continue",
                safe_path(file),
                mds::MAX_DIAGNOSTICS
            );
        }
    }

    if fix && !check && !diff {
        let fix_outcome = plan_and_apply_fixes(
            result,
            &source,
            base_dir,
            ctx.runtime_vars.clone(),
            &config,
            display_path,
        );
        match fix_outcome {
            FixFileOutcome::Fixed {
                new_source,
                residual,
            } => {
                render_result_human(&residual, quiet, named_source);
                if let Err(e) = atomic_write_file(file, &new_source, Durability::Fsync) {
                    eprintln!("error writing {}: {}", safe_path(file), safe_inline(&e));
                    return FileTally::Error;
                }
                if !quiet {
                    eprintln!("Fixed: {}", safe_path(file));
                }
                tally_from_result(&residual)
            }
            FixFileOutcome::PartiallyFixed {
                new_source,
                residual,
                applied_count,
                total_count,
            } => {
                render_result_human(&residual, quiet, named_source);
                if let Err(e) = atomic_write_file(file, &new_source, Durability::Fsync) {
                    eprintln!("error writing {}: {}", safe_path(file), safe_inline(&e));
                    return FileTally::Error;
                }
                // Print status AFTER write succeeds so "Partially fixed:" never
                // precedes "error writing" for a file that was never modified.
                // Unified message + quiet guard (#173).
                if !quiet {
                    eprintln!(
                        "Partially fixed: {} ({applied_count} of {total_count} fixes applied)",
                        safe_path(file)
                    );
                }
                tally_from_result(&residual)
            }
            FixFileOutcome::Rejected { reason, original } => {
                // D4 (AD-216-11): "fix rejected" is a status message — the safety
                // gate fired, the original diagnostics remain unmodified.  Suppress under
                // --quiet (main.rs:30).
                if !quiet {
                    eprintln!(
                        "{}: fix rejected: {}",
                        safe_path(file),
                        safe_inline(&reason)
                    );
                }
                render_result_human(&original, quiet, named_source);
                tally_from_result(&original)
            }
            FixFileOutcome::NothingToFix { original } => {
                render_result_human(&original, quiet, named_source);
                tally_from_result(&original)
            }
        }
    } else if fix && (check || diff) {
        // Directory-mode preview — route through gated pipeline.
        // R1: in the WouldFix arm the per-file tally comes from the RESIDUAL
        // (what a real --fix would leave behind); the rendered body stays
        // PRE-fix.  run_lint_directory floors the aggregate exit at 1 via
        // any_would_fix.
        let tally = match preview_fixes(
            &result,
            &source,
            base_dir,
            ctx.runtime_vars.clone(),
            &config,
            display_path,
        ) {
            PreviewOutcome::WouldFix {
                ref fixed,
                ref residual,
            } => {
                *any_would_fix = true;
                if diff {
                    let label = safe_path(file);
                    let diff_str = render_unified_diff(&source, fixed, &label);
                    let _ = write_stdout(&diff_str);
                }
                if check && !quiet {
                    eprintln!("Would fix: {}", safe_path(file));
                }
                tally_from_result(residual)
            }
            PreviewOutcome::Rejected(ref reason) => {
                if !quiet {
                    eprintln!("{}: fix rejected: {}", safe_path(file), safe_inline(reason));
                }
                tally_from_result(&result)
            }
            PreviewOutcome::NothingToFix => tally_from_result(&result),
        };
        render_result_human(&result, quiet, named_source);
        tally
    } else {
        render_result_human(&result, quiet, named_source);
        tally_from_result(&result)
    }
}

// ── Shared emit helpers ───────────────────────────────────────────────────────

/// Emit a `LintResult` to the appropriate channel based on format.
///
/// `named_source` is forwarded to human rendering for span context; ignored in JSON mode.
fn emit_result(
    format: LintFormat,
    result: &mds::LintResult,
    quiet: bool,
    named_source: Option<(&str, &str)>,
) {
    if format == LintFormat::Json {
        let json = result.to_canonical_json();
        let _ = write_stdout(&format!(
            "{}\n",
            serde_json::to_string(&json).expect("canonical lint JSON is always serializable")
        ));
    } else {
        render_result_human(
            result,
            quiet,
            named_source.expect("Human format requires named_source"),
        );
    }
}

/// AD-211-5 (2026-08-12 ruling): this envelope is the single CLI choke-point for
/// **lint's** analysis failures (config load, IO, resolution, parse).  When
/// `stdin_source` is `Some(source_text)` the embedded source identity in the rendered
/// output is replaced with [`STDIN_DISPLAY_LABEL`], so every CLI diagnostic context
/// for stdin input uses the uniform sentinel instead of the core's internal
/// `SOURCE_LABEL` (`"<source>"`) that `resolve_source_intrinsic` embeds in `MdsError`
/// spans.
///
/// **State it as a rule about this envelope, not about stdin:** every
/// `MdsError` reaching this function for a stdin run labels its source `<stdin>`.
/// Any error later routed here — a config rejection, a new IO failure — inherits
/// that label instead of inventing a second convention.
///
/// The JSON leg needs no relabel and takes none: `MdsError::serialize()` emits
/// `code` / `message` / `help` / `span`, and no `MdsError` `Display` template
/// interpolates `ctx.file_str`, so the source identity never reaches
/// `error.message`.  `cli_lint.rs::stdin_analysis_failure_labels_source_as_stdin`
/// pins that on both channels rather than leaving it as an assumption.
///
/// For errors from a file source, pass `stdin_source: None`; the error's embedded
/// `NamedSource` (which already carries the correct filename) is used as-is.
///
/// JSON format → stdout envelope; human → stderr via miette.
fn emit_analysis_failure_json_or_stderr(
    e: &MdsError,
    format: LintFormat,
    stdin_source: Option<&str>,
) {
    if format == LintFormat::Json {
        let envelope = serde_json::json!({
            "version": 1,
            "error": e.serialize()
        });
        let _ = write_stdout(&format!(
            "{}\n",
            serde_json::to_string(&envelope).expect("canonical lint JSON is always serializable")
        ));
    } else {
        // Route through the single render choke point (avoids PF-004 /
        // architecture-6: hand-rolled sanitize_control_chars bypass).
        let report = match stdin_source {
            Some(src) => relabel_stdin_error(e, src),
            None => miette::Report::from(e.clone()),
        };
        eprint_error(report);
    }
}

/// Extract and accumulate per-file JSON entries from a `LintResult` into `json_files`.
fn accumulate_result_json(result: &mds::LintResult, json_files: &mut Vec<serde_json::Value>) {
    let inner = result.to_canonical_json();
    if let Some(arr) = inner["files"].as_array() {
        json_files.extend(arr.iter().cloned());
    }
}

// ── Unit tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::{preview_fixes, PreviewOutcome};
    use mds::{FixLineSpan, LintDiagnostic, LintResult, Severity};
    use std::path::Path;

    /// ISS-13: CLI-level genuine partial overlaps are structurally impossible with
    /// the current 10 rules.  Every pair of real-rule fix spans is either disjoint
    /// (different AST blocks) or in a containment relationship (same block, different
    /// rules) — the latter is resolved by `dedup_contained_or_identical` before the
    /// overlap detector is reached.  No MDS fixture can drive `overlap_rejected=true`
    /// through the CLI binary.
    ///
    /// This unit test covers rejection surfacing at the deepest level reachable from
    /// the CLI crate: `preview_fixes` with a crafted `LintResult` whose `fix_removals`
    /// produce the same genuine partial overlap used in the mds-core ISS-02 regression
    /// test (fix.rs: `a4_partial_overlap_still_rejected_after_dedup`).
    ///
    /// Math (identical to ISS-02):
    ///   source = "line0\nline1\nline2\n"
    ///   Edit A: FixLineSpan::range_inclusive(0, 6)  → ByteEdit [0,  12)
    ///   Edit B: FixLineSpan::range_inclusive(6, 12) → ByteEdit [6,  18)
    ///   A.end=12 > B.start=6, B.end=18 > A.end=12 → partial overlap → overlap_rejected.
    ///
    /// `preview_fixes` must return `PreviewOutcome::Rejected` — the rejection must be
    /// surfaced (not silently swallowed as `NothingToFix`).  This pins PF-004: the
    /// preview path uses the same gated pipeline as the write path and is equally
    /// honest about overlap refusals.
    #[test]
    fn preview_fixes_surfaces_rejected_on_overlap() {
        let source = "line0\nline1\nline2\n";
        // Edit A covers bytes [0, 12): line0 start through line1 end (inclusive).
        let diag_a = LintDiagnostic::new("duplicate-import", Severity::Error, "a")
            .with_fix_removals(vec![FixLineSpan::range_inclusive(
                0, // inside line0
                6, // inside line1; extend_to_line_end(6) = 12
            )]);
        // Edit B covers bytes [6, 18): line1 start through line2 end (inclusive).
        // Partially overlaps A at [6, 12).
        let diag_b =
            LintDiagnostic::new("empty-block", Severity::Warn, "b").with_fix_removals(vec![
                FixLineSpan::range_inclusive(
                    6,  // inside line1
                    12, // inside line2; extend_to_line_end(12) = 18
                ),
            ]);
        let result = LintResult::new(vec![diag_a, diag_b]);

        let outcome = preview_fixes(
            &result,
            source,
            Path::new("."),
            None,
            &mds::LintConfig::default(),
            "overlap.mds",
        );

        assert!(
            matches!(outcome, PreviewOutcome::Rejected(_)),
            "preview_fixes must return Rejected for an overlap_rejected plan, \
             not NothingToFix or WouldFix (PF-004 — preview must be as honest as apply)"
        );
    }

    /// R1: the residual carried by `PreviewOutcome::WouldFix` must have every
    /// diagnostic's `file` field relabelled to the caller-supplied display label,
    /// mirroring the `plan_and_apply_fixes` contract.  Without the relabel the
    /// residual leaks the internal `STRING_SOURCE_MAP_LABEL` basename that
    /// `mds::lint_str_with` sets inside the reverify closure.
    ///
    /// The source carries one FIXABLE finding (empty-block on the bare `@if`) and
    /// one NON-fixable finding that survives the fix (unused-variable on the
    /// unreferenced frontmatter key), so the residual is non-empty — the label
    /// assertion cannot pass vacuously (PF-013), and a non-vacuity guard asserts
    /// the expected rule survived.
    #[test]
    fn preview_fixes_would_fix_relabels_residual_display_path() {
        let source = "---\nunused_key: value\n---\n\n@if \"a\" == \"a\":\n@end\n\nHello\n";
        let config = mds::LintConfig::default();
        let result = mds::lint_str_with(source, Some(Path::new(".")), None, &config)
            .expect("fixture source must lint");

        let outcome = preview_fixes(
            &result,
            source,
            Path::new("."),
            None,
            &config,
            "custom-label.mds",
        );

        match outcome {
            PreviewOutcome::WouldFix { ref residual, .. } => {
                assert!(
                    !residual.diagnostics.is_empty(),
                    "non-vacuity (PF-013): the unused-variable finding must survive the fix"
                );
                assert!(
                    residual
                        .diagnostics
                        .iter()
                        .any(|d| d.rule == "unused-variable"),
                    "non-vacuity (PF-013): expected the surviving rule to be unused-variable; \
                     got: {:?}",
                    residual
                        .diagnostics
                        .iter()
                        .map(|d| d.rule.as_str())
                        .collect::<Vec<_>>()
                );
                for diag in &residual.diagnostics {
                    assert_eq!(
                        diag.file.as_deref(),
                        Some("custom-label.mds"),
                        "R1: every residual diagnostic must carry the caller-supplied \
                         display label"
                    );
                }
            }
            _ => panic!(
                "preview_fixes must return WouldFix for a source with a fixable \
                 empty-block finding"
            ),
        }
    }

    /// #217: a path that is not under the lint root must be an `Io` error, never a
    /// key silently rebuilt out of the path's own components.
    ///
    /// The old body used `strip_prefix(root).unwrap_or(path)`, so an out-of-root
    /// path fell through to a `Normal`-component join of the FULL host path — a
    /// `files[].file` key describing a location outside the directory the user
    /// asked to lint, with the leading `/` quietly dropped.
    ///
    /// Positive control: the in-root arm must still return `Ok`, otherwise
    /// an unconditional `Err` would satisfy the rejection assertion while breaking
    /// every real path.
    #[test]
    fn relative_display_rejects_path_outside_root() {
        use super::relative_display;
        use std::path::Path;

        let root = Path::new("/lint-root");

        // Absolute out-of-root: the strip fails, and the first component of the
        // would-be fallback is `RootDir`.
        let err = relative_display(Path::new("/other/x.mds"), root)
            .expect_err("a path outside the lint root must not produce a display key");
        let message = err.to_string();
        assert!(
            message.contains("escapes lint root"),
            "out-of-root rejection must name the condition; got: {message:?}"
        );

        // RELATIVE out-of-root: every component is `Normal`, so the component
        // guard cannot see this one — only the `strip_prefix` result can reject
        // it. Without this arm a reintroduced `strip_prefix(root).unwrap_or(path)`
        // still satisfies the absolute arm above and goes unnoticed.
        let rel_root = Path::new("lint-root");
        let rel_err = relative_display(Path::new("other/x.mds"), rel_root)
            .expect_err("a relative path outside the lint root must not produce a display key");
        let rel_message = rel_err.to_string();
        assert!(
            rel_message.contains("escapes lint root"),
            "relative out-of-root rejection must name the condition; got: {rel_message:?}"
        );

        // CONTROL ARMS: in-root paths must still succeed with the unchanged key,
        // under both an absolute and a relative root.
        assert_eq!(
            relative_display(Path::new("/lint-root/a/b.mds"), root)
                .expect("an in-root path must still produce a display key"),
            "a/b.mds",
            "control: the in-root key must be byte-identical to the pre-#217 output"
        );
        assert_eq!(
            relative_display(Path::new("lint-root/a/b.mds"), rel_root)
                .expect("an in-root path under a relative root must still produce a key"),
            "a/b.mds",
            "control: the relative-root in-root key must be byte-identical too"
        );
    }

    /// #217: a directory entry whose name is not valid UTF-8 must be an `Io` error,
    /// never a lossy key.
    ///
    /// The old body ran `to_string_lossy` over each component, so an entry named
    /// with two invalid bytes became a key of two U+FFFD replacement characters —
    /// a `files[].file` value that names no file on disk and collides with every
    /// other undecodable name in the tree.
    ///
    /// The invalid bytes are built at RUNTIME from numeric values; no escape
    /// sequence or raw byte appears in this source file (Source hygiene gate).
    ///
    /// Positive control: the valid-UTF-8 arm must still return `Ok`.
    #[cfg(unix)]
    #[test]
    fn relative_display_rejects_non_utf8_component() {
        use super::relative_display;
        use std::os::unix::ffi::OsStrExt;
        use std::path::Path;

        let root = Path::new("/lint-root");

        // 0xFF and 0xFE are not legal UTF-8 lead bytes in any position.
        let raw: Vec<u8> = vec![0xff, 0xfe, b'.', b'm', b'd', b's'];
        let hostile = root.join(std::ffi::OsStr::from_bytes(&raw));

        let err = relative_display(&hostile, root)
            .expect_err("a non-UTF-8 entry name must not produce a display key");
        let message = err.to_string();
        assert!(
            message.contains("not valid UTF-8"),
            "non-UTF-8 rejection must name the condition; got: {message:?}"
        );

        // CONTROL ARM: a valid-UTF-8 sibling in the same root must still succeed.
        assert_eq!(
            relative_display(&root.join("ok.mds"), root)
                .expect("a valid-UTF-8 entry must still produce a display key"),
            "ok.mds",
            "control: the valid-UTF-8 key must be byte-identical to the pre-#217 output"
        );
    }

    /// Regression: `relative_display` must NOT treat a literal backslash in a
    /// Unix filename as a path separator.
    ///
    /// On Unix, POSIX forbids only `/` and NUL in filenames; `\` is an ordinary
    /// byte.  The old `to_string_lossy().replace('\\', "/")` implementation
    /// turned `sub/..\..\etc\evil.mds` into `sub/../../../etc/evil.mds`,
    /// providing a directory-traversal vector (CWE-22/CWE-41) and causing key
    /// collisions on the published lint JSON wire surface when two distinct files
    /// (e.g. `a/b.mds` and `a\b.mds`) were linted together.
    ///
    /// The new `Path::components()` join preserves `\` as a literal filename
    /// byte on Unix and normalises it to a separator on Windows, which is the
    /// correct platform-aware behaviour.
    ///
    /// Path construction uses Rust string literals containing a backslash byte
    /// (0x5C) — not a control byte, so the Source hygiene gate does not flag it.
    #[cfg(unix)]
    #[test]
    fn relative_display_preserves_literal_backslash_on_unix() {
        use super::relative_display;
        use std::path::Path;

        let root = Path::new("/lint-root");

        // A real subdirectory: /lint-root/a/b.mds  (two path components under root)
        let real_subdir = Path::new("/lint-root/a/b.mds");

        // A top-level file whose NAME contains a literal backslash: /lint-root/a\b.mds
        // On Unix the backslash is just a filename byte; Path treats this as ONE
        // component under root (not two).  The string "a\\b.mds" in Rust source
        // is the byte sequence a, 0x5C, b, ., m, d, s — no control bytes.
        let backslash_name = Path::new("/lint-root/a\\b.mds");

        let display_subdir = relative_display(real_subdir, root).expect("in-root path");
        let display_backslash = relative_display(backslash_name, root).expect("in-root path");

        assert_eq!(
            display_subdir, "a/b.mds",
            "real subdirectory path should emit forward-slash-separated key"
        );
        assert_eq!(
            display_backslash, "a\\b.mds",
            "a literal backslash filename byte must be preserved in the emitted key on Unix"
        );
        assert_ne!(
            display_subdir, display_backslash,
            "a literal-backslash filename must not collide with the same letters \
             separated by a real slash (was broken by the old .replace() approach)"
        );
    }

    /// Regression: the directory-mode sort key must be the SANITIZED display path
    /// so that sort position matches the sanitized `files[].file` key emitted by
    /// `to_canonical_json` for diagnostic entries, including control-byte filenames
    /// (AC-P1-10).
    ///
    /// Without sanitization: a file whose name begins with 0x01 (a C0 control byte)
    /// sorts BEFORE "P.mds" in the raw byte order (0x01 < 0x50), but its sanitized
    /// emitted key starts with `\` (0x5C, the JSON-escape prefix for byte 0x01),
    /// placing it AFTER "P.mds" in emitted-key order — violating AC-P1-10.
    ///
    /// With the sanitized sort key the two orderings agree: "P.mds" (emitted "P.mds")
    /// sorts before the control-byte file (whose JSON-emitted key starts with `\`) in both
    /// the array position and the emitted key comparison.
    ///
    /// The control byte is constructed at runtime via char::from(1u8) so that no
    /// literal control byte or \uXXXX escape appears in the source file (PF-018 /
    /// Source hygiene gate).
    #[cfg(unix)]
    #[test]
    fn sort_key_sanitizes_control_byte_filenames() {
        use super::relative_display;
        use std::path::Path;

        let root = Path::new("/lint-root");

        // Build a filename starting with byte 0x01 at runtime — not as a literal
        // control byte in source (PF-018).
        let ctrl_char = char::from(1u8); // U+0001, a C0 control character
        let ctrl_filename = format!("{ctrl_char}a.mds");
        let ctrl_path_buf = root.join(&ctrl_filename);
        let ctrl_path: &Path = &ctrl_path_buf;
        let normal_path = Path::new("/lint-root/P.mds");

        let ctrl_raw = relative_display(ctrl_path, root).expect("in-root path");
        let normal_raw = relative_display(normal_path, root).expect("in-root path");

        // Raw (unsanitized) order: 0x01 < 'P' (0x50) → control-byte file sorts first.
        assert!(
            ctrl_raw < normal_raw,
            "raw display: control-byte path ({ctrl_raw:?}) must sort before P.mds by \
             unsanitized byte order (confirms old sort would have been wrong)"
        );

        // Sanitized sort keys: byte 0x01 becomes a JSON escape starting with '\' (0x5C).
        // 0x5C > 'P' (0x50), so P.mds sorts first — matching the emitted key order.
        let ctrl_sort_key = mds::sanitize_control_chars_wire(&ctrl_raw).into_owned();
        let normal_sort_key = mds::sanitize_control_chars_wire(&normal_raw).into_owned();

        assert!(
            normal_sort_key < ctrl_sort_key,
            "sanitized sort key: P.mds ({normal_sort_key:?}) must sort before \
             control-byte file ({ctrl_sort_key:?}) — matching the emitted key order \
             (AC-P1-10)"
        );
    }

    /// Platform-independent: directory-mode sort must be byte-wise ascending over
    /// the normalised forward-slash display strings emitted by `relative_display`.
    ///
    /// Constructs paths via `PathBuf::join` (platform-agnostic component builder)
    /// so the test runs unmodified on both Unix and Windows without a `#[cfg]` guard.
    /// `relative_display` always joins with `/`, so the sort key is identical on both
    /// platforms.
    ///
    /// Critical ordering property: a flat file whose name starts with `sub[` must
    /// sort AFTER a nested file in directory `sub/`, because `/` (0x2F) < `[` (0x5B).
    /// If `relative_display` were changed to use the native separator (`\`, 0x5C on
    /// Windows), the `[` (0x5B) file would sort BEFORE the nested path (0x5B < 0x5C),
    /// reversing the intended order — and this test would fail on any platform where
    /// the temporary separator change is in effect (ADR-009 verified by changing
    /// `join("/")` to `join("\\")` in `relative_display`, confirming the test fails).
    ///
    /// The test exercises the same key function used by `run_lint_directory`'s
    /// `sort_by_cached_key` (F1): `sanitize_control_chars_wire(relative_display(p, dir))`.
    /// No filesystem access is needed — `relative_display` is a pure path computation.
    #[test]
    fn directory_sort_ascending_over_normalized_display_strings() {
        use super::relative_display;
        use std::path::PathBuf;

        // Build paths via PathBuf::join — uses native separator internally, but
        // `relative_display` always emits `/`-joined strings regardless of platform.
        let root = PathBuf::from("lint-root");
        let file_a = root.join("a.mds"); // flat: display "a.mds"
        let file_sub_a = root.join("sub").join("a.mds"); // nested: display "sub/a.mds"
        let file_sub_bracket = root.join("sub[after.mds"); // flat, [ in name: "sub[after.mds"
        let file_z = root.join("z.mds"); // flat: display "z.mds"

        // Verify display strings first (documents intent and catches platform drift).
        let display_a = relative_display(&file_a, &root).expect("in-root path");
        let display_sub_a = relative_display(&file_sub_a, &root).expect("in-root path");
        let display_sub_bracket = relative_display(&file_sub_bracket, &root).expect("in-root path");
        let display_z = relative_display(&file_z, &root).expect("in-root path");

        assert_eq!(
            display_a, "a.mds",
            "flat file must display without separator"
        );
        assert_eq!(
            display_sub_a, "sub/a.mds",
            "nested file must use forward-slash separator"
        );
        assert_eq!(
            display_sub_bracket, "sub[after.mds",
            "flat file with [ in name must display as single component"
        );
        assert_eq!(
            display_z, "z.mds",
            "flat file must display without separator"
        );

        // Sort by the same key as `run_lint_directory` (F1): sanitized display string.
        let mut paths = [
            file_z.clone(),
            file_sub_bracket.clone(),
            file_a.clone(),
            file_sub_a.clone(),
        ];
        paths.sort_by_cached_key(|p| {
            mds::sanitize_control_chars_wire(&relative_display(p, &root).expect("in-root path"))
                .into_owned()
        });

        let sorted: Vec<String> = paths
            .iter()
            .map(|p| relative_display(p, &root).expect("in-root path"))
            .collect();

        // Expected byte-wise order:
        //   "a.mds"        — 'a' (0x61)
        //   "sub/a.mds"    — 's' then '/' (0x2F) at position 3
        //   "sub[after.mds"— 's' then '[' (0x5B) at position 3  (0x2F < 0x5B)
        //   "z.mds"        — 'z' (0x7A)
        //
        // If relative_display used '\' (0x5C) instead of '/' (0x2F):
        //   "sub[after.mds" would sort BEFORE "sub\a.mds" (0x5B < 0x5C) — wrong.
        assert_eq!(
            sorted,
            vec!["a.mds", "sub/a.mds", "sub[after.mds", "z.mds"],
            "directory sort must be byte-wise ascending over normalised forward-slash \
             display strings; '/' (0x2F) must sort before '[' (0x5B) so nested paths \
             appear before same-prefix flat files with bracket-containing names"
        );
    }

    /// Windows-only: `relative_display` must normalise the native backslash separator
    /// to a forward slash in the emitted display string.
    ///
    /// This test will not execute in CI today (the Rust matrix uses `ubuntu-latest`
    /// only — adding `windows-latest` is a separate scope decision), but it documents
    /// the expected behaviour and will start running the moment the matrix is extended.
    #[cfg(windows)]
    #[test]
    fn relative_display_normalizes_windows_separator_to_forward_slash() {
        use super::relative_display;
        use std::path::Path;

        // Windows absolute path: C:\proj\sub\c.mds with root C:\proj
        let path = Path::new(r"C:\proj\sub\c.mds");
        let root = Path::new(r"C:\proj");
        let display = relative_display(path, root).expect("in-root path");

        assert_eq!(
            display, "sub/c.mds",
            "relative_display must emit forward-slash separator on Windows; \
             got {display:?} — native backslash must not appear in the wire key"
        );
    }
}