mds-cli 0.5.1

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
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
//! Shared output-path machinery for build, check, watch, fmt, and lint subcommands.
//!
//! # What lives here
//!
//! - [`OutputBase`] / [`resolve_output_base`] / [`output_path_for`]: directory-mode
//!   path resolution used by watch and build-directory. Each output is a
//!   [`WriteTarget`]: the path written, the path a message shows (#390), and the anchor
//!   [`crate::write::write_compiled`] writes it below (#160).
//! - [`collect_mds_files`] / [`is_partial`]: directory traversal helpers.
//! - [`probe_and_remove_stale`]: a directory build's stale-output cleanup after a change of
//!   kind, which removes only a `.json` mds provably wrote (#160).
//! - `ewriteln!` over [`write_stderr_fmt`]: the CLI's stderr choke point,
//!   which never panics — a closed pipe or a failed write becomes sticky [`OutputState`]
//!   instead (#157). [`write_stdout`] writes a command's product and reports a
//!   [`StdoutOutcome`], writing nothing once stdout's reader is gone; [`exit`] ends the
//!   process through [`final_exit_code`].
//! - [`install_panic_hook`] / [`catch_panic`]: a panic prints one fixed
//!   internal-compiler-error text — never the panic's message or location — and the run
//!   exits 101 (#389). [`catch_compile`] catches a panic in one file's compile, so a
//!   directory run or a watch session goes on without that file.
//! - [`eprint_error`]: the CLI's error-report choke point — escapes every report's
//!   message, help, and label text before miette renders it (CWE-150), then writes the
//!   frame through `ewriteln!`.
//! - [`preview_text_for`]: `--diff` preview output — neutralized on TTY, byte-faithful
//!   when piped, so redirected diffs stay applicable by `patch`/tooling.
//!
//! Single-file path helpers (`OutputKind`, `compile_to_content`,
//! `resolve_output_path_for_kind`) remain in `build.rs`; they are imported here when
//! callers need both single-file and directory logic.

use std::borrow::Cow;
use std::ffi::OsStr;
use std::io::{IsTerminal, Write as _};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};

use miette::Result;

use crate::build::{OutputKind, ProjectConfig};
use crate::write::{DirIdentity, NotRemoved, Removal};

// ── Streams and the exit funnel (#157) ───────────────────────────────────────

/// `eprintln!` for the CLI: write a line to stderr through [`write_stderr_fmt`], which
/// never panics.
///
/// `tests/print_discipline.rs` lists this macro beside the std print macros and scans
/// its arguments the same way. A stderr writer the guard does not list would take every
/// site that uses it out of the guard.
macro_rules! ewriteln {
    () => {
        $crate::output::write_stderr_fmt(::std::format_args!("\n"))
    };
    ($($arg:tt)+) => {
        $crate::output::write_stderr_fmt(::std::format_args!(
            "{}\n",
            ::std::format_args!($($arg)+)
        ))
    };
}

pub(crate) use ewriteln;

/// Sticky facts about the CLI's output streams, read when the process exits.
///
/// Each fact is one bit, set with `fetch_or`, so a fact recorded on any thread is still
/// there at exit. Only `STDOUT_FAILED` is ever cleared: it marks stdout's current
/// failure, which a write that lands ends. No fact the exit code reads is cleared.
/// Functions that decide something from these facts take `&OutputState`, so a unit test
/// builds its own instead of sharing the process's [`OUTPUT_STATE`] with every other
/// test in the binary.
///
/// Adding a fact is adding one bit and its accessors.
///
/// It also holds one request that is not a fact for the exit code: a terminal clear that
/// `mds watch --clear` asked for and the next printed byte makes ([`OutputState::ask_clear`]).
pub(crate) struct OutputState {
    bits: AtomicU8,
    clear_asked: AtomicBool,
}

impl OutputState {
    /// A stderr write hit a closed pipe: the reader is gone.
    const STDERR_CLOSED: u8 = 1 << 0;
    /// An output operation — a write, a flush, a directory creation, a delete — failed
    /// for any reason other than a closed pipe.
    const IO_FAILED: u8 = 1 << 1;
    /// A stdout write hit a closed pipe: the reader is gone.
    const STDOUT_CLOSED: u8 = 1 << 2;
    /// A stdout write failed for a reason other than a closed pipe, and no write has
    /// landed since. Cleared by a write that lands, so a later failure is a new one.
    const STDOUT_FAILED: u8 = 1 << 3;
    /// A `mds watch` session went live: from then on its output failures do not change
    /// the exit code ([`ExitPolicy::WatchSession`]).
    const WATCH_LIVE: u8 = 1 << 4;
    /// A panic happened (#389): the run exits 101, whatever else it recorded.
    const PANICKED: u8 = 1 << 5;
    /// A file of a run that carries on past it was refused for a resource limit: the
    /// run exits 3 ([`ExitPolicy::Batch`]), as that file alone would (#157).
    const RESOURCE_LIMITED: u8 = 1 << 6;
    /// A file returned an internal compiler error. A batch exits 101.
    const INTERNAL_FAILED: u8 = 1 << 7;

    pub(crate) const fn new() -> Self {
        Self {
            bits: AtomicU8::new(0),
            clear_asked: AtomicBool::new(false),
        }
    }

    /// Set `bit`; `true` when this call is the one that set it.
    fn set(&self, bit: u8) -> bool {
        self.bits.fetch_or(bit, Ordering::AcqRel) & bit == 0
    }

    fn clear(&self, bit: u8) {
        self.bits.fetch_and(!bit, Ordering::AcqRel);
    }

    fn has(&self, bit: u8) -> bool {
        self.bits.load(Ordering::Acquire) & bit != 0
    }

    /// Record that stderr's reader is gone. Later stderr writes are dropped.
    pub(crate) fn note_stderr_closed(&self) {
        self.set(Self::STDERR_CLOSED);
    }

    /// Record an output operation that failed for a reason other than a closed pipe.
    pub(crate) fn note_io_failure(&self) {
        self.set(Self::IO_FAILED);
    }

    /// Record that stdout's reader is gone. Later stdout writes are dropped.
    pub(crate) fn note_stdout_closed(&self) {
        self.set(Self::STDOUT_CLOSED);
    }

    /// Record a stdout write that failed for a reason other than a closed pipe; `true`
    /// for the first failed write since the run began or since a write last landed —
    /// the one that is reported.
    pub(crate) fn note_stdout_failure(&self) -> bool {
        self.set(Self::STDOUT_FAILED)
    }

    /// Record a stdout write that landed: stdout's current failure, if any, is over, so
    /// the next failure is reported again. The I/O failure recorded for the exit code
    /// stays recorded.
    pub(crate) fn note_stdout_written(&self) {
        self.clear(Self::STDOUT_FAILED);
    }

    pub(crate) fn stderr_closed(&self) -> bool {
        self.has(Self::STDERR_CLOSED)
    }

    pub(crate) fn io_failed(&self) -> bool {
        self.has(Self::IO_FAILED)
    }

    pub(crate) fn stdout_closed(&self) -> bool {
        self.has(Self::STDOUT_CLOSED)
    }

    /// Record that a `mds watch` session went live.
    pub(crate) fn note_watch_live(&self) {
        self.set(Self::WATCH_LIVE);
    }

    /// Record that a panic happened (#389).
    pub(crate) fn note_panicked(&self) {
        self.set(Self::PANICKED);
    }

    pub(crate) fn panicked(&self) -> bool {
        self.has(Self::PANICKED)
    }

    /// Record a file refused for a resource limit by a run that carries on past it (#157).
    pub(crate) fn note_resource_limited(&self) {
        self.set(Self::RESOURCE_LIMITED);
    }

    pub(crate) fn resource_limited(&self) -> bool {
        self.has(Self::RESOURCE_LIMITED)
    }

    fn note_internal_failed(&self) {
        self.set(Self::INTERNAL_FAILED);
    }

    fn internal_failed(&self) -> bool {
        self.has(Self::INTERNAL_FAILED)
    }

    /// Ask for a terminal clear before the next byte this process prints (#380): the
    /// next non-empty stderr write, or the next non-empty stdout write, makes it first.
    pub(crate) fn ask_clear(&self) {
        self.clear_asked.store(true, Ordering::Release);
    }

    /// Drop an asked clear without making it: a rebuild that printed nothing, or a
    /// panic report, which a clear must neither precede nor wipe (#380, #389).
    pub(crate) fn cancel_clear(&self) {
        self.clear_asked.store(false, Ordering::Release);
    }

    /// Take the asked clear: `true` once for each [`OutputState::ask_clear`], so one
    /// request makes one clear.
    fn take_clear(&self) -> bool {
        self.clear_asked.swap(false, Ordering::AcqRel)
    }

    #[cfg(test)]
    pub(crate) fn clear_is_asked(&self) -> bool {
        self.clear_asked.load(Ordering::Acquire)
    }

    /// The rule [`final_exit_code`] applies when the process exits:
    /// [`ExitPolicy::WatchSession`] once a watch session went live,
    /// [`ExitPolicy::Batch`] for every other run.
    pub(crate) fn exit_policy(&self) -> ExitPolicy {
        if self.has(Self::WATCH_LIVE) {
            ExitPolicy::WatchSession
        } else {
            ExitPolicy::Batch
        }
    }
}

/// The process's own [`OutputState`], used by the process-boundary functions
/// [`write_stderr_fmt`], [`write_stdout`], [`note_io_failure`],
/// [`note_watch_session_live`], [`exit`] and the panic hook, [`on_panic`].
static OUTPUT_STATE: OutputState = OutputState::new();

/// Record, for the exit code, that an output operation of this run failed for a reason
/// other than a closed pipe: [`exit`] then ends the run with at least 2 (#157).
///
/// For a run that reports a failure and carries on — a directory build or
/// `mds fmt <dir>` counting the file as failed — and so never returns the error to
/// `main`. A run that returns the `mds::io` error reaches the same exit code through
/// `exit_code` instead. `mds watch` never calls it: a rebuild's failure is reported as
/// it happens and does not change how the session exits ([`note_watch_session_live`]).
pub(crate) fn note_io_failure() {
    OUTPUT_STATE.note_io_failure();
}

/// Record that this `mds watch` session is live — every watch armed, every baseline
/// captured (#157). From here on [`exit`] applies [`ExitPolicy::WatchSession`]: a
/// rebuild's output failure, reported as it happened, and a stderr that fails other
/// than by a closed pipe no longer change the exit code. Until then — a session that
/// ends at startup — the batch rule applies.
pub(crate) fn note_watch_session_live() {
    OUTPUT_STATE.note_watch_live();
}

/// Erase the screen and the scrollback, then move the cursor home.
const CLEAR_SEQUENCE: &str = "\x1b[2J\x1b[3J\x1b[H";

/// Ask for `mds watch --clear`'s terminal clear (#380). The clear is made before the
/// next byte the process prints, on stderr, so it never wipes a line already printed —
/// a compile warning, a failure report — and a rebuild that prints nothing makes none.
/// Asked only when stderr is a terminal: the clear is a terminal control sequence.
pub(crate) fn ask_clear() {
    if stderr_is_a_terminal() {
        OUTPUT_STATE.ask_clear();
    }
}

/// Drop an asked clear without making it ([`OutputState::cancel_clear`]).
pub(crate) fn cancel_clear() {
    OUTPUT_STATE.cancel_clear();
}

/// Whether stderr is a terminal. A unit test's child process started with
/// `child_process::run_on_a_terminal` (test builds only) answers yes, so a test can see
/// the clear.
fn stderr_is_a_terminal() -> bool {
    #[cfg(test)]
    if child_process::on_a_terminal() {
        return true;
    }
    std::io::stderr().is_terminal()
}

/// Report an I/O failure of a run that carries on past it — a directory build,
/// `mds fmt <dir>` — as one `mds::io` error, and record it for the exit code (#157).
pub(crate) fn eprint_io_failure(e: mds::MdsError) {
    note_io_failure();
    eprint_error(miette::Report::new(e));
}

/// Report why one file of a directory build, check or fmt failed, and carry on.
///
/// A failure in the I/O and file-system class — exit 2 for the same file given alone:
/// `mds::io` (a source that cannot be read, a forbidden path character),
/// `mds::file_not_found`, `mds::not_mds` — is recorded for the exit code, so the run
/// exits 2 as that file alone would. A resource limit lifts the exit code to 3.
/// An internal compiler error lifts it to 101. A template error leaves the exit code
/// to the caller's count of failed files (1).
pub(crate) fn eprint_file_failure(report: miette::Report) {
    note_file_failure(&OUTPUT_STATE, &report);
    eprint_error(report);
}

/// Record in `state` what `report`, the failure of one file of a run that carries on past
/// it, means for the exit code: the class of the file's own exit code, when that class
/// lifts the run's ([`eprint_file_failure`]).
fn note_file_failure(state: &OutputState, report: &miette::Report) {
    match crate::build::exit_code(report) {
        IO_FAILURE_EXIT => state.note_io_failure(),
        RESOURCE_LIMIT_EXIT => state.note_resource_limited(),
        PANIC_EXIT => state.note_internal_failed(),
        _ => {}
    }
}

/// The body of `ewriteln!`: write `args` to stderr, never panicking.
///
/// std's `eprintln!` panics when the write fails, which ends the run with exit 101.
/// Here instead:
///
/// - A closed pipe (the reader is gone) records [`OutputState::note_stderr_closed`];
///   this write and every later stderr write are dropped, and the exit code does not
///   change.
/// - Any other write error records [`OutputState::note_io_failure`], which
///   [`final_exit_code`] turns into an exit of at least 2. Later writes are still
///   attempted.
pub(crate) fn write_stderr_fmt(args: std::fmt::Arguments<'_>) {
    write_stderr_to(&OUTPUT_STATE, &mut std::io::stderr().lock(), args);
}

/// [`write_stderr_fmt`] against any sink and state.
///
/// The text is rendered first and written with one `write_all`, then flushed. A
/// `Display` that fails ends the text where it failed: that is a bug in the impl, not an
/// output failure, so it records nothing. A clear asked for ([`ask_clear`]) goes in front
/// of the first non-empty text, in the same `write_all`.
fn write_stderr_to<W: std::io::Write + ?Sized>(
    state: &OutputState,
    sink: &mut W,
    args: std::fmt::Arguments<'_>,
) {
    if state.stderr_closed() {
        return;
    }
    let mut text = String::new();
    let _ = std::fmt::Write::write_fmt(&mut text, args);
    if !text.is_empty() && state.take_clear() {
        text.insert_str(0, CLEAR_SEQUENCE);
    }
    write_stderr_text(state, sink, &text);
}

/// Make an asked clear ([`ask_clear`]) on stderr now, before a command's product reaches
/// stdout: the screen clears before the rebuild's output appears, also under `--quiet`.
fn write_pending_clear_to<W: std::io::Write + ?Sized>(state: &OutputState, sink: &mut W) {
    if !state.stderr_closed() && state.take_clear() {
        write_stderr_text(state, sink, CLEAR_SEQUENCE);
    }
}

/// Write `text` to stderr with one `write_all`, then flush, recording a failure as
/// [`write_stderr_fmt`] says.
fn write_stderr_text<W: std::io::Write + ?Sized>(state: &OutputState, sink: &mut W, text: &str) {
    match sink.write_all(text.as_bytes()).and_then(|()| sink.flush()) {
        Ok(()) => {}
        Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => state.note_stderr_closed(),
        Err(_) => state.note_io_failure(),
    }
}

/// What happened to one [`write_stdout`] call.
#[must_use]
#[derive(Debug)]
pub(crate) enum StdoutOutcome {
    /// Every byte was written and flushed.
    Written,
    /// The reader is gone — a closed pipe, on this write or an earlier one. Nothing more
    /// is written to stdout, and the verdict is kept.
    Closed,
    /// A new stdout failure for any other reason — the first of the run, or the first
    /// since a write last landed: the caller reports it as `mds::io`.
    Failed(std::io::Error),
    /// Another failure after [`StdoutOutcome::Failed`] was returned, with no write
    /// landing in between: nothing was written, and the failure is not reported a
    /// second time.
    FailedAgain,
}

impl StdoutOutcome {
    /// What a run that ends on its own — build, fmt — makes of the outcome.
    ///
    /// A closed pipe is not an error: the reader is gone, so stdout gets nothing more
    /// and the run keeps its verdict. A new failure for another reason is `mds::io`,
    /// naming stdout; a repeat of it was already reported (#157). Nothing is recorded
    /// here; an `Err` reaches the exit code through the caller.
    ///
    /// `mds watch -o -` reads the outcome itself instead: a closed pipe ends its session,
    /// and neither it nor a repeated failure is a write it may remember as done.
    pub(crate) fn into_batch_result(self) -> std::result::Result<(), mds::MdsError> {
        match self {
            Self::Written | Self::Closed | Self::FailedAgain => Ok(()),
            Self::Failed(e) => Err(stdout_failure(&e)),
        }
    }
}

/// The `mds::io` error for a stdout write that failed for a reason other than a closed
/// pipe (#157).
pub(crate) fn stdout_failure(e: &std::io::Error) -> mds::MdsError {
    mds::MdsError::Io {
        message: format!("cannot write to stdout: {}", safe_inline(io_cause(e))),
    }
}

/// Write a command's product — compiled output, a diff, a JSON report — to stdout and
/// flush it. [`StdoutOutcome::Written`] only when both the write and the flush succeed.
///
/// Once stdout's reader is gone, every later call returns [`StdoutOutcome::Closed`]
/// without writing. After a failure for another reason, later calls still write, and a
/// repeat of the failure is [`StdoutOutcome::FailedAgain`], so it is reported once for
/// as long as it lasts. A write that lands ends it: a failure after that is new, and
/// [`StdoutOutcome::Failed`] again — a `mds watch -o -` session whose stdout recovers
/// and fails again reports both (#157). A write of no bytes shows nothing about stdout
/// and ends nothing.
///
/// A clear asked for ([`ask_clear`]) is made on stderr before non-empty bytes go to an
/// open stdout.
pub(crate) fn write_stdout(bytes: &[u8]) -> StdoutOutcome {
    if !bytes.is_empty() && !OUTPUT_STATE.stdout_closed() {
        write_pending_clear_to(&OUTPUT_STATE, &mut std::io::stderr().lock());
    }
    write_stdout_to(&OUTPUT_STATE, &mut std::io::stdout().lock(), bytes)
}

/// [`write_stdout`] against any sink and state.
fn write_stdout_to<W: std::io::Write + ?Sized>(
    state: &OutputState,
    sink: &mut W,
    bytes: &[u8],
) -> StdoutOutcome {
    if state.stdout_closed() {
        return StdoutOutcome::Closed;
    }
    match sink.write_all(bytes).and_then(|()| sink.flush()) {
        Ok(()) => {
            if !bytes.is_empty() {
                state.note_stdout_written();
            }
            StdoutOutcome::Written
        }
        Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {
            state.note_stdout_closed();
            StdoutOutcome::Closed
        }
        Err(e) => {
            if state.note_stdout_failure() {
                StdoutOutcome::Failed(e)
            } else {
                StdoutOutcome::FailedAgain
            }
        }
    }
}

/// Which rule [`final_exit_code`] applies.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ExitPolicy {
    /// A run that ends on its own — build, check, fmt, lint, init, and a watch session
    /// that never went live. An output failure lifts the exit code to at least 2.
    /// A resource limit lifts it to at least 3. An internal compiler error sets it to 101.
    Batch,
    /// A watch session after it went live ([`note_watch_session_live`]): its per-rebuild
    /// failures were reported as they happened, and they do not change the exit code.
    WatchSession,
}

/// The lowest exit code a batch run with an output failure ends with.
const IO_FAILURE_EXIT: i32 = 2;

/// The lowest exit code a batch run with a file refused for a resource limit ends with.
const RESOURCE_LIMIT_EXIT: i32 = 3;

/// The code a run whose verdict is `verdict` exits with, given what happened to its
/// output and to its files.
///
/// A panic comes first: a run that panicked exits 101 ([`PANIC_EXIT`]) under either
/// policy, whatever its verdict (#389). Otherwise a closed stdout or stderr pipe never
/// changes the code. A batch exits 101 after an internal compiler error in any file.
/// Otherwise, an output failure lifts the batch code to at least 2. A resource limit
/// lifts it to at least 3. [`ExitPolicy::WatchSession`] returns `verdict` unchanged.
#[must_use]
pub(crate) fn final_exit_code(verdict: i32, state: &OutputState, policy: ExitPolicy) -> i32 {
    if state.panicked() {
        return PANIC_EXIT;
    }
    match policy {
        ExitPolicy::Batch if state.internal_failed() => PANIC_EXIT,
        ExitPolicy::Batch => {
            let after_io = if state.io_failed() {
                verdict.max(IO_FAILURE_EXIT)
            } else {
                verdict
            };
            if state.resource_limited() {
                after_io.max(RESOURCE_LIMIT_EXIT)
            } else {
                after_io
            }
        }
        ExitPolicy::WatchSession => verdict,
    }
}

/// End the process: the CLI's exit funnel.
///
/// Exits with [`final_exit_code`] of `verdict` under the policy the run's state records
/// ([`OutputState::exit_policy`]): [`ExitPolicy::Batch`], so an output failure recorded
/// anywhere in the run is honoured on the way out — unless a watch session went live.
pub(crate) fn exit(verdict: i32) -> ! {
    std::process::exit(final_exit_code(
        verdict,
        &OUTPUT_STATE,
        OUTPUT_STATE.exit_policy(),
    ))
}

// ── Panics: one internal-compiler-error text (#389) ──────────────────────────
//
// A panic anywhere in the process runs `on_panic`, which prints `ICE_TEXT` and never
// the panic's message or location: a panic message can carry a user's text or a build
// machine's absolute paths. The run then exits 101. `main` runs the whole command
// inside `catch_panic`, so a panic on its thread unwinds — running the destructors that
// remove temporary files — to the exit funnel; a panic nothing catches, on a helper
// thread for one, ends the process at once through `exit_after_panic`. A batch runs
// each file's compile inside `catch_compile`, so a panic there fails that file alone.

/// What the CLI prints when it panics: that it failed, and where to report it. Nothing
/// about the panic itself.
const ICE_TEXT: &str = concat!(
    "mds: internal compiler error\n",
    "note: this is a bug in mds; please report it at ",
    env!("CARGO_PKG_REPOSITORY"),
    "/issues\n",
);

/// The exit code of a run that panicked, whatever else happened (#389) — Rust's own code
/// for a panic that ends `main`.
pub(crate) const PANIC_EXIT: i32 = 101;

/// The backtrace a panic prints after [`ICE_TEXT`], as `RUST_BACKTRACE` asks for it. Both
/// print the same frames, from the capture itself on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BacktraceStyle {
    /// Each frame's function and source line.
    Short,
    /// The same, with each frame's address (`RUST_BACKTRACE=full`).
    Full,
}

impl BacktraceStyle {
    /// The backtrace `RUST_BACKTRACE`'s `value` asks for, read as std reads it: none when
    /// it is unset or `0`, the frames with their addresses for `full`, the frames alone
    /// for any other value.
    fn from_env(value: Option<&OsStr>) -> Option<Self> {
        match value {
            None => None,
            Some(value) if value == OsStr::new("0") => None,
            Some(value) if value == OsStr::new("full") => Some(Self::Full),
            Some(_) => Some(Self::Short),
        }
    }
}

thread_local! {
    /// Whether this thread is running a [`catch_panic`] closure, which catches a panic
    /// that unwinds out of it.
    static CATCHING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    /// Whether this thread is unwinding from a panic the hook let unwind, and no
    /// [`catch_panic`] has caught yet.
    static UNWINDING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Install the CLI's panic hook, [`on_panic`] (#389). `main` calls it before anything
/// else. `RUST_BACKTRACE` is read here, once: the hook itself reads no environment.
pub(crate) fn install_panic_hook() {
    let backtrace = BacktraceStyle::from_env(std::env::var_os("RUST_BACKTRACE").as_deref());
    std::panic::set_hook(Box::new(move |info| on_panic(backtrace, info)));
}

/// The panic hook: what a panic on any thread does (#389).
///
/// 1. Record the panic: from here on [`final_exit_code`] is 101. This comes before
///    anything that can wait, so a run that ends while this thread is still in step 2 —
///    a helper thread's panic, say — still exits 101.
/// 2. One `write_all` of [`ICE_TEXT`] to stderr, its error ignored — a closed or failing
///    stderr loses the text and nothing else. Nothing the panic carries is formatted, so
///    no `Display` of the payload can run here, and std's stderr is a reentrant lock, so a
///    thread that panicked while writing to stderr takes it again. If another thread is
///    stuck inside a stderr write, this one waits with it.
/// 3. With `RUST_BACKTRACE` asking, [`write_backtrace`]. With the never-shipped
///    `debug-panics` feature, the panic's message and location.
/// 4. Let the panic unwind only to a [`catch_panic`] on this thread that is not already
///    unwinding from an earlier one. Otherwise end the process now, exit 101
///    ([`exit_after_panic`]): a panic on a thread that nothing catches — a watch helper
///    thread — would end that thread alone and leave the command running without it; and
///    a second panic while the thread unwinds from the first — a destructor that panics,
///    or the panic Rust raises where an unwind reaches a function that cannot unwind —
///    would make std abort the process after a message of its own.
///
/// It must not panic: std aborts a process whose panic hook panics, after printing the
/// second panic's location. `std::panic::always_abort`, with which a panic aborts without
/// calling any hook, is unstable, and the CLI never calls it; std sets it only in a child
/// between `fork` and `exec`, before the child is `mds` at all. A panic that cannot
/// unwind and follows no other — a check of undefined behaviour that a debug build
/// compiles in — looks to the hook like one that can: stable Rust does not say which it
/// is. Inside a [`catch_panic`] it prints the text, and then std aborts.
fn on_panic(backtrace: Option<BacktraceStyle>, info: &std::panic::PanicHookInfo<'_>) {
    OUTPUT_STATE.note_panicked();
    OUTPUT_STATE.cancel_clear();
    let mut stderr = std::io::stderr();
    let _ = stderr.write_all(ICE_TEXT.as_bytes());
    if let Some(style) = backtrace {
        write_backtrace(&mut stderr, style);
    }
    #[cfg(feature = "debug-panics")]
    write_panic_detail(&mut stderr, info);
    #[cfg(not(feature = "debug-panics"))]
    let _ = info;
    if !unwinds_to_a_catch() {
        exit_after_panic();
    }
}

/// Whether the panic being reported will unwind to a [`catch_panic`] on this thread:
/// the thread is inside one, and not already unwinding from an earlier panic. Marks the
/// thread as unwinding.
fn unwinds_to_a_catch() -> bool {
    let catching = CATCHING.with(std::cell::Cell::get);
    let already_unwinding = UNWINDING.with(|unwinding| unwinding.replace(true));
    catching && !already_unwinding
}

/// End the process after a panic that nothing will catch: exit 101 at once (#389). The
/// panicking thread cannot return to [`exit`], so the panic path has this way out of its
/// own.
fn exit_after_panic() -> ! {
    std::process::exit(PANIC_EXIT)
}

/// A panic that unwound out of a [`catch_panic`] closure. The hook has reported it.
#[derive(Debug)]
pub(crate) struct Panicked;

/// Run `f`, catching a panic that unwinds out of it — the one place the CLI catches a
/// panic (#389). The hook has already printed the text and recorded the panic, so the
/// run exits 101 whatever it does next; nothing here reports the panic again.
///
/// The panic's payload goes to [`dispose_payload`].
pub(crate) fn catch_panic<T>(
    f: impl FnOnce() -> T + std::panic::UnwindSafe,
) -> std::result::Result<T, Panicked> {
    let outer = CATCHING.with(|catching| catching.replace(true));
    let caught = std::panic::catch_unwind(f);
    CATCHING.with(|catching| catching.set(outer));
    caught.map_err(|payload| {
        dispose_payload(payload);
        UNWINDING.with(|unwinding| unwinding.set(false));
        Panicked
    })
}

/// Run one file's compile — `compile` — catching a panic in it, so a batch goes on
/// without that file: a directory run of `mds build`, `check`, `fmt` or `lint`, and every
/// compile of an `mds watch` session (#389).
///
/// The panic hook has printed the text and recorded the panic, so the run exits 101
/// whatever it does next. On `Err`, the caller counts the file as failed and prints
/// nothing more about it.
///
/// `compile` is the compile call alone. A panic abandons it part-way, so nothing in it
/// may write or delete a file or change state the batch goes on to use: what it
/// abandons is then only its own. The caller wraps it in `AssertUnwindSafe`, which says
/// just that; `tests/panic_hook.rs` pins every call site's closure to one compile call.
///
/// `label` is the file being compiled. A debug build's test trigger panics here when
/// `MDS_TEST_PANIC` is `compile:` followed by the label's file stem.
pub(crate) fn catch_compile<T>(
    label: &Path,
    compile: impl FnOnce() -> T + std::panic::UnwindSafe,
) -> std::result::Result<T, Panicked> {
    catch_panic(move || {
        panic_on_compile(label);
        compile()
    })
}

/// What [`dispose_payload`] did with a caught panic's payload.
#[derive(Debug, PartialEq, Eq)]
enum Disposal {
    /// Dropped: a panic message, whose destructor only frees its memory.
    Dropped,
    /// Forgotten: its destructor never runs, and the memory it holds is not freed.
    Forgotten,
}

/// Get rid of a caught panic's payload. The `String` or `&'static str` message a
/// `panic!` makes is dropped, which runs no code of the panic's own, so a watch session
/// that catches panics again and again does not hold on to their messages. Any other
/// payload is forgotten (`mem::forget`): its destructor is arbitrary code, and a panic
/// in it would be a panic outside any catch.
fn dispose_payload(payload: Box<dyn std::any::Any + Send>) -> Disposal {
    if payload.is::<String>() || payload.is::<&'static str>() {
        drop(payload);
        Disposal::Dropped
    } else {
        std::mem::forget(payload);
        Disposal::Forgotten
    }
}

/// Write the panicking thread's backtrace to `sink`, as `RUST_BACKTRACE` asked: a
/// `stack backtrace:` line, then the frames, each line WIRE-escaped with its line break
/// kept. A write that fails is ignored — stderr is where it would be reported.
fn write_backtrace<W: std::io::Write + ?Sized>(sink: &mut W, style: BacktraceStyle) {
    let backtrace = std::backtrace::Backtrace::force_capture();
    let mut text = String::from("stack backtrace:\n");
    // A frame that fails to render ends the text where it failed.
    let _ = match style {
        BacktraceStyle::Short => std::fmt::Write::write_fmt(&mut text, format_args!("{backtrace}")),
        BacktraceStyle::Full => {
            std::fmt::Write::write_fmt(&mut text, format_args!("{backtrace:#}"))
        }
    };
    let _ = sink.write_all(escape_each_line(&text).as_bytes());
}

/// `text` with each line WIRE-escaped on its own and ended by a line break, so a line
/// keeps its break and gains no raw control character.
fn escape_each_line(text: &str) -> String {
    let mut escaped = String::with_capacity(text.len());
    for line in text.split_terminator('\n') {
        escaped.push_str(&mds::sanitize_control_chars_wire(line));
        escaped.push('\n');
    }
    escaped
}

/// The panic's message and location, escaped as a backtrace line is — only in a build
/// with the never-shipped `debug-panics` feature (#389).
#[cfg(feature = "debug-panics")]
fn write_panic_detail<W: std::io::Write + ?Sized>(
    sink: &mut W,
    info: &std::panic::PanicHookInfo<'_>,
) {
    let payload = info.payload();
    let message = payload
        .downcast_ref::<&str>()
        .copied()
        .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
        .unwrap_or("(a panic payload that is not text)");
    let mut text = String::new();
    let _ = std::fmt::Write::write_fmt(&mut text, format_args!("panic: {message}\n"));
    if let Some(location) = info.location() {
        let _ = std::fmt::Write::write_fmt(&mut text, format_args!("  at {location}\n"));
    }
    let _ = sink.write_all(escape_each_line(&text).as_bytes());
}

// ── Test-only panic trigger (#389) ───────────────────────────────────────────

/// `MDS_TEST_PANIC`: how a debug build is made to panic on purpose, for the tests of the
/// panic hook (`tests/panic_hook.rs`). A release build has none of it.
#[cfg(debug_assertions)]
mod panic_trigger {
    use std::path::Path;

    /// The variable that asks for a panic, and where:
    /// - `main`: in the command's dispatch;
    /// - `thread`: in a thread the dispatch starts and waits for;
    /// - `compile:<stem>`: in [`catch_compile`](super::catch_compile), compiling a file
    ///   whose file stem is `<stem>`;
    /// - `notify` / `ctrlc`: in `mds watch`'s file-event callback / Ctrl-C handler, each
    ///   on a thread of its own.
    const VARIABLE: &str = "MDS_TEST_PANIC";

    /// A word the payload carries, for a test to look for.
    pub(super) const SENTINEL: &str = "mds-test-panic-payload";

    /// What `MDS_TEST_PANIC` asks for, when it is set to text.
    fn requested() -> Option<String> {
        std::env::var_os(VARIABLE).and_then(|value| value.into_string().ok())
    }

    /// Panic as `MDS_TEST_PANIC` asks, if it asks for `main` or `thread`. The dispatch
    /// calls it first.
    pub(crate) fn panic_on_request() {
        match requested().as_deref() {
            Some("main") => std::panic::panic_any(payload()),
            Some("thread") => {
                // A thread's panic that does not end the process leaves the dispatch to
                // carry on as if nothing had happened — what a test must be able to see.
                let _ = std::thread::spawn(|| std::panic::panic_any(payload())).join();
            }
            _ => {}
        }
    }

    /// Panic when `MDS_TEST_PANIC` is `compile:` followed by `label`'s file stem.
    /// [`catch_compile`](super::catch_compile) calls it inside its catch.
    pub(crate) fn panic_on_compile(label: &Path) {
        let Some(stem) = label.file_stem().and_then(std::ffi::OsStr::to_str) else {
            return;
        };
        if requested()
            .as_deref()
            .and_then(|value| value.strip_prefix("compile:"))
            == Some(stem)
        {
            std::panic::panic_any(payload());
        }
    }

    /// Panic when `MDS_TEST_PANIC` is `handler`, the name of the handler that calls it:
    /// `notify` or `ctrlc`.
    pub(crate) fn panic_in_handler(handler: &str) {
        if requested().as_deref() == Some(handler) {
            std::panic::panic_any(payload());
        }
    }

    /// A payload no panic output may show: the sentinel, a raw ESC and the absolute path
    /// of the working directory.
    pub(super) fn payload() -> String {
        let esc = char::from(0x1b);
        let here = std::env::current_dir().unwrap_or_else(|_| std::env::temp_dir());
        format!("{SENTINEL} {esc}[2J {}", here.display())
    }
}

#[cfg(debug_assertions)]
use panic_trigger::panic_on_compile;
#[cfg(debug_assertions)]
pub(crate) use panic_trigger::{panic_in_handler, panic_on_request};

/// A release build's `MDS_TEST_PANIC` trigger in the dispatch: nothing (#389).
#[cfg(not(debug_assertions))]
pub(crate) fn panic_on_request() {}

/// A release build's `MDS_TEST_PANIC` trigger in [`catch_compile`]: nothing (#389).
#[cfg(not(debug_assertions))]
fn panic_on_compile(_label: &Path) {}

/// A release build's `MDS_TEST_PANIC` trigger in a watch handler: nothing (#389).
#[cfg(not(debug_assertions))]
pub(crate) fn panic_in_handler(_handler: &str) {}

// ── Stdin display sentinel ────────────────────────────────────────────────────

/// AD-211-1 / AD-211-3: the single stdin source-identity sentinel used by every
/// CLI diagnostic context.
///
/// Every user-visible emission of stdin's source identity — human diagnostics, JSON
/// `files[].file`, fix-preview status lines, diff headers, source-map `sources[]`,
/// and the analysis-failure envelope — uses this exact string.  The remap is applied
/// at the CLI output boundary; `crates/mds-core` continues to carry `"input.mds"`
/// (STRING_SOURCE_MAP_LABEL) as the internal VFS entry key, which is NOT changed.
///
/// Centralised here so the CLI has exactly one definition of the sentinel (AD-211-3),
/// replacing the previously scattered literals — including the hardcoded `"<stdin>"`
/// in `apply_source_map_file_label`, the `OK: <stdin>` status line in `main.rs`, and
/// the `fmt` stdin label.
pub(crate) const STDIN_DISPLAY_LABEL: &str = "<stdin>";

// ── Stdin source-identity relabel (AD-211-5) ─────────────────────────────────

/// Render-boundary wrapper that replaces the source identity embedded in an
/// [`mds::MdsError`] with [`STDIN_DISPLAY_LABEL`].
///
/// `resolve_source_intrinsic` sets `ctx.file_str = "<source>"`, so every error a
/// string-source (stdin) analysis produces carries `NamedSource::new("<source>", …)`
/// and renders as `<source>:L:C`. Replacing it here — not in `crates/mds-core` —
/// keeps the core constant intact for the non-stdin paths that legitimately use it
/// (`resolver_tests.rs` locks `SOURCE_LABEL`) and matches the "relabel at the CLI
/// output boundary" discipline of AD-211-1.
///
/// It also matches PF-014: the swap happens on the miette **input** (the
/// `NamedSource` handed to the renderer), never on already-rendered output.
///
/// Delegates every `Diagnostic` method to `inner` except `source_code`, which
/// returns the pre-built replacement (or `None` when the inner error carried no
/// embedded source, so miette skips code-frame rendering rather than trying to
/// resolve spans against a source that is not there).
///
/// # Exit codes
///
/// This type is transparent to [`crate::build::exit_code`], which unwraps it before
/// classifying the error. A wrapped `MdsError::FileNotFound` must still exit 2, not
/// 1 — see the downcast ladder there.
pub(crate) struct StdinRelabeledError {
    inner: mds::MdsError,
    /// `Some(named)` when the inner error's embedded source is the stdin sentinel
    /// `"<source>"` — replaced with a `NamedSource` labelled `"<stdin>"`.
    ///
    /// `None` in two cases:
    /// - The inner error had no embedded source at all (e.g. `MdsError::Io`).
    /// - The inner error's embedded source belongs to an **imported file** — its
    ///   real path must be preserved so miette renders the caret at the correct
    ///   location.  `source_code()` delegates to `inner` in both sub-cases.
    source: Option<miette::NamedSource<String>>,
}

impl StdinRelabeledError {
    /// The error this wrapper renders. Used by `exit_code` so wrapping cannot
    /// change a process exit status.
    pub(crate) fn inner(&self) -> &mds::MdsError {
        &self.inner
    }
}

impl std::fmt::Display for StdinRelabeledError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self.inner, f)
    }
}

impl std::fmt::Debug for StdinRelabeledError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(&self.inner, f)
    }
}

impl std::error::Error for StdinRelabeledError {}

impl miette::Diagnostic for StdinRelabeledError {
    fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
        miette::Diagnostic::code(&self.inner)
    }
    fn severity(&self) -> Option<miette::Severity> {
        miette::Diagnostic::severity(&self.inner)
    }
    fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
        miette::Diagnostic::help(&self.inner)
    }
    fn url<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
        miette::Diagnostic::url(&self.inner)
    }
    fn labels<'a>(&'a self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + 'a>> {
        miette::Diagnostic::labels(&self.inner)
    }
    fn source_code(&self) -> Option<&dyn miette::SourceCode> {
        match &self.source {
            Some(ns) => Some(ns as &dyn miette::SourceCode),
            // When `source` is None the relabel decided NOT to replace: either the
            // inner error carries no source at all (MdsError::Io) or it carries a
            // real imported-file source that must be preserved intact.  Delegate so
            // miette still renders the imported-file code frame correctly.
            None => miette::Diagnostic::source_code(&self.inner),
        }
    }
    fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn miette::Diagnostic> + 'a>> {
        miette::Diagnostic::related(&self.inner)
    }
    fn diagnostic_source(&self) -> Option<&dyn miette::Diagnostic> {
        miette::Diagnostic::diagnostic_source(&self.inner)
    }
}

/// AD-211-5: build a report whose embedded source identity reads
/// [`STDIN_DISPLAY_LABEL`] instead of the core's `"<source>"`.
///
/// This is a **conditional** label swap: the replacement only happens when the
/// inner error's embedded `NamedSource` carries the stdin sentinel `"<source>"`
/// set by `resolve_source_intrinsic`.  Errors whose embedded source belongs to an
/// **imported file** carry the real file path and are left untouched — replacing
/// them would render the caret against stdin text at the wrong location, which is
/// exactly the PF-012 in-bounds-but-wrong class this PR set out to avoid.
/// AD-211-5 only authorised relabelling stdin's OWN source identity.
///
/// The source text used for span rendering, the message, the code, the help and
/// the labels are all untouched.  `miette`'s own
/// [`miette::Report::with_source_code`] cannot do this: its `WithSourceCode`
/// wrapper returns `self.error.source_code().or(Some(&self.source_code))`, so an
/// inner diagnostic that already carries a `NamedSource` (which these do) wins
/// and the replacement is ignored.
///
/// Call sites (symbolic references; prefer these over line numbers to avoid stale citations):
/// - `mds check -`: `run_check` in `crates/mds-cli/src/main.rs`
/// - `mds build -` (single-file path): `compile_to_content` in `crates/mds-cli/src/build.rs`
/// - `mds build -` (directory stdin path): `run_build` in `crates/mds-cli/src/build.rs`
/// - `mds lint -`: the human result sink's `analysis_failed` in
///   `crates/mds-cli/src/lint_sink.rs`, for every failure of a stdin run
///
/// Any new CLI boundary that renders a stdin analysis failure must call this
/// function; skipping it renders `<source>` and breaks the uniform-sentinel rule.
pub(crate) fn relabel_stdin_error(e: &mds::MdsError, source: &str) -> miette::Report {
    // Only replace the embedded source when the inner error's source name is the
    // stdin sentinel set by `resolve_source_intrinsic` — checked via
    // `e.is_string_source()`, which keeps the sentinel comparison inside mds-core.
    // Errors from imported files carry the real file path; replacing them would
    // render the caret against stdin text at the wrong location (PF-012 / AD-211-5 scope).
    miette::Report::new(StdinRelabeledError {
        source: if e.is_string_source() {
            miette::Diagnostic::source_code(e)
                .map(|_| mds::named_source_for_render(STDIN_DISPLAY_LABEL, source))
        } else {
            None
        },
        inner: e.clone(),
    })
}

// ── Working directory (#390) ──────────────────────────────────────────────────

/// The working directory, which a path typed relative to it resolves against (#390).
///
/// Fails closed: a working directory that cannot be determined — deleted while the
/// process is in it, say — is `mds::io` (exit 2), `cannot determine current directory:
/// <reason>`, never a fallback to `"."`, which would name whatever directory the process
/// is left in rather than the one the path was typed against. The words are mds-core's
/// for a string compile that needs the working directory (its private
/// `current_dir_base`), so a relative output location and a stdin source that meet the
/// same failure read the same.
pub(crate) fn current_dir() -> std::result::Result<PathBuf, mds::MdsError> {
    std::env::current_dir().map_err(|e| mds::MdsError::Io {
        message: format!(
            "cannot determine current directory: {}",
            safe_inline(io_cause(&e))
        ),
    })
}

// ── Output-location validation (#265) ─────────────────────────────────────────

/// Refuse an output location that carries a forbidden path character (#265):
/// `mds::io`, exit 2.
///
/// `what` names the setting (`-o/--output`, `--out-dir`, `mds.json build.output_dir`).
/// Callers run this UP FRONT — before any input is read or compiled — so a hostile
/// output location never reaches path derivation, `create_dir_all` or the write
/// guard. The message names the codepoint as `U+XXXX` and shows the value escaped
/// by [`mds::escape_path_for_message`], so it carries none of the 80 codepoints.
///
/// `ensure_existing_mds_file` also runs it on a single-file argument (`what` =
/// `path`), before that file's existence check.
///
/// A value that is not valid UTF-8 is scanned lossily: every forbidden codepoint
/// that is validly encoded survives the conversion. The scan and the message are
/// [`mds::reject_forbidden_path`]'s, so the CLI refuses a path in mds-core's words.
pub(crate) fn reject_forbidden_output_path(
    what: &str,
    value: &OsStr,
) -> std::result::Result<(), mds::MdsError> {
    mds::reject_forbidden_path(what, Path::new(value), &value.to_string_lossy())
}

/// Refuse an output location that is not valid UTF-8 (#390): `mds::io`, exit 2,
/// `<what> is not valid UTF-8: "<value>"`, the value shown with U+FFFD for each invalid
/// sequence and escaped by [`mds::escape_path_for_message`]. Otherwise the value, as
/// text.
///
/// Every status line and comparison would name such a location by its lossy form, which
/// is a different path. Callers run it up front, after
/// [`reject_forbidden_output_path`], so it is never created or written.
pub(crate) fn reject_non_utf8_output_path<'a>(
    what: &str,
    value: &'a OsStr,
) -> std::result::Result<&'a str, mds::MdsError> {
    value.to_str().ok_or_else(|| mds::MdsError::Io {
        message: format!(
            "{what} is not valid UTF-8: \"{}\"",
            mds::escape_path_for_message(&value.to_string_lossy())
        ),
    })
}

/// Refuse an output location whose RESOLVED form carries a forbidden path character
/// (#265): `mds::io`, exit 2.
///
/// [`reject_forbidden_output_path`] checks the value as typed; this checks where it
/// leads. A symlinked directory in it — or, for a relative value, the working
/// directory above it — can resolve into a hostile-named directory the value never
/// names. The location need not exist yet (it is created on the first write): its
/// deepest existing ancestor is canonicalized — the components below that are the
/// typed ones, already checked — and the whole resolved form is scanned. Callers run
/// it up front beside the typed check, so a refused location is never created or
/// written, and no later status line can show it.
///
/// The message, `<what> resolved path contains forbidden character U+XXXX: "<typed>"`,
/// names `typed`, the value as typed, escaped by [`mds::escape_path_for_message`] —
/// never the absolute resolved path. The scan and the message are
/// [`mds::reject_forbidden_path`]'s.
///
/// A relative value is resolved against the working directory, so one that cannot be
/// determined refuses it too, in [`current_dir`]'s words (#390): there is no directory
/// the value names.
pub(crate) fn reject_forbidden_resolved_output_path(
    what: &str,
    path: &Path,
    typed: &OsStr,
) -> std::result::Result<(), mds::MdsError> {
    let Some(resolved) = resolve_existing_prefix(path)? else {
        return Ok(());
    };
    mds::reject_forbidden_path(
        &format!("{what} resolved path"),
        &resolved,
        &typed.to_string_lossy(),
    )
}

/// The canonical form of the deepest existing ancestor of `path` (`path` itself when
/// it exists); a relative `path` is taken against the working directory, which must
/// exist ([`current_dir`]).
///
/// `None` when no ancestor resolves, so there is nothing on disk the value could lead
/// through and the typed check stands alone.
fn resolve_existing_prefix(path: &Path) -> std::result::Result<Option<PathBuf>, mds::MdsError> {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        current_dir()?.join(path)
    };
    // Bounded: one step per component of `absolute`.
    Ok(absolute.ancestors().find_map(|a| a.canonicalize().ok()))
}

/// Refuse an `mds.json` `build.output_dir` that leaves the directory `mds.json` is in: an
/// absolute one — a root or a drive prefix — or one with a `..` component. `mds::io`,
/// exit 2, naming the value as written.
///
/// The value is the repository's, not a path the user typed, so it may only name a
/// directory below `mds.json`'s own, which is where its writes are anchored (#160). The
/// raw components are checked rather than a canonical form because the directory may not
/// exist yet (it is created on the first write). Shared by the single-file
/// (`resolve_output_path_for_kind`) and directory ([`resolve_output_base`]) resolvers so
/// both refuse it identically.
pub(crate) fn reject_output_dir_escape(output_dir: &str) -> std::result::Result<(), mds::MdsError> {
    use std::path::Component;

    let mut components = Path::new(output_dir).components();
    if components
        .clone()
        .any(|c| matches!(c, Component::RootDir | Component::Prefix(_)))
    {
        return Err(mds::MdsError::Io {
            message: format!(
                "mds.json output_dir '{}' must be a relative path",
                mds::escape_path_for_message(output_dir)
            ),
        });
    }
    if components.any(|c| c == Component::ParentDir) {
        return Err(mds::MdsError::Io {
            message: format!(
                "mds.json output_dir '{}' must not contain '..' components",
                mds::escape_path_for_message(output_dir)
            ),
        });
    }
    Ok(())
}

// ── Output base for directory mode ────────────────────────────────────────────

/// Describes where directory-mode output files are written.
///
/// `Dir` mirrors the source subtree under a directory:
///   `source.strip_prefix(root)` → `<dir>/rel/stem.<ext>`
/// `NextToSource` places the output next to the source file.
#[derive(Debug, Clone)]
pub(crate) enum OutputBase {
    /// The directory, in the two forms [`resolve_output_base`] fixes once (#390).
    Dir {
        /// Absolute, canonical where it exists: where outputs are written, and what every
        /// containment check (`starts_with`) compares.
        canonical: PathBuf,
        /// The same directory as the user named it: `--out-dir` as typed, or `mds.json`
        /// `build.output_dir` below the directory `mds.json` was reached by. The form a
        /// status line names an output by.
        shown: PathBuf,
        /// How many of the directory's own last components lie below the anchor its
        /// writes are made below (#160): none for `--out-dir`, which is its own anchor,
        /// resolved when the run starts; `build.output_dir`'s, below the directory
        /// `mds.json` is in, so a symlink there is refused like any other below an anchor.
        below_anchor: usize,
    },
    NextToSource,
}

/// One file the CLI writes, in the two forms fixed where its location is resolved —
/// [`output_path_for`] in directory mode, `resolve_output_path_for_kind` for a single
/// file (#390) — and the anchor its write resolves by path (#160).
///
/// `path` is where the bytes go. `shown` is the same file as the user named it: the path
/// as typed, or the part below a directory they named — the directory argument,
/// `--out-dir`, or the directory `mds.json` was reached by — joined to that directory as
/// typed. A status line, a message the caller writes itself, and the error
/// [`crate::write::write_compiled`] raises writing it name the file by `shown` alone,
/// so display never resolves a path again.
///
/// The last `below_anchor` components of `path` — and of `shown`, which ends in the same
/// names — lie below the write's anchor: the parent of a file argument or of `-o`,
/// `--out-dir`, a directory argument's root, or, for `mds.json`'s `build.output_dir`, the
/// directory `mds.json` is in, with `build.output_dir`'s own directories below it. The
/// write resolves the anchor by path, in the form `path` holds it — as typed, or as
/// resolved once when the run started: a directory-mode `--out-dir` ([`OutputBase::Dir`]'s
/// `canonical`) and the entry's directory or directory argument of `mds watch` — and
/// refuses a symlink at any of the components below it instead of writing through it.
/// A write `mds watch` makes below its out-dir also names the directory its anchor must
/// be ([`WriteTarget::below_checked_anchor`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct WriteTarget {
    pub(crate) path: PathBuf,
    pub(crate) shown: PathBuf,
    below_anchor: usize,
    /// The directory the write must find its anchor to be, when its caller has just
    /// checked which one that is; `None`: whatever directory the anchor's path leads to.
    checked_anchor: Option<DirIdentity>,
}

impl WriteTarget {
    /// A file named exactly as it is written: a path the user typed, or one built from a
    /// typed path alone, so its two forms are one. Its anchor is its own directory.
    pub(crate) fn as_typed(path: PathBuf) -> Self {
        Self::new(path.clone(), path)
    }

    /// A file written at `path` and named as `shown`, anchored at the directory it is in:
    /// the typed parent of a file argument, of `-o`, or of a file-mode output's directory.
    pub(crate) fn new(path: PathBuf, shown: PathBuf) -> Self {
        Self {
            path,
            shown,
            below_anchor: 1,
            checked_anchor: None,
        }
    }

    /// The file `rel` below the anchor `anchor`, named below `shown_anchor`, the same
    /// directory as the user named it: a directory-mode output below `--out-dir` or the
    /// directory argument, or a directory's entry its walk found. `rel` is relative; the
    /// write refuses a `..` in it.
    pub(crate) fn below(anchor: &Path, shown_anchor: &Path, rel: &Path) -> Self {
        Self {
            path: anchor.join(rel),
            shown: shown_anchor.join(rel),
            // `components` keeps a `.` only at the start, which a join drops.
            below_anchor: rel
                .components()
                .filter(|c| *c != std::path::Component::CurDir)
                .count(),
            checked_anchor: None,
        }
    }

    /// The file `rel` below a directory-mode out-dir, `dir` in its two forms, whose own last
    /// `dir_below_anchor` components lie below the anchor too — none for `--out-dir`,
    /// `build.output_dir`'s below the directory `mds.json` is in ([`OutputBase::Dir`]).
    pub(crate) fn below_out_dir(
        dir: &Path,
        shown_dir: &Path,
        dir_below_anchor: usize,
        rel: &Path,
    ) -> Self {
        let mut target = Self::below(dir, shown_dir, rel);
        target.below_anchor += dir_below_anchor;
        target
    }

    /// `file`, a path the walk of `root.walked` found, below that root as its anchor and
    /// named below `root.typed`. A file not below the walked root has no typed form and is
    /// anchored at its own directory.
    pub(crate) fn walked_below(root: RootPaths<'_>, file: &Path) -> Self {
        match file.strip_prefix(root.walked) {
            Ok(rel) => Self::below(root.walked, root.typed, rel),
            Err(_) => Self::as_typed(file.to_path_buf()),
        }
    }

    /// How many of the last components of `path` lie below the anchor.
    pub(crate) fn below_anchor(&self) -> usize {
        self.below_anchor
    }

    /// The same file below `dir`, the directory its anchor is as its caller resolved and
    /// checked it — `mds watch`'s out-dir, or the directory `mds.json` is in — written only
    /// if the directory the write opens as its anchor is `identity` (#160). The last
    /// `missing` components of `dir`, which were not there when it was checked, lie below
    /// the anchor too: the write opens the directory above them, the one checked, and
    /// creates them below it without following a symlink. Named as before.
    pub(crate) fn below_checked_anchor(
        &self,
        dir: &Path,
        missing: usize,
        identity: DirIdentity,
    ) -> Self {
        let above = self
            .path
            .components()
            .count()
            .saturating_sub(self.below_anchor);
        Self {
            path: dir.join(self.path.components().skip(above).collect::<PathBuf>()),
            shown: self.shown.clone(),
            below_anchor: self.below_anchor + missing,
            checked_anchor: Some(identity),
        }
    }

    /// The directory the write must find its anchor to be, if its caller checked it.
    pub(crate) fn checked_anchor(&self) -> Option<DirIdentity> {
        self.checked_anchor
    }

    /// The file `edit` derives from this one, in both forms and below the same anchor —
    /// the sidecar map beside an output, say. `edit` changes the file name alone.
    pub(crate) fn sibling(&self, edit: impl Fn(&Path) -> PathBuf) -> Self {
        Self {
            path: edit(&self.path),
            shown: edit(&self.shown),
            below_anchor: self.below_anchor,
            checked_anchor: self.checked_anchor,
        }
    }
}

/// A directory-mode root in the two forms its sources are walked in and named by, always
/// in `(typed, walked)` order, so the two cannot be passed swapped (#390).
///
/// `walked` is the form the sources below it are walked in — what [`output_path_for`]
/// strips a source against. `typed` is the directory argument as typed: an output next to
/// its source is named below it. `mds build` walks the directory as typed and passes it as
/// both; `mds watch` walks its canonical form, which matches the event paths notify
/// reports, and holds the entry's directory and the `--vars` file's in the same two forms
/// to name a directory it watches.
#[derive(Debug, Clone, Copy)]
pub(crate) struct RootPaths<'a> {
    pub(crate) typed: &'a Path,
    pub(crate) walked: &'a Path,
}

impl<'a> RootPaths<'a> {
    /// A root walked as typed: its two forms are one.
    pub(crate) fn as_typed(dir: &'a Path) -> Self {
        Self {
            typed: dir,
            walked: dir,
        }
    }

    /// `source`, a path the walk of `walked` produced, named below `typed`. A source not
    /// below `walked` has no typed form and keeps its own.
    pub(crate) fn shown_below(self, source: &Path) -> PathBuf {
        self.typed_below(source)
            .unwrap_or_else(|| source.to_path_buf())
    }

    /// `path` named below `typed` — `walked` itself as `typed`, with no separator added —
    /// or `None` when `path` is not `walked` or below it.
    pub(crate) fn typed_below(self, path: &Path) -> Option<PathBuf> {
        let below = path.strip_prefix(self.walked).ok()?;
        Some(if below.as_os_str().is_empty() {
            self.typed.to_path_buf()
        } else {
            self.typed.join(below)
        })
    }
}

/// Resolve `out_dir` to an absolute, canonicalized path for reliable `starts_with` checks.
///
/// [`resolve_output_base`] calls it for the `--out-dir` of `run_build_directory` and of
/// a directory watch's startup (`dir_startup::arm_pre_read`). A relative path is resolved
/// against the working directory; the result is then canonicalized (falls back to the
/// absolute form when the directory does not yet exist).
///
/// # Errors
///
/// A relative `out_dir` when the working directory cannot be determined: `mds::io`, in
/// [`current_dir`]'s words (#390). It is never anchored at `"."` instead, which would
/// leave a relative base that every `starts_with` check downstream misreads.
pub(crate) fn canonicalize_out_dir(
    out_dir: Option<&PathBuf>,
) -> std::result::Result<Option<PathBuf>, mds::MdsError> {
    let Some(d) = out_dir else {
        return Ok(None);
    };
    let abs = if d.is_absolute() {
        d.clone()
    } else {
        current_dir()?.join(d)
    };
    Ok(Some(abs.canonicalize().unwrap_or(abs)))
}

/// Compute the `OutputBase` for directory mode, fixing both forms of its directory here,
/// once (#390).
///
/// Precedence (mirrors `resolve_output_path_for_kind` for file mode):
/// 1. `--out-dir` → `Dir`: canonical per [`canonicalize_out_dir`], shown as typed; the
///    anchor of its writes.
/// 2. `mds.json build.output_dir` → `Dir`: below the config directory, the anchor of its
///    writes, shown below the directory `mds.json` was reached by — refuses an absolute
///    value and `..` components at startup (`mds::io`, exit 2).
/// 3. Default → `NextToSource`
///
/// # Errors
///
/// A relative `--out-dir` when the working directory cannot be determined
/// ([`canonicalize_out_dir`]), and a `build.output_dir` that is absolute or has a `..`
/// component ([`reject_output_dir_escape`]).
pub(crate) fn resolve_output_base(
    out_dir: Option<&PathBuf>,
    config: &Option<ProjectConfig>,
) -> Result<OutputBase> {
    if let (Some(typed), Some(canonical)) = (out_dir, canonicalize_out_dir(out_dir)?) {
        return Ok(OutputBase::Dir {
            canonical,
            shown: typed.clone(),
            below_anchor: 0,
        });
    }
    if let Some(ProjectConfig {
        config,
        dir,
        shown_dir,
    }) = config
    {
        if let Some(ref output_dir) = config.build.output_dir {
            reject_output_dir_escape(output_dir)?;
            return Ok(OutputBase::Dir {
                canonical: dir.join(output_dir),
                shown: shown_dir.join(output_dir),
                // Names alone, once the refusal above has run; a `.` adds none.
                below_anchor: Path::new(output_dir)
                    .components()
                    .filter(|c| matches!(c, std::path::Component::Normal(_)))
                    .count(),
            });
        }
    }
    Ok(OutputBase::NextToSource)
}

/// Compute the mirrored output path for a source file in directory mode.
///
/// Infallible — no directory creation.
///
/// Defined in terms of [`mirror_stem`] so the strip_prefix path-escape logic is kept in
/// one place, shared with [`output_base_no_ext`].
///
/// - `Dir`: mirrors `source` relative to `root.walked` under the directory — its
///   canonical form for the write, its shown form for the message (#390).
///   If `strip_prefix` fails (source not under root after canonicalization),
///   falls back to `<dir>/stem.<ext>` — **never** joins an absolute path that
///   could escape the output directory (the path-escape guard).
/// - `NextToSource`: `source.with_extension(ext)` beside the source as walked, named
///   below the directory argument as typed ([`output_stem_for`], #390).
///
/// The `ext` parameter is the output extension without leading `.` (`"md"` or `"json"`).
///
/// # This is the WRITE oracle
///
/// It is called once per output path actually computed for a write, so it is where the
/// [`MirroredStem::Flattened`] arm is reported — a warning naming the source, the root
/// and the flat output. [`output_base_no_ext`] computes the same stem for bookkeeping —
/// a directory build's source-map base — and stays silent; moving the report there would
/// fire it for a stem no write is made at (#217).
///
/// No live caller can reach the flattened arm: `build` walks `root` and hands the walk's
/// own prefix back here; `watch` gates event paths on `starts_with(&ctx.root)` and its
/// startup/baseline loops use canonical keys under a canonical root whose walker skips
/// symlinks. The warning is therefore an invariant report, not a user-facing condition —
/// if it is ever seen, one of those gates has moved.
pub(crate) fn output_path_for(
    source: &Path,
    root: RootPaths<'_>,
    base: &OutputBase,
    ext: &str,
) -> WriteTarget {
    match base {
        OutputBase::Dir {
            canonical,
            shown,
            below_anchor,
        } => {
            let (rel, flattened) = mirrored_output(source, root.walked, ext);
            let target = WriteTarget::below_out_dir(canonical, shown, *below_anchor, &rel);
            if flattened {
                // Invariant report, not gated on --quiet (like the walker's depth-limit
                // warning). Emitted once per output-path computation:
                // build — once per file, since its `output_base_no_ext` probes are silent;
                // watch — once per rebuild (#217).
                eprint_warning(&format!(
                    "warning: {} is outside the build root {}; its output is written flat \
                     as {} (another source outside the root with the same file name would \
                     overwrite it)",
                    safe_path(source),
                    safe_path(root.walked),
                    safe_path(&target.shown)
                ));
            }
            target
        }
        OutputBase::NextToSource => {
            output_stem_for(source, root, base).sibling(|stem| stem.with_extension(ext))
        }
    }
}

/// `source`'s output below the out-dir — the part below it, mirrored as [`mirror_stem`]
/// mirrors it — and whether the mirror was flattened. [`output_path_for`] joins it to both
/// forms of the out-dir, so both name the same file below it. A mirror that is not below
/// the out-dir is replaced by its flat name ([`flat_output`]), flagged flattened.
fn mirrored_output(source: &Path, root: &Path, ext: &str) -> (PathBuf, bool) {
    let mirrored = mirror_stem(source, root);
    let flattened = matches!(mirrored, MirroredStem::Flattened(_));
    let no_ext = mirrored.into_path();
    // Invariant: `no_ext` was built by `mirror_stem` as `[<dirs>/]<stem>`, so
    // `file_name()` is `Some`. The literal fallback exists because the previous
    // one — `source.as_os_str()` — could be absolute, and an absolute name makes
    // a join re-root out of the out-dir.
    let mut name = no_ext
        .file_name()
        .unwrap_or_else(|| OsStr::new("output"))
        .to_os_string();
    name.push(".");
    name.push(ext);
    let out = no_ext.parent().unwrap_or(Path::new("")).join(&name);
    // Containment invariant: the output path must remain inside the out-dir, so the part
    // below it is names alone. `mirror_stem` already guards the strip_prefix escape case
    // by returning a bare `<stem>` for out-of-root sources; the with-extension step cannot
    // escape. The check here is a defence-in-depth assertion, and the assertion stays
    // DEBUG-ONLY on purpose: a release build does not stop. It falls back to the flat
    // name, which is contained, and reports it as flattened, so `output_path_for` warns;
    // the write also refuses a `..` below its anchor whatever reaches it (#160).
    if out
        .components()
        .all(|c| matches!(c, std::path::Component::Normal(_)))
    {
        return (out, flattened);
    }
    debug_assert!(
        false,
        "output_path_for: output {out:?} is not below the out-dir"
    );
    flat_output(source, ext)
}

/// The flat output name for `source`, `<stem>.<ext>`, and the flag that it is flattened:
/// the fallback of [`mirrored_output`] for a mirror that is not below the out-dir. The
/// caller reports it, as it reports a source outside the root (#217).
fn flat_output(source: &Path, ext: &str) -> (PathBuf, bool) {
    // Invariant: same as in `mirror_stem` — the name must be relative.
    let mut flat_name = source
        .file_stem()
        .unwrap_or_else(|| OsStr::new("output"))
        .to_os_string();
    flat_name.push(".");
    flat_name.push(ext);
    (PathBuf::from(flat_name), true)
}

// ── Directory traversal ───────────────────────────────────────────────────────

/// Result of a directory walk, carrying both the collected files and a count
/// of `.mds` files that were skipped because they reside inside
/// default-excluded directories (hidden dirs, `node_modules`).
///
/// A non-zero `excluded_by_default` with an empty `files` list means every
/// candidate was filtered out by the default exclusions — distinguishable from
/// a genuinely empty tree (where both are zero).
pub(crate) struct WalkResult {
    /// Files that were collected and are eligible for processing.
    pub files: Vec<PathBuf>,
    /// No-follow metadata from the walk for each collected file.
    metadata: std::collections::HashMap<PathBuf, std::fs::Metadata>,
    /// Count of `.mds` files found inside default-excluded directories.
    pub excluded_by_default: usize,
}

/// Recursively collect all `.mds` files under `root`, bounded by `max_depth`,
/// returning a [`WalkResult`] that also carries the count of files skipped due
/// to default exclusions (hidden dirs, `node_modules`).
///
/// Use this at call sites that need to distinguish "genuinely empty tree" from
/// "all candidates excluded". Use [`collect_mds_files`] at call sites (e.g.
/// watch) that only need the file list.
pub(crate) fn collect_mds_files_detailed(
    root: &Path,
    max_depth: usize,
    exclude_prefix: Option<&Path>,
) -> WalkResult {
    let mut walk = WalkResult {
        files: Vec::new(),
        metadata: std::collections::HashMap::new(),
        excluded_by_default: 0,
    };
    collect_mds_files_inner(root, 0, max_depth, exclude_prefix, &mut walk);
    pause_after_walk();
    walk
}

/// Pin a collected file to its walk-time location and no-follow metadata.
/// The file and typed root must come from the same walk.
pub(crate) fn walked_pin(
    walk: &WalkResult,
    file: &Path,
    typed_dir: &Path,
    canonical_dir: &Path,
) -> std::result::Result<mds::EntryPin, mds::MdsError> {
    let invalid = || mds::MdsError::Io {
        message: format!(
            "cannot read {}: missing or invalid walk metadata",
            safe_path(file)
        ),
    };
    let relative = file.strip_prefix(typed_dir).map_err(|_| invalid())?;
    let metadata = walk.metadata.get(file).ok_or_else(invalid)?;
    Ok(mds::EntryPin::key(canonical_dir.join(relative)).with_walked(metadata))
}

#[cfg(debug_assertions)]
mod walk_pause_trigger {
    use super::*;
    use crate::write::{atomic_write_file, Durability, Parents};

    const VARIABLE: &str = "MDS_TEST_PAUSE_AFTER_WALK";
    const POLL: std::time::Duration = std::time::Duration::from_millis(5);
    const MAX_POLLS: u32 = 2_000;

    pub(crate) fn pause_after_walk() {
        let Some(go) = std::env::var_os(VARIABLE).map(PathBuf::from) else {
            return;
        };
        let mut paused = go.clone().into_os_string();
        paused.push(".paused");
        // If the marker fails, the test reports that the walk did not pause.
        if atomic_write_file(
            &WriteTarget::as_typed(PathBuf::from(paused)),
            "",
            Durability::RenameOnly,
            Parents::Existing,
        )
        .is_err()
        {
            return;
        }
        for _ in 0..MAX_POLLS {
            if go.exists() {
                return;
            }
            std::thread::sleep(POLL);
        }
    }
}

#[cfg(debug_assertions)]
use walk_pause_trigger::pause_after_walk;

#[cfg(not(debug_assertions))]
pub(crate) fn pause_after_walk() {}

/// Recursively collect all `.mds` files under `root`, bounded by `max_depth`.
///
/// Symlinked directories AND symlinked files are skipped to avoid cycles and
/// to maintain build parity with the single-file symlink guard (PF-004 / commit aa0c538).
/// When `exclude_prefix` is `Some(p)`, any path that starts with `p` is skipped
/// (used to exclude the out-dir when it is inside the watched root).
///
/// For callers that need to distinguish "genuinely empty tree" from "all candidates
/// excluded", use [`collect_mds_files_detailed`] instead.
pub(crate) fn collect_mds_files(
    root: &Path,
    max_depth: usize,
    exclude_prefix: Option<&Path>,
) -> Vec<PathBuf> {
    collect_mds_files_detailed(root, max_depth, exclude_prefix).files
}

/// Return `true` when a directory name should be excluded from recursive
/// traversal by default (PF-004: enforced on the shared walker so ALL
/// subcommands — build / check / lint / fmt / watch — inherit the behaviour).
///
/// Excluded directory names:
/// - Any name that starts with `.` (hidden directories, e.g. `.git`, `.cache`)
/// - `node_modules`
///
/// Note: this gate applies to the RECURSION step only — the root directory
/// that was explicitly passed to `collect_mds_files` is always processed,
/// even if its own name happens to start with `.`.  Hidden *files* (e.g.
/// `.dotfile.mds`) at the traversed directory level are still collected.
pub(crate) fn is_default_excluded_dir(name: &str) -> bool {
    name.starts_with('.') || name == "node_modules"
}

/// Return `true` when `path` lives inside a default-excluded sub-directory
/// of `root` (i.e. traversal would have been skipped there by
/// `is_default_excluded_dir`).
///
/// Used by the watch guards to detect events that should be treated as external
/// dependencies rather than normal output-producing sources (PF-004 class:
/// the same limit must be enforced on the parallel event-processing path as on
/// the initial walker path — avoids the "limit on one path but not another"
/// bug class).
pub(crate) fn is_within_default_excluded_dir(root: &Path, path: &Path) -> bool {
    // Strip the root prefix to get a relative path, then walk the ancestor
    // chain using Path::parent() — avoids allocating a Vec<Component> just to
    // drop the final component (issue #69: this runs on the watch per-event
    // hot path).
    //
    // Edge case: when `rel` is a single component (e.g. "foo.mds"),
    // rel.parent() returns Some("") whose file_name() is None, and
    // "".parent() returns None, ending the loop correctly.
    let rel = match path.strip_prefix(root) {
        // `false` IS the closed value here (#217): this predicate answers "is `path`
        // inside a default-excluded subdirectory OF `root`", and a path that is not
        // under `root` at all has no such subdirectory — the honest answer is no. It is
        // not a fail-open default, because no caller acts on this answer alone: the
        // watch's `classify` evaluates it only after its own `starts_with(root)` test, so
        // an out-of-root path is already classified as an external dep (compile for deps,
        // never emit output) before this function's answer is consulted, and
        // `handle_fs_event_dir` uses it only to drop a path, never to admit one.
        Err(_) => return false,
        Ok(r) => r,
    };
    let mut ancestor = rel.parent();
    while let Some(dir) = ancestor {
        if let Some(name) = dir.file_name().and_then(|n| n.to_str()) {
            if is_default_excluded_dir(name) {
                return true;
            }
        }
        ancestor = dir.parent();
    }
    false
}

/// The entries of one directory, sorted by file name: the walk visits a tree in the same
/// order on every platform. `read_dir` gives no set order (hash or creation order on most
/// Linux filesystems), and a run that processes files one by one — `mds fmt` of a
/// directory — shows its results in the order it visits them.
fn by_name(read_dir: std::fs::ReadDir) -> Vec<std::fs::DirEntry> {
    let mut entries: Vec<_> = read_dir.flatten().collect();
    entries.sort_by_cached_key(std::fs::DirEntry::file_name);
    entries
}

fn collect_mds_files_inner(
    dir: &Path,
    depth: usize,
    max_depth: usize,
    exclude_prefix: Option<&Path>,
    results: &mut WalkResult,
) {
    if depth > max_depth {
        // The directory name is discovered by the walk — the user never types it — so it
        // is untrusted on every subcommand that shares this walker (build / check / fmt /
        // lint / watch).  Prose through `eprint_warning` (HUMAN), the path through
        // `safe_path` (WIRE): a directory name is never legitimately multi-line, and a
        // raw one here forged a standalone `Clean: …` line as well as emitting raw ESC.
        eprint_warning(&format!(
            "warning: directory depth limit ({max_depth}) reached at {}; \
             deeper files will not be processed",
            safe_path(dir)
        ));
        return;
    }
    let read_dir = match std::fs::read_dir(dir) {
        Ok(rd) => rd,
        Err(_) => return,
    };
    for entry in by_name(read_dir) {
        let path = entry.path();

        // Skip the output directory when it is nested inside the root.
        if let Some(excl) = exclude_prefix {
            if path.starts_with(excl) {
                continue;
            }
        }

        let file_type = match entry.file_type() {
            Ok(ft) => ft,
            Err(_) => continue,
        };
        if file_type.is_symlink() {
            // Symlinked dirs AND symlinked files are skipped (PF-004 / build parity).
            // This preserves the same guard as single-file mode where symlinked entries
            // are rejected at startup (commit aa0c538).
            continue;
        }
        if file_type.is_dir() {
            // Skip hidden directories (e.g. .git, .cache) and node_modules on the
            // RECURSION step so all subcommands inherit the default exclusions via
            // the shared walker (PF-004).  The root dir that was explicitly passed
            // to collect_mds_files() is NEVER checked here — this guard applies
            // only to directory ENTRIES discovered during traversal.  Since entries
            // are always children of the current dir, they are never the explicit root.
            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                if is_default_excluded_dir(name) {
                    // Count the .mds files we're skipping so callers can emit a
                    // meaningful diagnostic when all candidates are excluded.
                    count_mds_in_excluded_dir(
                        &path,
                        depth + 1,
                        max_depth,
                        &mut results.excluded_by_default,
                    );
                    continue;
                }
            }
            collect_mds_files_inner(&path, depth + 1, max_depth, exclude_prefix, results);
        } else if file_type.is_file() && path.extension().and_then(|e| e.to_str()) == Some("mds") {
            let Ok(metadata) = entry.metadata() else {
                continue;
            };
            if !metadata.is_file() {
                continue;
            }
            results.metadata.insert(path.clone(), metadata);
            results.files.push(path);
        }
    }
}

/// Count `.mds` files inside a directory that is being skipped due to a
/// default exclusion. Symlinks are still skipped. Does not apply further
/// exclusion filtering — we are already inside an excluded root, so every
/// `.mds` descendant is a skipped candidate regardless of name.
fn count_mds_in_excluded_dir(dir: &Path, depth: usize, max_depth: usize, count: &mut usize) {
    if depth > max_depth {
        return;
    }
    let Ok(rd) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in rd.flatten() {
        let path = entry.path();
        let Ok(ft) = entry.file_type() else { continue };
        if ft.is_symlink() {
            continue;
        }
        if ft.is_dir() {
            count_mds_in_excluded_dir(&path, depth + 1, max_depth, count);
        } else if ft.is_file() && path.extension().and_then(|e| e.to_str()) == Some("mds") {
            *count += 1;
        }
    }
}

/// Return `true` if `path`'s file name starts with `_` (partial convention, DD2).
///
/// A name that is not valid UTF-8 answers `false` — "not a partial", i.e. a source that
/// should be compiled and written. That is the closed answer, not the open one (#217):
/// such a source never reaches a write, because every read goes through
/// `mds-core`'s `path_to_str`, which rejects a non-UTF-8 path with `MdsError::Io`. The
/// file is reported as a per-file failure (exit 2 in single-file mode, one `failed` in
/// the directory tally) instead of being silently skipped the way `true` would skip it.
pub(crate) fn is_partial(path: &Path) -> bool {
    path.file_name()
        .and_then(|n| n.to_str())
        .map(|s| s.starts_with('_'))
        .unwrap_or(false)
}

/// `Some(n)` when `files` is non-empty and every entry is a `_`-prefixed partial —
/// the "nothing to build/check" case #387 closes; `None` for an empty list (the
/// empty-tree arm owns that) or when any non-partial entry exists. One predicate for
/// `run_build_directory` and `run_check_directory` so the two arms cannot drift.
pub(crate) fn partials_only(files: &[PathBuf]) -> Option<usize> {
    if files.is_empty() {
        return None;
    }
    files.iter().all(|f| is_partial(f)).then_some(files.len())
}

// ── Stale-output cleanup ──────────────────────────────────────────────────────

/// The stale output beside `written`, the output of a source that compiled to `kind`: the
/// other kind's output of the same name (#160), which [`probe_and_remove_stale`] deals
/// with — `out/a.b.md`'s is `out/a.b.json`.
pub(crate) fn stale_output(written: &WriteTarget, kind: OutputKind) -> WriteTarget {
    written.sibling(|path| path.with_extension(kind.stale_extension()))
}

/// After a directory build wrote `written`, the output of a source that compiled to
/// `kind`, deal with the other kind's output of the same name that an earlier build left
/// when the source compiled to that kind (#160). It is named from the output written —
/// `out/a.b.md`'s is `out/a.b.json` — never from the source's name, which for `a.b.mds`
/// would name `a.mds`'s output.
///
/// - A stale `.json` is removed only while it holds exactly what mds writes for a
///   messages output ([`holds_messages_output`]), and only as every removal is made
///   ([`crate::write::remove_proven`]): below the output's anchor, through no symlink
///   there, and only as a regular file. Anything else at its name — another file, a
///   symlink, a directory, a FIFO — is kept, with one warning.
/// - A stale `.md` is never removed — nothing in Markdown shows that mds wrote it — and
///   is kept, as is anything else at its name, with one warning.
///
/// A removal is silent, as is a name nothing has; `quiet` silences the warnings, which
/// name the file by its `shown` form (#390).
///
/// # Errors
///
/// `mds::io`, for the caller to report (#157), naming the stale `.json` as shown: one
/// that cannot be looked at or read, so nothing is known of it, and a proven one that is
/// not removed — refused (a symlink below the anchor, say) or the removal failed.
pub(crate) fn probe_and_remove_stale(
    written: &WriteTarget,
    kind: OutputKind,
    quiet: bool,
) -> std::result::Result<(), mds::MdsError> {
    let stale = stale_output(written, kind);
    match kind {
        OutputKind::Markdown => remove_stale_messages(&stale, quiet),
        OutputKind::Messages => {
            if !quiet && std::fs::symlink_metadata(&stale.path).is_ok() {
                eprint_warning(&format!(
                    "warning: kept stale output {}: mds never removes a Markdown file",
                    safe_path(&stale.shown)
                ));
            }
            Ok(())
        }
    }
}

/// Remove `stale`, the `.json` of a source that now compiles to Markdown, only while it
/// holds exactly what mds writes for a messages output; keep anything else with one
/// warning (none under `quiet`). See [`probe_and_remove_stale`].
fn remove_stale_messages(
    stale: &WriteTarget,
    quiet: bool,
) -> std::result::Result<(), mds::MdsError> {
    let proof = |file: &mut std::fs::File| {
        let size = file.metadata()?.len();
        holds_messages_output(file, size, mds::MAX_FILE_SIZE)
    };
    let not_removed = match crate::write::remove_proven(stale, proof) {
        Ok(Removal::Removed | Removal::Missing) => return Ok(()),
        Ok(Removal::Kept) | Err(NotRemoved::NotAFile | NotRemoved::Link) => {
            if !quiet {
                eprint_warning(&format!(
                    "warning: kept stale output {}: not proven to be written by mds",
                    safe_path(&stale.shown)
                ));
            }
            return Ok(());
        }
        Err(not_removed) => not_removed,
    };
    Err(stale_removal_error(
        "stale output",
        &stale.shown,
        &not_removed,
    ))
}

/// Word `not_removed`, a [`crate::write::remove_proven`] refusal already decided to be an
/// error rather than a kept file, as `mds::io`: "cannot read `<noun>` …" when nothing is
/// known of the file, "could not remove `<noun>` …" otherwise. Shared by the stale-output
/// removal above and `build::verify_then_delete_map`'s stale map, so the two wordings
/// cannot drift apart (#160).
pub(crate) fn stale_removal_error(
    noun: &str,
    shown: &Path,
    not_removed: &NotRemoved,
) -> mds::MdsError {
    let what = match not_removed {
        NotRemoved::Unreadable(_) => "cannot read",
        _ => "could not remove",
    };
    mds::MdsError::Io {
        message: format!(
            "{what} {noun} {}: {}",
            safe_path(shown),
            not_removed.cause()
        ),
    }
}

/// One message as a messages output holds it: the fields of [`mds::Message`], in the
/// order they are written, and no other.
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
struct WrittenMessage {
    role: String,
    content: String,
}

/// Whether `reader` holds exactly what mds writes for a messages output (#160): a JSON
/// array of messages that, written back as a messages output is written
/// ([`crate::build::messages_json`]), gives the same bytes — so neither its shape nor its
/// text differs from a file mds wrote. `size` is the reader's length, which sizes the
/// read; no more than `cap` bytes are read, and a reader that holds more holds no
/// messages output.
fn holds_messages_output(
    reader: &mut impl std::io::Read,
    size: u64,
    cap: u64,
) -> std::io::Result<bool> {
    if size > cap {
        return Ok(false);
    }
    let bytes = mds::read_at_most(reader, cap.saturating_add(1), size)?;
    if bytes.len() as u64 > cap {
        return Ok(false);
    }
    let Ok(messages) = serde_json::from_slice::<Vec<WrittenMessage>>(&bytes) else {
        return Ok(false);
    };
    Ok(crate::build::messages_json(&messages).is_ok_and(|written| written.as_bytes() == bytes))
}

/// Where a `Dir`-mode source lands below the out-dir, without its extension.
///
/// `Flattened` is the `strip_prefix` failure arm: contained by construction (the stem is
/// always a relative `OsStr`) but it abandons the subtree mirror, so two out-of-root
/// sources with the same file name map to the same path. Unreachable from every live
/// caller — see [`output_path_for`] — and the variant exists so the write oracle can
/// *say* so instead of silently degrading (#217).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum MirroredStem {
    /// `source` was below `root`: its relative subtree is preserved below the out-dir.
    Mirrored(PathBuf),
    /// `source` was not below `root`: only its stem survives, directly below the out-dir.
    Flattened(PathBuf),
}

impl MirroredStem {
    /// The extension-less output path below the out-dir, whichever arm produced it.
    pub(crate) fn into_path(self) -> PathBuf {
        match self {
            Self::Mirrored(p) | Self::Flattened(p) => p,
        }
    }
}

/// Compute the `Dir`-mode extension-less output stem for `source`, relative to the
/// out-dir, classified by whether the subtree mirror survived.
///
/// Single source of truth for both [`output_base_no_ext`] (the silent probe oracle) and
/// [`output_path_for`] (the write oracle that reports the flatten).
fn mirror_stem(source: &Path, root: &Path) -> MirroredStem {
    match source.strip_prefix(root) {
        Ok(rel) => {
            // Invariant: `rel` is a non-empty RELATIVE path — `source` is a regular
            // `.mds` file strictly below `root` — so `file_stem()` is `Some`. For a
            // single-component `rel` (a bare file name) `parent()` is `Some("")`, not
            // `None`, so a bare name lands directly in the out-dir.
            let stem = rel.file_stem().unwrap_or(rel.as_os_str()).to_os_string();
            MirroredStem::Mirrored(rel.parent().unwrap_or(Path::new("")).join(stem))
        }
        Err(_) => {
            // Invariant: the stem must be relative, or joining it re-roots and the result
            // leaves the out-dir entirely (`d.join("/") == "/"`). `file_stem()` is `None`
            // only for `/`, `..` and a bare drive prefix — never a `.mds` file — and the
            // fallback that used to stand here, `source.as_os_str()`, was exactly the
            // absolute value that escapes. A literal is the only value guaranteed relative
            // for every input.
            let stem = source.file_stem().unwrap_or_else(|| OsStr::new("output"));
            MirroredStem::Flattened(PathBuf::from(stem))
        }
    }
}

/// Return the path stem (path without extension) for a compiled source.
///
/// The `path` of [`output_stem_for`]: a directory build takes the directory its output
/// lands in — a source map's base — from it.
///
/// For `Dir` mode this defers to [`mirror_stem`] so the stem is always computed
/// consistently with [`output_path_for`], below the directory's canonical form: the stem
/// is for probing the filesystem, not for a message.
pub(crate) fn output_base_no_ext(source: &Path, root: &Path, base: &OutputBase) -> PathBuf {
    match base {
        OutputBase::Dir { canonical, .. } => canonical.join(mirror_stem(source, root).into_path()),
        OutputBase::NextToSource => {
            // source.with_extension("") removes the existing extension.
            source.with_extension("")
        }
    }
}

/// [`output_base_no_ext`] in both forms, fixed here as [`output_path_for`] fixes an
/// output's (#390), below the same anchor (#160): `path` is the extension-less stem the
/// filesystem is probed at; `shown` is the same stem below the out-dir's shown form, or —
/// next to the source — below the directory argument as typed. [`output_path_for`]
/// names an output next to its source from it.
///
/// Like [`output_base_no_ext`] it is a probe: it reports nothing, the flattened arm
/// included.
pub(crate) fn output_stem_for(
    source: &Path,
    root: RootPaths<'_>,
    base: &OutputBase,
) -> WriteTarget {
    match base {
        OutputBase::Dir {
            canonical,
            shown,
            below_anchor,
        } => WriteTarget::below_out_dir(
            canonical,
            shown,
            *below_anchor,
            &mirror_stem(source, root.walked).into_path(),
        ),
        OutputBase::NextToSource => {
            WriteTarget::walked_below(root, source).sibling(|source| source.with_extension(""))
        }
    }
}

// ── Sanitized stderr render ───────────────────────────────────────────────────

/// Re-export: byte-length-preserving source neutralization before miette rendering.
///
/// Lives in `mds-core` so both `MdsError::at()` (compiler error path) and
/// `render_diag_human` (lint diagnostic path) use a single canonical implementation
/// (avoids PF-004 / PF-014 parallel-path drift).
pub(crate) use mds::neutralize_source_for_render;

/// A terminal-safe view of a [`miette::Report`], built **before** rendering.
///
/// Overrides every text surface the frame can render — the `Display` message, the
/// `code`, the `help` and `url` text, each [`miette::LabeledSpan`]'s label, and the
/// whole auxiliary diagnostic graph (`source` cause chain, `related`,
/// `diagnostic_source`) — with [`mds::sanitize_control_chars`]-escaped copies (HUMAN
/// mode, so `\n` and `\t` survive and multi-line frames stay readable).  Everything the
/// frame's geometry depends on — `severity`, `source_code`, and each label's byte span —
/// is delegated to the inner report untouched, so the byte-length-preserving
/// neutralization already applied to source excerpts (via `mds::named_source_for_render`)
/// keeps every span offset and caret column exact.
///
/// Every copy is rendered at construction without panicking (#157): a surface whose
/// `Display` fails is dropped, or — for a message, which is never optional — replaced
/// by a fixed placeholder. miette then formats owned strings for all of those surfaces;
/// what it still reads through the inner report is the source excerpt, and a read that
/// fails there is handled by [`render_error_sanitized`].
///
/// # Why this is the PF-014-correct boundary
///
/// The rendered frame is never post-processed.  Running a sanitizer over an
/// already-rendered miette frame would escape miette's *own* ANSI SGR colour codes
/// into literal `\u001b[33m` noise on any colour-capable TTY — on completely benign
/// input — and desynchronise caret alignment.  CI cannot catch that regression
/// because the CLI tests pin `NO_COLOR=1` and pipe stderr.  Sanitizing the renderer's
/// *inputs* has neither failure mode.
///
/// # Why it wraps the whole `Report` rather than just `MdsError`
///
/// The CLI produces two error families: `MdsError` (compiler diagnostics) and
/// CLI-authored `miette::miette!()` reports, which do **not** downcast to `MdsError`
/// (see `build::exit_code`).  Both interpolate untrusted text — a template's include
/// alias in the first case, an `mds.json` value or a hostile filename in the second.
/// Wrapping at the `Report` level covers both, and keeps covering any error type added
/// later, so the guarantee holds by construction rather than by remembering to extend
/// a downcast ladder (avoids PF-004).
///
/// # The auxiliary graph (`source` / `related` / `diagnostic_source`)
///
/// A `Diagnostic` can hang three further diagnostic graphs off itself, all of which
/// miette renders: the `std::error::Error` cause chain, the `related()` siblings, and
/// `diagnostic_source()`.  All three carry prose, so all three must be escaped.
///
/// They cannot be forwarded by reference the way `code`/`severity`/`url` are: those
/// accessors return borrows of the *inner* report, so handing back a sanitized view
/// would require the wrapper to own it and hand out a borrow of itself.  This wrapper
/// therefore materialises the whole graph into owned [`SanitizedNode`]s at construction
/// (bounded by [`MAX_AUX_DEPTH`]) and forwards borrows of those.
///
/// Enforcing this with a `debug_assert!` that the graph is empty — which is what an
/// earlier revision did, on the grounds that no CLI error populates it today — is
/// exactly PF-005: `debug_assert!` is compiled out of release, so the invariant would
/// hold under test and be absent in the shipped binary.  The first error type to grow a
/// `#[source]` field would have silently dropped its cause chain from release stderr
/// while CI stayed green.
struct SanitizedReport {
    inner: miette::Report,
    message: String,
    code: Option<String>,
    help: Option<String>,
    url: Option<String>,
    source: Option<SanitizedNode>,
    related: Vec<SanitizedNode>,
    diagnostic_source: Option<SanitizedNode>,
}

/// Depth bound for materialising a report's cause / related / diagnostic-source graph.
///
/// Cause chains are finite in practice, but nothing in the `Error` trait forbids a cycle
/// (a `source()` that returns a sibling of itself would loop forever).  Rendering is not
/// a place to discover that, so the walk is explicitly bounded; a graph deeper than this
/// is truncated, which drops trailing context but never hangs or overflows the stack.
const MAX_AUX_DEPTH: usize = 16;

/// An owned, control-character-escaped snapshot of one node in a report's auxiliary
/// diagnostic graph.
///
/// Every prose surface (`message`, `help`, `code`, `url`, label text) is escaped with
/// HUMAN-mode [`mds::sanitize_control_chars`] when the node is built.  Label byte spans
/// are copied verbatim, exactly as `SanitizedReport::labels` does, so caret geometry
/// against the parent's already-neutralized source stays exact.
///
/// `source_code()` returns `None` by design: a `&dyn miette::SourceCode` cannot be
/// cloned out of the inner diagnostic, and miette falls back to the *parent* report's
/// source — which `SanitizedReport::source_code` forwards — when a nested diagnostic
/// supplies none.  So a nested diagnostic still renders against neutralized source.
struct SanitizedNode {
    message: String,
    help: Option<String>,
    code: Option<String>,
    url: Option<String>,
    severity: Option<miette::Severity>,
    labels: Option<Vec<miette::LabeledSpan>>,
    source: Option<Box<SanitizedNode>>,
    related: Vec<SanitizedNode>,
    diagnostic_source: Option<Box<SanitizedNode>>,
}

/// Placeholder for a message whose own `Display` failed (#157).
const UNFORMATTABLE: &str = "(this text could not be formatted)";

/// Render `d` into a `String` without panicking: `None` when its `Display` fails.
///
/// `to_string()` and `format!` panic when an impl returns `fmt::Error`, and a report's
/// text comes from `Display` impls this crate does not control.
fn display_text<T: std::fmt::Display + ?Sized>(d: &T) -> Option<String> {
    let mut text = String::new();
    std::fmt::Write::write_fmt(&mut text, format_args!("{d}")).ok()?;
    Some(text)
}

/// Escape one optional `Display` surface to an owned `String`.
///
/// A surface whose `Display` fails is dropped: code, help and url are optional, so the
/// frame renders without it.
fn escape_display(d: Option<Box<dyn std::fmt::Display + '_>>) -> Option<String> {
    d.and_then(|v| display_text(&*v))
        .map(|text| mds::sanitize_control_chars(&text).into_owned())
}

/// Escape a message, or [`UNFORMATTABLE`] when its `Display` fails — a message is never
/// optional, so its place says why it is empty.
fn escape_message<T: std::fmt::Display + ?Sized>(d: &T) -> String {
    display_text(d).map_or_else(
        || UNFORMATTABLE.to_owned(),
        |text| mds::sanitize_control_chars(&text).into_owned(),
    )
}

/// Escape a `Diagnostic`'s label text, keeping each byte span verbatim.
///
/// `None` is preserved as `None` (rather than collapsed to an empty vector) so miette
/// distinguishes "no labels" from "labels, but none of them" exactly as it did before
/// the wrapper was introduced.
fn escape_labels(d: &dyn miette::Diagnostic) -> Option<Vec<miette::LabeledSpan>> {
    Some(
        d.labels()?
            .map(|label| {
                let text = label
                    .label()
                    .map(|t| mds::sanitize_control_chars(t).into_owned());
                let span = *label.inner();
                if label.primary() {
                    miette::LabeledSpan::new_primary_with_span(text, span)
                } else {
                    miette::LabeledSpan::new_with_span(text, span)
                }
            })
            .collect(),
    )
}

impl SanitizedNode {
    /// Build from a `Diagnostic` node (used for `related` / `diagnostic_source`).
    fn from_diagnostic(d: &dyn miette::Diagnostic, depth: usize) -> Self {
        Self {
            message: escape_message(d),
            help: escape_display(d.help()),
            code: escape_display(d.code()),
            url: escape_display(d.url()),
            severity: d.severity(),
            labels: escape_labels(d),
            source: Self::chain_from_error(std::error::Error::source(d), depth),
            related: Self::related_from(d, depth),
            diagnostic_source: Self::boxed_from_diagnostic(d.diagnostic_source(), depth),
        }
    }

    /// Build from a plain `Error` node (used for the `source()` cause chain, whose links
    /// expose no `Diagnostic` data — only a `Display` message and a further `source()`).
    fn from_error(e: &(dyn std::error::Error + 'static), depth: usize) -> Self {
        Self {
            message: escape_message(e),
            help: None,
            code: None,
            url: None,
            severity: None,
            labels: None,
            source: Self::chain_from_error(e.source(), depth),
            related: Vec::new(),
            diagnostic_source: None,
        }
    }

    fn chain_from_error(
        e: Option<&(dyn std::error::Error + 'static)>,
        depth: usize,
    ) -> Option<Box<SanitizedNode>> {
        if depth >= MAX_AUX_DEPTH {
            return None;
        }
        e.map(|e| Box::new(Self::from_error(e, depth + 1)))
    }

    fn boxed_from_diagnostic(
        d: Option<&dyn miette::Diagnostic>,
        depth: usize,
    ) -> Option<Box<SanitizedNode>> {
        if depth >= MAX_AUX_DEPTH {
            return None;
        }
        d.map(|d| Box::new(Self::from_diagnostic(d, depth + 1)))
    }

    fn related_from(d: &dyn miette::Diagnostic, depth: usize) -> Vec<SanitizedNode> {
        if depth >= MAX_AUX_DEPTH {
            return Vec::new();
        }
        d.related()
            .map(|rs| {
                rs.map(|r| SanitizedNode::from_diagnostic(r, depth + 1))
                    .collect()
            })
            .unwrap_or_default()
    }
}

impl std::fmt::Display for SanitizedNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

/// Hand-written for the same reason as [`SanitizedReport`]'s: the derived `Debug` of a
/// miette type can be its full graphical render, which would bypass the escaping.
impl std::fmt::Debug for SanitizedNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SanitizedNode")
            .field("message", &self.message)
            .field("help", &self.help)
            .finish_non_exhaustive()
    }
}

impl std::error::Error for SanitizedNode {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source
            .as_deref()
            .map(|n| n as &(dyn std::error::Error + 'static))
    }
}

impl miette::Diagnostic for SanitizedNode {
    fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
        boxed_str(self.code.as_deref())
    }

    fn severity(&self) -> Option<miette::Severity> {
        self.severity
    }

    fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
        boxed_str(self.help.as_deref())
    }

    fn url<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
        boxed_str(self.url.as_deref())
    }

    fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
        Some(Box::new(self.labels.as_ref()?.iter().cloned()))
    }

    fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn miette::Diagnostic> + 'a>> {
        related_iter(&self.related)
    }

    fn diagnostic_source(&self) -> Option<&dyn miette::Diagnostic> {
        self.diagnostic_source
            .as_deref()
            .map(|n| n as &dyn miette::Diagnostic)
    }
}

/// Box an optional `&str` as the `Display` trait object miette's accessors return.
fn boxed_str(s: Option<&str>) -> Option<Box<dyn std::fmt::Display + '_>> {
    s.map(|s| -> Box<dyn std::fmt::Display + '_> { Box::new(s) })
}

/// Shared `related()` body: `None` when empty, so miette omits the section entirely.
fn related_iter(
    nodes: &[SanitizedNode],
) -> Option<Box<dyn Iterator<Item = &dyn miette::Diagnostic> + '_>> {
    if nodes.is_empty() {
        return None;
    }
    Some(Box::new(nodes.iter().map(|n| n as &dyn miette::Diagnostic)))
}

impl SanitizedReport {
    fn new(inner: miette::Report) -> Self {
        let message = escape_message(&inner);
        let code = escape_display(inner.code());
        let help = escape_display(inner.help());
        let url = escape_display(inner.url());
        let source = SanitizedNode::chain_from_error(std::error::Error::source(&*inner), 0)
            .map(|boxed| *boxed);
        let related = SanitizedNode::related_from(inner.as_ref(), 0);
        let diagnostic_source =
            SanitizedNode::boxed_from_diagnostic(inner.diagnostic_source(), 0).map(|boxed| *boxed);

        Self {
            inner,
            message,
            code,
            help,
            url,
            source,
            related,
            diagnostic_source,
        }
    }
}

impl std::fmt::Display for SanitizedReport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

/// Hand-written so the wrapper never surfaces the inner report's own `Debug`, which
/// under miette's `fancy` feature is the full graphical render of the *unsanitized*
/// error.
impl std::fmt::Debug for SanitizedReport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SanitizedReport")
            .field("message", &self.message)
            .field("help", &self.help)
            .finish_non_exhaustive()
    }
}

/// Forwards the **sanitized** cause chain, never the inner report's own.
impl std::error::Error for SanitizedReport {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source
            .as_ref()
            .map(|n| n as &(dyn std::error::Error + 'static))
    }
}

impl miette::Diagnostic for SanitizedReport {
    fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
        boxed_str(self.code.as_deref())
    }

    fn severity(&self) -> Option<miette::Severity> {
        self.inner.severity()
    }

    fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
        boxed_str(self.help.as_deref())
    }

    fn url<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
        boxed_str(self.url.as_deref())
    }

    fn source_code(&self) -> Option<&dyn miette::SourceCode> {
        self.inner.source_code()
    }

    /// Byte spans are forwarded verbatim (they index the neutralized, byte-length-
    /// preserved source); only the label *text* is escaped.  `LintDiagnostic` uses its
    /// own message as the label text, so this is a real untrusted-text surface.
    fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
        Some(Box::new(escape_labels(self.inner.as_ref())?.into_iter()))
    }

    /// The **sanitized** related-diagnostic snapshots, not the inner report's.
    fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn miette::Diagnostic> + 'a>> {
        related_iter(&self.related)
    }

    /// The **sanitized** diagnostic source, not the inner report's.
    fn diagnostic_source(&self) -> Option<&dyn miette::Diagnostic> {
        self.diagnostic_source
            .as_ref()
            .map(|n| n as &dyn miette::Diagnostic)
    }
}

/// Wrap `report` so every prose surface it renders is control-character-escaped.
///
/// This is the construction-boundary half of the PF-014 design: callers hand it a
/// `Report` built from raw values, and it produces one whose message, help, and label
/// text are safe to hand to miette.  See [`SanitizedReport`] for the full rationale.
fn sanitize_report(report: miette::Report) -> miette::Report {
    miette::Report::new(SanitizedReport::new(report))
}

/// Sanitize `report`'s inputs and render it to a `String` — the pure transformation
/// extracted from [`eprint_error`] so it can be tested without touching stderr.
///
/// The rendered frame itself is never post-processed (PF-014); all escaping happens
/// in [`sanitize_report`], before miette sees the values.
///
/// Never panics (#157). The frame is rendered through `fmt::Write`, which reports a
/// formatting failure as `fmt::Error` where `format!` would panic; when miette's render
/// fails part-way — a source excerpt that cannot be read, say — the partial frame is
/// discarded and [`plain_text_fallback`] renders the report instead.
///
/// Note: idempotency is a property of [`mds::sanitize_control_chars`] (calling it
/// twice on already-sanitized input is a no-op), not of this function (each call
/// re-renders the `Report` from scratch).  That idempotency is what lets
/// `render_diag_human` keep sanitizing its own inputs — it must, because it also
/// neutralizes the source excerpt and filename, which this boundary cannot do.
fn render_error_sanitized(report: miette::Report) -> String {
    let report = sanitize_report(report);
    let mut rendered = String::new();
    match std::fmt::Write::write_fmt(&mut rendered, format_args!("{report:?}")) {
        Ok(()) => rendered,
        Err(std::fmt::Error) => plain_text_fallback(report.as_ref()),
    }
}

/// The plain-text form of a report whose frame miette could not render: its code, its
/// message and its help, each escaped, laid out like miette's frame without the source
/// excerpt. A surface whose `Display` fails is left out, as in [`SanitizedReport`].
fn plain_text_fallback(d: &dyn miette::Diagnostic) -> String {
    let mut out = String::new();
    if let Some(code) = d.code().and_then(|c| display_text(&*c)) {
        out.push_str(&mds::sanitize_control_chars_wire(&code));
        out.push_str("\n\n");
    }
    push_frame_block(&mut out, "  \u{00d7} ", &escape_message(d));
    if let Some(help) = escape_display(d.help()) {
        push_frame_block(&mut out, "  help: ", &help);
    }
    out
}

/// Push `lead` and `text`, continuing each further line of `text` under miette's
/// U+2502 rule, then end the line.
fn push_frame_block(out: &mut String, lead: &str, text: &str) {
    out.push_str(lead);
    out.push_str(&text.replace('\n', "\n  \u{2502} "));
    out.push('\n');
}

/// Render a miette `Report` to stderr — the single choke-point for all CLI error
/// output.
///
/// All per-file error handlers in `main`, `build`, `fmt`, `lint`, and `watch` route
/// error rendering through this helper, so there is exactly one site to audit for
/// escape-injection safety: a check enforced on the primary path and silently absent on
/// a sibling path is the failure this one site prevents.
///
/// **This function escapes the report's message, help, label text, and auxiliary
/// diagnostic graph itself**, via [`sanitize_report`], for every report it is given —
/// `MdsError` and CLI-authored `miette::miette!()` alike.  Callers do not need to
/// pre-sanitize prose.
///
/// What callers still owe, because this boundary cannot supply it: the
/// [`miette::NamedSource`] attached to the report, whose two halves need different
/// treatments (byte-length-preserving neutralization for the span-indexed source, WIRE
/// escaping for the single-line filename).  Build it with
/// [`mds::named_source_for_render`] — `MdsError::at()` (compiler path),
/// `check_equivalence` (formatter) and `render_diag_human` (lint path) all do.
///
/// miette's own ANSI SGR styling is passed through untouched — carets and box-drawing
/// survive intact.
///
/// Writes through `ewriteln!`, so a closed or failing stderr never panics (#157).
///
/// Note: status-line path display (`Clean:`, `Fixed:`, etc.) is handled by the
/// separate [`safe_path`] helper, not by this function.
pub(crate) fn eprint_error(report: miette::Report) {
    ewriteln!("{}", render_error_sanitized(report));
}

/// Print a CLI warning to stderr with HUMAN-mode escaping applied to the whole line
/// (CWE-150 / PF-004 / #176).
///
/// Applies [`mds::sanitize_control_chars`] (preserves `\n` and `\t`; escapes all other
/// C0 / DEL / C1 controls and bidi / separator / BOM characters to their six-character
/// `\uXXXX` literals) before printing, so a hostile warning message cannot inject ANSI
/// terminal commands into stderr.
///
/// # This helper alone is NOT sufficient — it is the prose half of the rule
///
/// HUMAN mode preserves `\n` on purpose, so that a multi-line warning body still renders
/// as multiple lines. That means routing a hostile *identifier* through this function
/// closes CWE-150 on it and leaves CWE-117 open: `lint.rs`'s unknown-`mds.json`-rule
/// warning already called this helper, and a rule name of
/// `x<LF>Clean: totally-real.mds<LF>0 problems found` still emitted three standalone
/// lines byte-identical in form to genuine status output.
///
/// The governing rule is per FIELD, not per surface (spec §7.5):
///
/// | Part of the line | Mode | Helper |
/// |------------------|------|--------|
/// | warning prose / body | HUMAN | this function |
/// | interpolated filename or path | WIRE | [`safe_path`] |
/// | interpolated identifier, config value, or error cause | WIRE | [`safe_inline`] |
///
/// So the correct shape is `eprint_warning(&format!("warning: … {} …", safe_path(p)))` —
/// both escapes, not either one.
///
/// # Enumeration is not a guarantee — the guard is
///
/// Two earlier revisions of this rustdoc asserted coverage by listing the sites that had
/// been routed. Each list was correct when written and stale by the next review: first
/// `lint.rs`'s rule warning was missed, then the walker's own depth-limit warning inside
/// this very file. A guarantee stated as a property of a code path is only ever a
/// property of the sites someone remembered to enumerate — that is PF-004.
///
/// The property is therefore no longer asserted in prose here. It is enforced by
/// `crates/mds-cli/tests/print_discipline.rs`, which fails if any print macro under
/// `crates/mds-cli/src/**` interpolates a value that is not passed through one of the
/// escape helpers, and which applies the same rule to `format!` invocations nested
/// inside `eprint_warning` calls. `watch.rs`'s lifecycle status lines — previously
/// carved out as a pre-existing gap — are in scope and now routed like everything else.
///
/// Writes through `ewriteln!`, so a closed or failing stderr never panics (#157).
pub(crate) fn eprint_warning(w: &str) {
    ewriteln!("{}", mds::sanitize_control_chars(w));
}

/// Neutralize hostile control bytes in source text for `--diff` preview output.
///
/// `--diff` preview output: neutralized on TTY, byte-faithful when piped.
///
/// **`--diff` only.** `--check` on its own emits no preview text — just `Would fix:` /
/// `Would reformat:` status lines, which are sanitized unconditionally via
/// [`safe_path`] and never reach this function. The only caller is
/// [`render_unified_diff`], shared by `mds fmt --diff` and `mds lint --fix --diff`.
///
/// When `writer_is_tty` is `true`, returns [`neutralize_source_for_render`]`(text)` —
/// a byte-length-preserving substitution that maps C0/DEL/C1 controls and the widened
/// bidi/format hazard class (added in #176) to `?` or U+00A0/U+FFFD so hostile template
/// source cannot inject ANSI terminal commands into the rendered diff (CWE-150).
///
/// When `writer_is_tty` is `false`, returns `Cow::Borrowed(text)` unchanged so
/// redirected diff output (e.g. `mds fmt --diff > patch.diff`) stays byte-faithful
/// and applicable by `patch`/tooling.
///
/// This is a pure, allocation-free helper for clean inputs; the TTY detection
/// (`std::io::stdout().is_terminal()`) is performed at the call site so this function
/// is testable without a real TTY (avoids PF-014: sanitize renderer inputs, not the
/// rendered frame).
///
/// # Byte-length invariant
///
/// `neutralize_source_for_render` is byte-length-preserving — every substitution
/// produces a replacement of the same UTF-8 byte count — so diff hunk byte offsets
/// remain coherent after substitution on the TTY path. Never use
/// [`mds::sanitize_control_chars`] here: it expands 1–2-byte controls to 6 bytes,
/// desynchronising all offsets that follow.
///
/// # Boundary table entry (consistent with `crates/mds-core/src/lint/diagnostic.rs`)
///
/// | Boundary | Mode | Content |
/// |----------|------|---------|
/// | `--diff` preview output | neutralized, TTY-gated | source excerpts via `neutralize_source_for_render`; piped path returns `Cow::Borrowed` |
#[must_use]
pub(crate) fn preview_text_for(writer_is_tty: bool, text: &str) -> Cow<'_, str> {
    if writer_is_tty {
        neutralize_source_for_render(text)
    } else {
        Cow::Borrowed(text)
    }
}

// ── Diff rendering ───────────────────────────────────────────────────────────

/// Render a unified diff between `original` and `modified` with optional colorization.
///
/// The single shared implementation used by both `fmt --diff` and `lint --diff`.
///
/// When stdout is a TTY, both strings are neutralized via [`preview_text_for`] before
/// diffing so hostile ESC/control bytes in template source cannot inject ANSI commands
/// into the rendered diff (CWE-150, security-11). When piped, the strings pass through
/// unchanged so redirected diff output remains byte-faithful and applicable by
/// `patch`/tooling.
#[must_use]
pub(crate) fn render_unified_diff(original: &str, modified: &str, label: &str) -> String {
    let is_tty = std::io::stdout().is_terminal();
    let original = preview_text_for(is_tty, original);
    let modified = preview_text_for(is_tty, modified);
    let diff = similar::TextDiff::from_lines(original.as_ref(), modified.as_ref());
    let unified = diff
        .unified_diff()
        .context_radius(3)
        .header(label, label)
        .to_string();

    if unified.is_empty() || !is_tty {
        return unified;
    }
    colorize_unified_diff(&unified)
}

/// Colorize a unified diff string with ANSI codes.
///
/// Uses a state machine keyed on the first `@@` hunk marker to correctly color
/// removed (`-`) and added (`+`) lines inside hunks without miscoloring file-header
/// lines (`---`/`+++`) as hunk content when a removed or added line's own content
/// starts with `--` or `++`.
pub(crate) fn colorize_unified_diff(unified: &str) -> String {
    const RED: &str = "\x1b[31m";
    const GREEN: &str = "\x1b[32m";
    const CYAN: &str = "\x1b[36m";
    const RESET: &str = "\x1b[0m";

    let mut out = String::with_capacity(unified.len() + 64);
    let mut in_hunk = false;
    for line in unified.split_inclusive('\n') {
        let color = if line.starts_with("@@") {
            in_hunk = true;
            CYAN
        } else if !in_hunk && (line.starts_with("---") || line.starts_with("+++")) {
            CYAN
        } else if in_hunk && line.starts_with('+') {
            GREEN
        } else if in_hunk && line.starts_with('-') {
            RED
        } else {
            ""
        };
        if color.is_empty() {
            out.push_str(line);
            continue;
        }
        out.push_str(color);
        match line.strip_suffix('\n') {
            Some(stripped) => {
                out.push_str(stripped);
                out.push_str(RESET);
                out.push('\n');
            }
            None => {
                out.push_str(line);
                out.push_str(RESET);
            }
        }
    }
    out
}

/// Sanitize a filesystem path for terminal display (CWE-150 / CWE-117 guard).
///
/// Converts the path to a display string and escapes it with
/// [`mds::escape_path_for_message`] — WIRE mode ([`mds::sanitize_control_chars_wire`])
/// plus `\t`, i.e. every forbidden path character (#265) — so hostile filenames cannot
/// inject ANSI terminal commands (e.g. `ESC[2J`) *or* forge additional status lines,
/// and no status line shows a raw character that a path may not carry.
///
/// # Why WIRE and not HUMAN
///
/// Status lines are single-line by construction: `Clean: {path}`, `Fixed: {path}`,
/// `Compiled to {path}` are emitted unframed and unindented, one per file. POSIX
/// permits a newline inside a filename, and the user never types the name — `mds lint .`
/// discovers it by directory walk. HUMAN mode preserves newlines (so that multi-line
/// diagnostic *messages* keep rendering), which would let a file whose name embeds
/// `<LF>Clean: real.mds<LF>OK: all-fine.mds` emit two attacker-authored lines
/// byte-identical in form to genuine output. A filename is never legitimately
/// multi-line, so escaping the newline to its six-character literal costs nothing and
/// closes the forgery.
///
/// This matches the treatment `files[].file` already gets on the JSON wire surface
/// (`LintResult::to_canonical_json`) and that miette frame headers get via
/// [`mds::named_source_for_render`] — the human status path was the inconsistent one.
///
/// All status-line path interpolations (`Clean:`, `Fixed:`, `Compiled to:`, etc.) in
/// `lint`, `fmt`, and `build` must route through this helper (avoids PF-004 /
/// security-5: unsanitized filename vector in status output).
///
/// Also the CLI's single choke-point for stripping a Windows verbatim prefix
/// (`\\?\C:\…`) before display (#409): a canonicalized `--out-dir` join, or any
/// other canonical path, is passed through [`mds::display_native_path`] first.
/// Off Windows that call is a no-op, so every call site gets the conventional
/// form unconditionally, on every host.
pub(crate) fn safe_path(p: &std::path::Path) -> String {
    safe_file_display(&mds::display_native_path(p).display().to_string())
}

/// [`safe_path`] for a filename that is already a `&str` (e.g. a `LintDiagnostic::file`
/// basename that never became a `Path`).
///
/// Exists so those sites cannot drift into open-coding a different escape mode — the
/// exact PF-004 shape that left `Clean: {filename}` on HUMAN mode while every other
/// status line was on WIRE.
pub(crate) fn safe_file_display(name: &str) -> String {
    mds::escape_path_for_message(name).into_owned()
}

/// WIRE-escape any untrusted value that is interpolated into a **single-line** status,
/// warning, or error line.
///
/// This is the general form of [`safe_path`] / [`safe_file_display`]: the same WIRE
/// escape (those two also escape `\t`, which a path may not carry), for values that are
/// neither a `Path` nor a filename — the cause of an I/O or file-watcher error, with its
/// paths dropped first ([`io_cause`], [`notify_cause`]), an `mds.json` rule name or config
/// value, a `--format` argument, a fix-rejection reason.
///
/// # Why WIRE, on human surfaces too
///
/// Per the governing per-field rule (spec §7.5): **on the diagnostic surfaces — the
/// `"version": 1` JSON wire, CLI status and warning lines, `[file:line:col]` frame
/// headers — untrusted identifiers, filenames and causes are WIRE-escaped, human output
/// included; only *prose* — a diagnostic message or help body — stays HUMAN.** (Source-map
/// paths and `CompileResult.dependencies` are the named carve-out: not diagnostics, not
/// escaped.) The discriminator is whether the
/// value is legitimately multi-line. A rule name, a path, a `--format` value and an
/// `io::Error` never are; a diagnostic body genuinely is. Leaving `\n` raw in the first
/// group buys nothing and lets the value forge a standalone status line that is
/// byte-identical in form to genuine output (CWE-117).
///
/// The surrounding warning prose stays HUMAN — pass the assembled string to
/// [`eprint_warning`], and WIRE-escape each interpolated value with this helper.
///
/// Idempotent (a property of [`mds::sanitize_control_chars_wire`]), so wrapping a value
/// that was already escaped at construction — e.g.
/// `mds::fix::FixOutcome::Rejected.reason` — is a no-op rather than a double escape.
/// That matters: it lets every call site apply the rule unconditionally instead of
/// tracking which values arrived pre-escaped (PF-004).
///
/// Enforced mechanically by `tests/print_discipline.rs`.
pub(crate) fn safe_inline(value: impl std::fmt::Display) -> String {
    mds::sanitize_control_chars_wire(&value.to_string()).into_owned()
}

/// The text [`notify_cause`] shows for a file watcher's own message that names a path.
const WATCHER_ERROR: &str = "file watcher error";

/// The cause an [`std::io::Error`] gives, with any path it carries dropped (#390): what
/// every message `mds` builds around an I/O error interpolates — through [`safe_inline`],
/// like any other value a line interpolates.
///
/// An error the operating system raised displays as the system's description and code
/// (`Permission denied (os error 13)`), and one made from a kind alone, or from a message
/// of std's own, as that kind or message: none of them names a path, so each is shown as
/// it displays. An error that carries a payload — text or an error a library attached —
/// is shown by its kind alone (`permission denied`): the payload may quote a path, as
/// tempfile's does (`… at path "<the temporary file>"`), and its cause chain need not lead
/// back to the error it wraps (tempfile's skips it).
pub(crate) fn io_cause(e: &std::io::Error) -> String {
    match e.get_ref() {
        None => e.to_string(),
        Some(_) => e.kind().to_string(),
    }
}

/// The cause a [`notify::Error`] gives, without the paths it lists (#390) — through
/// [`safe_inline`] in a message, as [`io_cause`]'s is.
///
/// notify displays an error as its kind's text followed by ` about [<paths>]`, the paths
/// it was handed — for `mds watch`, a directory's canonical path. Only the kind's text is
/// shown: an I/O error's through [`io_cause`], notify's own fixed texts in notify's words,
/// and a backend's own message as given (`Input watch path is neither a file nor a
/// directory.` on Windows) unless it carries a path separator, when [`WATCHER_ERROR`]
/// stands for it.
pub(crate) fn notify_cause(e: &notify::Error) -> String {
    use notify::ErrorKind;
    match &e.kind {
        ErrorKind::Io(io) => io_cause(io),
        ErrorKind::Generic(text) if !text.contains(['/', '\\']) => text.clone(),
        ErrorKind::Generic(_) => WATCHER_ERROR.to_owned(),
        ErrorKind::PathNotFound => notify::Error::path_not_found().to_string(),
        ErrorKind::WatchNotFound => notify::Error::watch_not_found().to_string(),
        ErrorKind::InvalidConfig(config) => notify::Error::invalid_config(config).to_string(),
        ErrorKind::MaxFilesWatch => notify::Error::new(ErrorKind::MaxFilesWatch).to_string(),
    }
}

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

/// A unit test that runs again as a child process, for what only a process of its own
/// can show: the panic hook, and the stderr funnel the whole process shares (#389).
#[cfg(test)]
pub(crate) mod child_process {
    /// The variable that makes a test run as the child [`run`] starts.
    const CHILD: &str = "MDS_UNIT_TEST_CHILD";

    /// Run the test `name` again as a child — this test binary, that one test — with
    /// [`CHILD`] set, in a process of its own. The child's `RUST_BACKTRACE` is removed: CI
    /// sets it for every job.
    pub(crate) fn run(name: &str) -> std::process::Output {
        let binary = std::env::current_exe().expect("the test binary's path");
        std::process::Command::new(binary)
            .args([name, "--exact", "--nocapture", "--test-threads=1"])
            .env(CHILD, name)
            .env_remove("RUST_BACKTRACE")
            .output()
            .expect("the child runs")
    }

    /// Whether this process is the child [`run`] started for the test `name`.
    pub(crate) fn is_child(name: &str) -> bool {
        std::env::var_os(CHILD).is_some_and(|value| value == name)
    }

    /// The variable that makes the child's stderr count as a terminal.
    const TERMINAL: &str = "MDS_UNIT_TEST_TERMINAL";

    /// [`run`], with the child's stderr counted as a terminal ([`on_a_terminal`]), so the
    /// test sees the clear that `--clear` makes only on a terminal.
    pub(crate) fn run_on_a_terminal(name: &str) -> std::process::Output {
        let binary = std::env::current_exe().expect("the test binary's path");
        std::process::Command::new(binary)
            .args([name, "--exact", "--nocapture", "--test-threads=1"])
            .env(CHILD, name)
            .env(TERMINAL, "1")
            .env_remove("RUST_BACKTRACE")
            .output()
            .expect("the child runs")
    }

    /// Whether this process is a child that [`run_on_a_terminal`] started.
    pub(crate) fn on_a_terminal() -> bool {
        std::env::var_os(CHILD).is_some() && std::env::var_os(TERMINAL).is_some()
    }

    /// Whether this process's clear is asked for and not made yet (#380).
    pub(crate) fn clear_is_asked() -> bool {
        super::OUTPUT_STATE.clear_is_asked()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn walked_pin_reports_missing_metadata_without_a_panic() {
        let file = Path::new("src").join("a.mds");
        let walk = WalkResult {
            files: vec![file.clone()],
            metadata: std::collections::HashMap::new(),
            excluded_by_default: 0,
        };
        let error = walked_pin(&walk, &file, Path::new("src"), Path::new("canonical")).unwrap_err();
        assert!(matches!(error, mds::MdsError::Io { .. }));
        assert_eq!(
            error.to_string(),
            format!(
                "cannot read {}: missing or invalid walk metadata",
                safe_path(&file)
            )
        );

        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("a.mds");
        std::fs::write(&source, "Hello\n").unwrap();
        let mut complete = walk;
        complete
            .metadata
            .insert(file.clone(), std::fs::symlink_metadata(source).unwrap());
        assert!(walked_pin(&complete, &file, Path::new("src"), dir.path()).is_ok());
        assert!(walked_pin(&complete, &file, Path::new("other"), dir.path()).is_err());
    }

    /// An out-dir written at `/out` and typed as `out`, so every assertion tells the two
    /// forms apart.
    fn out_base() -> OutputBase {
        OutputBase::Dir {
            canonical: PathBuf::from("/out"),
            shown: PathBuf::from("out"),
            below_anchor: 0,
        }
    }

    /// The file `rel` below the anchor `anchor`, named below `shown_anchor` (#160).
    fn target(anchor: &str, shown_anchor: &str, rel: &str) -> WriteTarget {
        WriteTarget::below(Path::new(anchor), Path::new(shown_anchor), Path::new(rel))
    }

    /// #390: a directory-mode output is written below the out-dir's canonical form and
    /// named below its shown form — the same file below each; a map sidecar derives from
    /// both forms alike; and an output next to its source is named as the walk found it.
    /// #160: each is anchored at the out-dir, or at the directory argument next to its
    /// source, with the directories the mirror keeps below that anchor.
    #[test]
    fn an_output_is_written_below_the_canonical_out_dir_and_named_below_the_typed_one() {
        let source = Path::new("/root/sub/page.mds");
        let root = Path::new("/root");
        let out = output_path_for(source, RootPaths::as_typed(root), &out_base(), "md");
        assert_eq!(out, target("/out", "out", "sub/page.md"));
        assert_eq!(
            out.sibling(crate::build::map_path_for),
            target("/out", "out", "sub/page.md.map")
        );
        assert_eq!(
            output_path_for(
                Path::new("src/sub/page.mds"),
                RootPaths::as_typed(Path::new("src")),
                &OutputBase::NextToSource,
                "md"
            ),
            target("src", "src", "sub/page.md")
        );
    }

    /// What mds writes for the messages template `@message user:` / `Hi` / `@end`.
    const HI: &str = "[\n  {\n    \"role\": \"user\",\n    \"content\": \"Hi\"\n  }\n]\n";

    /// What a build writes for the messages template `source` — compiled as a build
    /// compiles it — in `dir`.
    fn compiled_messages(dir: &Path, source: &str) -> String {
        let path = dir.join("chat.mds");
        std::fs::write(&path, source).unwrap();
        let compiled =
            crate::build::compile_to_content(&path, None, true, mds::CompileOptions::default())
                .unwrap();
        assert_eq!(compiled.kind, OutputKind::Messages, "{source:?}");
        compiled.content
    }

    /// Whether `bytes` is proven a messages output mds wrote, read no further than `cap`.
    fn proven(bytes: &[u8], cap: u64) -> bool {
        holds_messages_output(&mut &bytes[..], bytes.len() as u64, cap).unwrap()
    }

    /// #160: a messages output is proven one mds wrote by its exact bytes, and by nothing
    /// less: the same messages formatted or escaped another way, a field more, fewer or in
    /// another order, another shape, bytes that are not UTF-8, and one byte over the cap
    /// are not. Control: what a build writes — a message's quotes, tab and non-ASCII
    /// characters as it escapes them, and the empty array of a template whose messages are
    /// all empty — is.
    #[test]
    fn a_messages_output_is_proven_only_by_the_bytes_mds_writes() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(
            compiled_messages(dir.path(), "@message user:\nHi\n@end\n"),
            HI
        );
        let escaped = compiled_messages(
            dir.path(),
            "@message system:\nSay \"hi\"\tthen go\n@end\n@message user:\nCaf\u{e9} \u{2014} 1 < 2\n@end\n",
        );
        // A messages template whose only message has an empty body has none to write.
        let none = compiled_messages(dir.path(), "@message user:\n  \n@end\n");
        assert_eq!(none, "[]\n", "mds writes an empty messages output");
        for (name, output) in [
            ("HI", HI),
            ("escaped", escaped.as_str()),
            ("none", none.as_str()),
        ] {
            assert!(
                proven(output.as_bytes(), mds::MAX_FILE_SIZE),
                "control: {name} {output:?}"
            );
        }

        let backslash = '\\';
        let not_written_by_mds: Vec<(&str, Vec<u8>)> = vec![
            (
                "compact",
                b"[{\"role\":\"user\",\"content\":\"Hi\"}]\n".to_vec(),
            ),
            ("no final newline", HI.trim_end_matches('\n').into()),
            ("CRLF", HI.replace('\n', "\r\n").into()),
            (
                "a byte-order mark",
                [&b"\xEF\xBB\xBF"[..], HI.as_bytes()].concat(),
            ),
            (
                "another escape",
                HI.replace("\"Hi\"", &format!("\"H{backslash}u0069\""))
                    .into(),
            ),
            (
                "a field more",
                HI.replace("\"Hi\"\n", "\"Hi\",\n    \"name\": \"x\"\n")
                    .into(),
            ),
            (
                "a field fewer",
                HI.replace(",\n    \"content\": \"Hi\"", "").into(),
            ),
            (
                "fields in another order",
                b"[\n  {\n    \"content\": \"Hi\",\n    \"role\": \"user\"\n  }\n]\n".to_vec(),
            ),
            ("content not a string", HI.replace("\"Hi\"", "1").into()),
            (
                "an object",
                b"{\n  \"role\": \"user\",\n  \"content\": \"Hi\"\n}\n".to_vec(),
            ),
            ("strings", b"[\n  \"Hi\"\n]\n".to_vec()),
            ("null", b"null\n".to_vec()),
            ("empty", Vec::new()),
            ("a raw control character", HI.replace("Hi", "H\u{1}").into()),
        ];
        for (name, bytes) in not_written_by_mds {
            assert!(!proven(&bytes, mds::MAX_FILE_SIZE), "{name}: {bytes:?}");
        }
        let mut not_utf8 = HI.as_bytes().to_vec();
        let at = HI.find("Hi").unwrap() + 1;
        not_utf8[at] = 0xFF;
        assert!(!proven(&not_utf8, mds::MAX_FILE_SIZE), "not UTF-8");

        let size = HI.len() as u64;
        assert!(
            proven(HI.as_bytes(), size),
            "control: a file of exactly the cap"
        );
        assert!(!proven(HI.as_bytes(), size - 1), "one byte over the cap");
        assert!(
            !holds_messages_output(&mut HI.as_bytes(), size + 1, size).unwrap(),
            "a size over the cap"
        );
        assert!(
            !holds_messages_output(&mut HI.as_bytes(), 1, size - 1).unwrap(),
            "a reader holding more than the cap whatever its size said"
        );
    }

    /// #160: a stale output whose directory below the anchor is a symlink is not removed
    /// through it, though it holds exactly what mds writes: the removal is refused
    /// (`mds::io`), naming the stale output and the link as shown, and the file of that
    /// name where the link leads is left. Control: the same stale output below a real
    /// directory is removed.
    #[cfg(unix)]
    #[test]
    fn a_stale_output_is_never_removed_through_a_symlink_below_its_anchor() {
        let dir = tempfile::tempdir().unwrap();
        let anchor = dir.path().join("out");
        std::fs::create_dir_all(anchor.join("real")).unwrap();
        std::fs::create_dir(dir.path().join("victim")).unwrap();
        std::os::unix::fs::symlink("../victim", anchor.join("sub")).unwrap();
        let victim = dir.path().join("victim/x.json");
        std::fs::write(&victim, HI).unwrap();

        let written = WriteTarget::below(&anchor, Path::new("out"), Path::new("sub/x.md"));
        let result = probe_and_remove_stale(&written, OutputKind::Markdown, true);
        assert_eq!(
            std::fs::read_to_string(&victim).ok().as_deref(),
            Some(HI),
            "nothing is removed through the symlink"
        );
        match result {
            Err(mds::MdsError::Io { message }) => assert_eq!(
                message,
                "could not remove stale output out/sub/x.json: \
                 refusing to follow a symlink at out/sub"
            ),
            other => panic!("want Err(MdsError::Io {{ .. }}); got {other:?}"),
        }

        // Control: below a real directory, the stale output is removed.
        let real = anchor.join("real/x.json");
        std::fs::write(&real, HI).unwrap();
        let written = WriteTarget::below(&anchor, Path::new("out"), Path::new("real/x.md"));
        assert!(probe_and_remove_stale(&written, OutputKind::Markdown, true).is_ok());
        assert!(!real.exists(), "control: the stale output is removed");
    }

    /// #160, #157: a stale output proven mds's whose removal fails is an `mds::io` error
    /// naming it as shown, and the file is left; a build reports it and exits 2. Control:
    /// once its directory is writable again, it is removed.
    ///
    /// Unix-only: a mode makes the directory read-only; skipped where it does not (as
    /// root).
    #[cfg(unix)]
    #[test]
    fn a_proven_stale_output_that_cannot_be_removed_is_an_io_error() {
        use std::os::unix::fs::PermissionsExt as _;

        let dir = tempfile::tempdir().unwrap();
        let anchor = dir.path().join("out");
        std::fs::create_dir(&anchor).unwrap();
        let stale = anchor.join("x.json");
        std::fs::write(&stale, HI).unwrap();
        let written = WriteTarget::below(&anchor, Path::new("out"), Path::new("x.md"));
        let mode = |mode| std::fs::set_permissions(&anchor, std::fs::Permissions::from_mode(mode));
        mode(0o555).unwrap();
        if std::fs::write(anchor.join(".probe"), "").is_ok() {
            mode(0o755).unwrap();
            ewriteln!("skipped: out is writable at mode 0o555 (running as root?)");
            return;
        }
        let result = probe_and_remove_stale(&written, OutputKind::Markdown, true);
        mode(0o755).unwrap();

        match result {
            Err(mds::MdsError::Io { message }) => assert_eq!(
                message,
                format!(
                    "could not remove stale output out/x.json: {}",
                    std::io::Error::from(rustix::io::Errno::ACCESS)
                )
            ),
            other => panic!("want Err(MdsError::Io {{ .. }}); got {other:?}"),
        }
        assert_eq!(std::fs::read_to_string(&stale).ok().as_deref(), Some(HI));
        assert!(probe_and_remove_stale(&written, OutputKind::Markdown, true).is_ok());
        assert!(!stale.exists(), "control: the stale output is removed");
    }

    /// #160, #157: the same on Windows — a stale output proven mds's whose removal fails is
    /// an `mds::io` error naming it as shown, and the file is left. Control: once nothing
    /// holds it, it is removed.
    ///
    /// Windows-only — it runs in the Windows CI leg, never on a unix machine. There, a file
    /// held open by a handle that does not share deletion cannot be removed while it is
    /// held; a read-only file is no such case, since std removes one on Windows.
    #[cfg(windows)]
    #[test]
    fn a_proven_stale_output_held_open_on_windows_is_an_io_error() {
        use std::os::windows::fs::OpenOptionsExt as _;
        /// `FILE_SHARE_READ`: another handle may read the file, never delete it.
        const FILE_SHARE_READ: u32 = 0x1;
        /// `ERROR_SHARING_VIOLATION`: what removing a file another handle denies that gives.
        const ERROR_SHARING_VIOLATION: i32 = 32;

        let dir = tempfile::tempdir().unwrap();
        let anchor = dir.path().join("out");
        std::fs::create_dir(&anchor).unwrap();
        let stale = anchor.join("x.json");
        std::fs::write(&stale, HI).unwrap();
        let written = WriteTarget::below(&anchor, Path::new("out"), Path::new("x.md"));
        let held = std::fs::OpenOptions::new()
            .read(true)
            .share_mode(FILE_SHARE_READ)
            .open(&stale)
            .unwrap();
        let result = probe_and_remove_stale(&written, OutputKind::Markdown, true);
        drop(held);

        match result {
            Err(mds::MdsError::Io { message }) => assert_eq!(
                message,
                format!(
                    "could not remove stale output {}: {}",
                    Path::new("out").join("x.json").display(),
                    std::io::Error::from_raw_os_error(ERROR_SHARING_VIOLATION)
                )
            ),
            other => panic!("want Err(MdsError::Io {{ .. }}); got {other:?}"),
        }
        assert_eq!(std::fs::read_to_string(&stale).ok().as_deref(), Some(HI));
        assert!(probe_and_remove_stale(&written, OutputKind::Markdown, true).is_ok());
        assert!(!stale.exists(), "control: the stale output is removed");
    }

    /// #160: a stale `.json` whose bytes are not UTF-8, or that is larger than the read
    /// cap (10 MiB), is not proven mds's and is kept by a directory build's cleanup, though
    /// it holds what mds writes for a messages output but for one byte, or would hold
    /// exactly that but for its size. Control: the same messages output of exactly the
    /// cap, and the output with its byte restored, are each removed. Built at run time.
    #[test]
    fn a_stale_json_that_is_not_utf8_or_over_the_read_cap_is_kept() {
        let dir = tempfile::tempdir().unwrap();
        let anchor = dir.path().join("out");
        std::fs::create_dir(&anchor).unwrap();
        let stale = anchor.join("x.json");
        let written = WriteTarget::below(&anchor, Path::new("out"), Path::new("x.md"));
        let kept_or_removed = |bytes: &[u8]| {
            std::fs::write(&stale, bytes).unwrap();
            assert!(probe_and_remove_stale(&written, OutputKind::Markdown, true).is_ok());
            if stale.exists() {
                "kept"
            } else {
                "removed"
            }
        };

        let mut not_utf8 = HI.as_bytes().to_vec();
        not_utf8[HI.find("Hi").unwrap() + 1] = 0xFF;
        assert_eq!(kept_or_removed(&not_utf8), "kept", "not UTF-8");
        assert_eq!(kept_or_removed(HI.as_bytes()), "removed", "control: {HI:?}");

        // What mds writes for one message whose content is `len` bytes of `a`.
        let output = |len: usize| {
            let message = WrittenMessage {
                role: "user".to_owned(),
                content: "a".repeat(len),
            };
            crate::build::messages_json(&[message]).unwrap()
        };
        let cap = usize::try_from(mds::MAX_FILE_SIZE).unwrap();
        let frame = output(0).len();
        let over = output(cap + 1 - frame);
        assert_eq!(over.len(), cap + 1, "one byte over the cap");
        assert_eq!(kept_or_removed(over.as_bytes()), "kept", "over the cap");
        let at_cap = output(cap - frame);
        assert_eq!(at_cap.len(), cap, "exactly the cap");
        assert_eq!(
            kept_or_removed(at_cap.as_bytes()),
            "removed",
            "control: exactly the cap"
        );
    }

    /// #390: a root walked in another form than it was typed in — `mds watch` walks the
    /// canonical directory — names an output next to its source, and the stem it is named
    /// from, below the directory as typed, while both are written and probed below the
    /// walked form; under an out-dir the typed root changes nothing. A source outside the
    /// walked root has no typed form and keeps its own.
    #[test]
    fn an_output_next_to_its_source_is_named_below_the_root_as_typed() {
        let root = RootPaths {
            typed: Path::new("src"),
            walked: Path::new("/root"),
        };
        let source = Path::new("/root/sub/page.mds");
        let next_to = OutputBase::NextToSource;

        assert_eq!(
            output_path_for(source, root, &next_to, "md"),
            target("/root", "src", "sub/page.md")
        );
        assert_eq!(
            output_stem_for(source, root, &next_to),
            target("/root", "src", "sub/page")
        );
        assert_eq!(
            output_path_for(source, root, &out_base(), "json"),
            target("/out", "out", "sub/page.json")
        );
        assert_eq!(
            output_stem_for(source, root, &out_base()),
            target("/out", "out", "sub/page")
        );
        assert_eq!(
            output_stem_for(Path::new("/other/page.mds"), root, &next_to),
            WriteTarget::as_typed(PathBuf::from("/other/page"))
        );
    }

    /// #390: `resolve_output_base` fixes both forms of the out-dir: the canonical form is
    /// absolute, the shown form is the out-dir exactly as typed; `mds.json`'s
    /// `build.output_dir` is resolved below the config directory and shown below the
    /// directory `mds.json` was reached by. #160: `--out-dir` is its writes' anchor, and
    /// `build.output_dir`'s own directories lie below the config directory, theirs.
    #[test]
    fn the_out_dir_is_shown_as_typed_and_resolved_absolute() {
        let typed = PathBuf::from("out");
        match resolve_output_base(Some(&typed), &None).expect("a relative out-dir resolves") {
            OutputBase::Dir {
                canonical,
                shown,
                below_anchor,
            } => {
                assert!(canonical.is_absolute(), "canonical: {canonical:?}");
                assert!(canonical.ends_with("out"), "canonical: {canonical:?}");
                assert_eq!(shown, typed);
                assert_eq!(below_anchor, 0);
            }
            other => panic!("want Dir; got {other:?}"),
        }

        let config = Some(ProjectConfig {
            config: crate::build::MdsConfig {
                build: crate::build::BuildConfig {
                    output_dir: Some("dist".to_string()),
                    ..Default::default()
                },
                ..Default::default()
            },
            dir: PathBuf::from("/project"),
            shown_dir: PathBuf::from("src/.."),
        });
        match resolve_output_base(None, &config).expect("a config output_dir resolves") {
            OutputBase::Dir {
                canonical,
                shown,
                below_anchor,
            } => {
                assert_eq!(canonical, Path::new("/project").join("dist"));
                assert_eq!(shown, Path::new("src/..").join("dist"));
                assert_eq!(below_anchor, 1);
            }
            other => panic!("want Dir; got {other:?}"),
        }
    }

    /// #160: a directory-mode output below `mds.json`'s `build.output_dir` is anchored at
    /// the directory `mds.json` is in, `build.output_dir`'s own directories below it — a
    /// `.` adds none — and an absolute value is refused before it can name an anchor.
    #[test]
    fn a_build_output_dir_lies_below_the_config_directory() {
        let config = |output_dir: &str| {
            Some(ProjectConfig {
                config: crate::build::MdsConfig {
                    build: crate::build::BuildConfig {
                        output_dir: Some(output_dir.to_string()),
                        ..Default::default()
                    },
                    ..Default::default()
                },
                dir: PathBuf::from("/project"),
                shown_dir: PathBuf::from("."),
            })
        };
        let root = PathBuf::from("/project/src");
        let source = root.join("sub").join("a.mds");
        for (output_dir, rel) in [("dist", "dist/sub/a.md"), ("./a/b", "a/b/sub/a.md")] {
            let base = resolve_output_base(None, &config(output_dir)).expect("relative");
            assert_eq!(
                output_path_for(&source, RootPaths::as_typed(&root), &base, "md"),
                target("/project", ".", rel),
                "{output_dir:?}"
            );
        }
        let absolute = std::env::temp_dir().join("dist");
        let refused = resolve_output_base(None, &config(absolute.to_str().unwrap()))
            .expect_err("an absolute output_dir is refused")
            .to_string();
        assert!(refused.contains("must be a relative path"), "{refused}");
    }

    // output_path_for with "json" and "md" extensions.
    #[test]
    fn output_path_for_json_extension_dir_mode() {
        let source = PathBuf::from("/root/src/chat.mds");
        let root = PathBuf::from("/root");
        let base = out_base();
        let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "json");
        assert_eq!(result, target("/out", "out", "src/chat.json"));
    }

    #[test]
    fn output_path_for_md_extension_dir_mode() {
        let source = PathBuf::from("/root/src/page.mds");
        let root = PathBuf::from("/root");
        let base = out_base();
        let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "md");
        assert_eq!(result, target("/out", "out", "src/page.md"));
    }

    #[test]
    fn output_path_for_next_to_source() {
        let source = PathBuf::from("/root/src/page.mds");
        let root = PathBuf::from("/root");
        let base = OutputBase::NextToSource;
        let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "md");
        assert_eq!(result, target("/root", "/root", "src/page.md"));
    }

    #[test]
    fn output_path_for_next_to_source_json() {
        let source = PathBuf::from("/root/src/chat.mds");
        let root = PathBuf::from("/root");
        let base = OutputBase::NextToSource;
        let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "json");
        assert_eq!(result, target("/root", "/root", "src/chat.json"));
    }

    // The `..` containment guard still holds: when the source is outside the root, the
    // output must be `base/stem.ext`, not escaped.
    #[test]
    fn output_path_for_outside_root_falls_back_to_flat() {
        let source = PathBuf::from("/other/page.mds");
        let root = PathBuf::from("/root");
        let base = out_base();
        let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "md");
        // Must be inside /out, not escape to /other.
        assert!(
            result.path.starts_with("/out"),
            "output must be inside /out; got {result:?}"
        );
        assert_eq!(result, target("/out", "out", "page.md"));
    }

    /// Body of the first `fn` whose header starts with `header`, brace-matched from the
    /// first `{` after it. Used by the lexical guard below; `None` when the header is
    /// absent, which the caller turns into a non-vacuity failure.
    fn fn_body(src: &str, header: &str) -> Option<String> {
        let start = src.find(header)?;
        let open = start + src[start..].find('{')?;
        let mut depth = 0usize;
        for (i, c) in src[open..].char_indices() {
            match c {
                '{' => depth += 1,
                '}' => {
                    depth -= 1;
                    if depth == 0 {
                        return Some(src[open..open + i + 1].to_string());
                    }
                }
                _ => {}
            }
        }
        None
    }

    /// #217: the `Dir`-mode oracles must be able to say WHICH arm produced a stem — the
    /// subtree mirror, or the out-of-root flatten that drops the subtree and lets two
    /// sources with the same file name collide.
    ///
    /// Both arms are asserted: an assertion that only ever observes `Flattened` would be
    /// satisfied by a classifier that returns it unconditionally.
    #[test]
    fn mirror_stem_classifies_out_of_root_as_flattened() {
        assert_eq!(
            mirror_stem(Path::new("/other/page.mds"), Path::new("/root")),
            MirroredStem::Flattened(PathBuf::from("page")),
            "a source outside the root loses its subtree and must say so"
        );
        assert_eq!(
            mirror_stem(Path::new("/root/a/page.mds"), Path::new("/root")),
            MirroredStem::Mirrored(PathBuf::from("a/page")),
            "a source below the root keeps its subtree and must NOT be reported"
        );
    }

    /// #217: a stem-less source must never hand `d.join` an absolute argument.
    ///
    /// `Path::new("/").file_stem()` is `None`, and the fallback used to be
    /// `source.as_os_str()` — `"/"`. `Path::new("/out").join("/")` re-roots to `"/"`,
    /// and the write oracle then built `"/.md"`. Neither is inside the out-dir, and
    /// neither is a path any source would legitimately compile to.
    ///
    /// `output_path_for_outside_root_falls_back_to_flat` above is the control: a source
    /// that HAS a stem still flattens to `<out-dir>/<stem>.<ext>`.
    #[test]
    fn stemless_source_never_escapes_out_dir() {
        let source = Path::new("/");
        let root = Path::new("/root");
        let base = out_base();

        assert_eq!(
            output_base_no_ext(source, root, &base),
            PathBuf::from("/out/output"),
            "the probe oracle must keep a stem-less source inside the out-dir"
        );
        assert_eq!(
            output_path_for(source, RootPaths::as_typed(root), &base, "md"),
            target("/out", "out", "output.md"),
            "the write oracle must not join an absolute stem"
        );
    }

    /// The flat name a mirror that leaves the out-dir falls back to is flagged flattened,
    /// so the write oracle warns for it as it warns for a source outside the root (#217).
    #[test]
    fn the_flat_fallback_of_a_mirror_is_flagged_flattened() {
        assert_eq!(
            flat_output(Path::new("/root/../x/a.mds"), "md"),
            (PathBuf::from("a.md"), true)
        );
        assert_eq!(
            flat_output(Path::new("/"), "json"),
            (PathBuf::from("output.json"), true),
            "a stem-less source keeps a relative name"
        );
    }

    /// A source whose path climbs out of the root by `..` mirrors to a name that is not
    /// below the out-dir. A release build then writes it flat and flags it flattened (#160).
    /// A debug build stops on the assertion before that, so the test runs in a release
    /// build only.
    #[cfg(not(debug_assertions))]
    #[test]
    fn a_mirror_that_leaves_the_out_dir_is_written_flat_and_reported() {
        assert_eq!(
            mirrored_output(Path::new("/root/../x/a.mds"), Path::new("/root"), "md"),
            (PathBuf::from("a.md"), true),
            "the flat name is returned with the flag that makes the caller warn"
        );
    }

    /// #217: the out-of-root flatten is reported from the WRITE oracle only.
    ///
    /// `output_base_no_ext` is a probe: a directory build takes a source map's base from
    /// it, for a stem no output is written at. A warning there would fire on bookkeeping
    /// rather than on a write.
    /// `output_path_for` is called once per output path actually computed for a write,
    /// so that is where the report belongs.
    ///
    /// Lexical, because the property being pinned is exactly "which function contains
    /// the call". Both headers must be found, or the two negative assertions would pass
    /// on an empty string.
    #[test]
    fn flatten_warning_lives_in_the_write_oracle_only() {
        const SRC: &str = include_str!("output.rs");
        const NEEDLE: &str = "is outside the build root";

        let oracle = fn_body(SRC, "fn output_path_for(")
            .expect("non-vacuity: fn output_path_for must be present in this file");

        assert!(
            oracle.contains("eprint_warning("),
            "the write oracle must report the flattened arm; body: {oracle}"
        );
        assert!(
            oracle.contains(NEEDLE),
            "the write oracle's report must name the out-of-root condition; body: {oracle}"
        );
        // Both probes: the stem, and the stem in both forms that an output beside its
        // source is named from (#390).
        for header in ["fn output_base_no_ext(", "fn output_stem_for("] {
            let probe = fn_body(SRC, header)
                .unwrap_or_else(|| panic!("non-vacuity: {header} must be present in this file"));
            assert!(
                !probe.contains("eprint_warning("),
                "the probe oracle must stay silent — it runs on bookkeeping, not on writes; \
                 body: {probe}"
            );
            assert!(
                !probe.contains(NEEDLE),
                "the probe oracle must not carry the report text either; body: {probe}"
            );
        }
    }

    /// The `.<name>.tmp-<pid>-<n>` temp files an atomic write leaves in flight must
    /// never be collected as sources. The suffix sits AFTER the `.mds`, so
    /// `Path::extension()` is the `tmp-…` component and the walker's extension gate
    /// rejects it — the same gate the dir-mode watch filter uses.
    ///
    /// The second half is the non-vacuity control: a name whose `.mds` is genuinely
    /// last IS collected, so the first assertion is not passing on an empty walk.
    #[test]
    fn collect_mds_files_ignores_write_atomic_temp_names() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("t.mds"), "real").unwrap();
        std::fs::write(dir.path().join(".t.mds.tmp-4242-7"), "in flight").unwrap();
        let files = collect_mds_files(dir.path(), 64, None);
        assert_eq!(files.len(), 1, "temp file must not be collected: {files:?}");
        // Non-vacuity: the inverted name IS collected.
        std::fs::write(dir.path().join(".tmp-4242-8.t.mds"), "wrong shape").unwrap();
        assert_eq!(collect_mds_files(dir.path(), 64, None).len(), 2);
    }

    /// The walk visits each directory's entries by name, on every platform: a file beside a
    /// directory comes before the directory's files when its name sorts first, and after
    /// them when it sorts last. `read_dir` order is not sorted on most Linux filesystems,
    /// and `mds fmt` of a directory rewrites and reports in walk order.
    #[test]
    fn collect_mds_files_visits_each_directory_by_name() {
        let dir = tempfile::tempdir().unwrap();
        // Created in reverse name order, so creation order is not name order.
        for name in ["z.mds", "m/b.mds", "m/a.mds", "a.mds"] {
            let path = dir.path().join(name);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, "x\n").unwrap();
        }
        let names: Vec<_> = collect_mds_files(dir.path(), 64, None)
            .iter()
            .map(|path| path.strip_prefix(dir.path()).unwrap().to_path_buf())
            .collect();
        let want: Vec<PathBuf> = ["a.mds", "m/a.mds", "m/b.mds", "z.mds"]
            .iter()
            .map(PathBuf::from)
            .collect();
        assert_eq!(names, want);
    }

    #[test]
    fn is_partial_detects_underscore_prefix() {
        assert!(is_partial(Path::new("/dir/_partial.mds")));
        assert!(!is_partial(Path::new("/dir/main.mds")));
        assert!(!is_partial(Path::new("/dir/not_partial.mds")));
    }

    #[test]
    fn partials_only_answers() {
        assert_eq!(partials_only(&[]), None);
        assert_eq!(partials_only(&[PathBuf::from("_a.mds")]), Some(1));
        assert_eq!(
            partials_only(&[PathBuf::from("_a.mds"), PathBuf::from("b.mds")]),
            None
        );
        assert_eq!(
            partials_only(&[PathBuf::from("_a.mds"), PathBuf::from("_b.mds")]),
            Some(2)
        );
    }

    // ── is_default_excluded_dir ───────────────────────────────────────────────

    #[test]
    fn hidden_dir_is_excluded() {
        assert!(is_default_excluded_dir(".git"));
        assert!(is_default_excluded_dir(".cache"));
        assert!(is_default_excluded_dir(".hidden"));
    }

    #[test]
    fn node_modules_is_excluded() {
        assert!(is_default_excluded_dir("node_modules"));
    }

    #[test]
    fn ordinary_dirs_are_not_excluded() {
        assert!(!is_default_excluded_dir("src"));
        assert!(!is_default_excluded_dir("prompts"));
        assert!(!is_default_excluded_dir("templates"));
    }

    // ── is_within_default_excluded_dir ───────────────────────────────────────

    #[test]
    fn path_inside_node_modules_is_excluded() {
        assert!(is_within_default_excluded_dir(
            Path::new("/root"),
            Path::new("/root/node_modules/foo.mds")
        ));
    }

    #[test]
    fn path_inside_git_dir_is_excluded() {
        assert!(is_within_default_excluded_dir(
            Path::new("/root"),
            Path::new("/root/.git/config")
        ));
    }

    #[test]
    fn path_inside_hidden_subdir_is_excluded() {
        assert!(is_within_default_excluded_dir(
            Path::new("/root"),
            Path::new("/root/.cache/something.mds")
        ));
    }

    #[test]
    fn normal_path_under_root_is_not_excluded() {
        assert!(!is_within_default_excluded_dir(
            Path::new("/root"),
            Path::new("/root/src/main.mds")
        ));
    }

    #[test]
    fn hidden_file_at_root_level_is_not_excluded() {
        // Hidden files at the top level are not inside an excluded DIR.
        assert!(!is_within_default_excluded_dir(
            Path::new("/root"),
            Path::new("/root/.dotfile.mds")
        ));
    }

    #[test]
    fn path_outside_root_is_not_excluded() {
        // Paths not under root at all are not affected by the root-relative check.
        assert!(!is_within_default_excluded_dir(
            Path::new("/root"),
            Path::new("/other/node_modules/foo.mds")
        ));
    }

    // ── collect_mds_files walker exclusions ───────────────────────────────────

    #[test]
    fn walker_skips_node_modules_subdir() {
        let dir = tempfile::tempdir().unwrap();
        // Create a normal .mds file and one inside node_modules.
        std::fs::write(dir.path().join("main.mds"), "hello").unwrap();
        let nm = dir.path().join("node_modules");
        std::fs::create_dir(&nm).unwrap();
        std::fs::write(nm.join("lib.mds"), "lib").unwrap();

        let files = collect_mds_files(dir.path(), 64, None);
        assert_eq!(
            files.len(),
            1,
            "node_modules/lib.mds should be excluded; found: {files:?}"
        );
        assert!(files[0].ends_with("main.mds"));
    }

    #[test]
    fn walker_skips_hidden_subdir() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("main.mds"), "hello").unwrap();
        let hidden = dir.path().join(".git");
        std::fs::create_dir(&hidden).unwrap();
        std::fs::write(hidden.join("config.mds"), "not a real file").unwrap();

        let files = collect_mds_files(dir.path(), 64, None);
        assert_eq!(
            files.len(),
            1,
            ".git/*.mds should be excluded; found: {files:?}"
        );
    }

    #[test]
    fn walker_collects_hidden_file_at_root_level() {
        // Hidden FILES (not directories) at the traversed level are still collected.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("main.mds"), "hello").unwrap();
        std::fs::write(dir.path().join(".dotfile.mds"), "dot").unwrap();

        let mut files = collect_mds_files(dir.path(), 64, None);
        files.sort();
        assert_eq!(
            files.len(),
            2,
            "hidden file should still be collected; found: {files:?}"
        );
    }

    #[test]
    fn walker_processes_explicitly_passed_hidden_root() {
        // The root dir itself is always processed even if its name starts with '.'.
        let dir = tempfile::tempdir().unwrap();
        let hidden_root = dir.path().join(".myhidden");
        std::fs::create_dir(&hidden_root).unwrap();
        std::fs::write(hidden_root.join("template.mds"), "hello").unwrap();

        let files = collect_mds_files(&hidden_root, 64, None);
        assert_eq!(
            files.len(),
            1,
            "explicitly-passed hidden root should be processed; found: {files:?}"
        );
    }

    // ── collect_mds_files_detailed / WalkResult ───────────────────────────────

    #[test]
    fn walk_result_empty_dir_has_zero_excluded() {
        let dir = tempfile::tempdir().unwrap();
        let result = collect_mds_files_detailed(dir.path(), 64, None);
        assert_eq!(result.files.len(), 0);
        assert_eq!(
            result.excluded_by_default, 0,
            "genuinely empty dir must have 0 excluded"
        );
    }

    #[test]
    fn walk_result_all_excluded_counts_skipped_files() {
        let dir = tempfile::tempdir().unwrap();
        // All files inside a hidden dir → excluded_by_default > 0, files empty.
        let hidden = dir.path().join(".prompts");
        std::fs::create_dir(&hidden).unwrap();
        std::fs::write(hidden.join("a.mds"), "a").unwrap();
        std::fs::write(hidden.join("b.mds"), "b").unwrap();

        let result = collect_mds_files_detailed(dir.path(), 64, None);
        assert_eq!(result.files.len(), 0, "no files should be in results");
        assert_eq!(
            result.excluded_by_default, 2,
            "excluded_by_default must equal the count of skipped .mds files; got {}",
            result.excluded_by_default
        );
    }

    #[test]
    fn walk_result_mixed_counts_excluded_and_collects_normal() {
        let dir = tempfile::tempdir().unwrap();
        // One normal file + one in node_modules.
        std::fs::write(dir.path().join("normal.mds"), "hello").unwrap();
        let nm = dir.path().join("node_modules");
        std::fs::create_dir(&nm).unwrap();
        std::fs::write(nm.join("excluded.mds"), "lib").unwrap();

        let result = collect_mds_files_detailed(dir.path(), 64, None);
        assert_eq!(result.files.len(), 1, "only normal.mds should be collected");
        assert_eq!(
            result.excluded_by_default, 1,
            "one file in node_modules should be counted as excluded"
        );
    }

    // ── is_within_default_excluded_dir single-component edge case ─────────────

    #[test]
    fn single_component_path_is_not_inside_excluded_dir() {
        // rel = "foo.mds" (single component): rel.parent() = Some(""), which has
        // no file_name(), so the loop terminates without false-positive.
        assert!(!is_within_default_excluded_dir(
            Path::new("/root"),
            Path::new("/root/foo.mds")
        ));
    }

    #[test]
    fn output_base_no_ext_dir_mode() {
        let source = PathBuf::from("/root/src/chat.mds");
        let root = PathBuf::from("/root");
        let base = out_base();
        let result = output_base_no_ext(&source, &root, &base);
        assert_eq!(result, PathBuf::from("/out/src/chat"));
    }

    #[test]
    fn output_base_no_ext_next_to_source() {
        let source = PathBuf::from("/root/src/chat.mds");
        let root = PathBuf::from("/root");
        let base = OutputBase::NextToSource;
        let result = output_base_no_ext(&source, &root, &base);
        assert_eq!(result, PathBuf::from("/root/src/chat"));
    }

    // ── preview_text_for: TTY-gated source neutralization (security-11) ──────────

    /// T-12a [security-11 / PF-013]: preview_text_for(true, hostile) neutralizes ESC
    /// and preserves byte length (so diff hunks remain coherent after substitution).
    ///
    /// Positive assertion required by PF-013: the neutralized form MUST be present,
    /// not merely asserted absent in the raw form.
    #[test]
    fn preview_text_for_tty_neutralizes_esc_preserves_byte_length() {
        let hostile = "hello\x1bworld"; // ESC (U+001B) is 1-byte C0
        let result = preview_text_for(true, hostile);
        // Byte-length invariant: neutralize_source_for_render is byte-length-preserving.
        assert_eq!(
            result.len(),
            hostile.len(),
            "byte length must be preserved on TTY path"
        );
        // ESC must be absent from TTY output (security gate).
        assert!(
            !result.contains('\x1b'),
            "raw ESC must be absent from TTY output; got: {result:?}"
        );
        // PF-013 positive assertion: the substituted '?' must be present.
        assert!(
            result.contains('?'),
            "ESC must be replaced with '?' on TTY path; got: {result:?}"
        );
    }

    /// T-12b [security-11 / PF-013]: preview_text_for(false, ...) returns Cow::Borrowed
    /// so piped diff output is byte-identical to the raw source (patch/tooling safety).
    #[test]
    fn preview_text_for_not_tty_returns_borrowed_passthrough() {
        let hostile = "hello\x1bworld";
        let result = preview_text_for(false, hostile);
        // Must be Cow::Borrowed — no allocation, byte-identical to input.
        assert!(
            matches!(result, Cow::Borrowed(_)),
            "piped path must return Cow::Borrowed (no allocation); got Owned"
        );
        assert_eq!(
            result.as_ref(),
            hostile,
            "piped path must be byte-identical to input"
        );
    }

    /// T-12c [security-11 / PF-013]: preview_text_for(true, clean) returns unchanged content
    /// because neutralize_source_for_render returns Cow::Borrowed for clean inputs.
    #[test]
    fn preview_text_for_tty_clean_string_unchanged() {
        let clean = "hello world\n";
        let result = preview_text_for(true, clean);
        assert_eq!(
            result.as_ref(),
            clean,
            "clean string must be unchanged on TTY path"
        );
    }

    // ── safe_path: CWE-150 status-line guard (security-5/6) ──────────────────────

    /// T-11a [security-5 / PF-013]: safe_path escapes a raw ESC byte in a filename
    /// to the 6-char \\uXXXX literal so it cannot inject ANSI into a status line.
    #[test]
    fn safe_path_sanitizes_esc_byte() {
        let raw = format!("dir/fo{}o.mds", '\x1b');
        let p = std::path::Path::new(&raw);
        let result = safe_path(p);
        assert!(
            !result.contains('\x1b'),
            "raw ESC must be absent from safe_path output"
        );
        assert!(
            result.contains("\\u001B"),
            "ESC must be escaped to \\u001B; got: {result:?}"
        );
    }

    /// T-11b [security-5 / PF-013]: safe_path passes a clean path through unchanged
    /// (no unnecessary allocation or mutation).
    #[test]
    fn safe_path_passes_clean_path_unchanged() {
        let p = std::path::Path::new("dir/normal.mds");
        assert_eq!(safe_path(p), "dir/normal.mds");
    }

    /// #265: a path is escaped for the whole forbidden-path class, TAB included —
    /// WIRE mode alone leaves a TAB raw, and a status line showing a path must carry
    /// none of the 80 codepoints.
    #[test]
    fn safe_path_escapes_every_forbidden_char_tab_included() {
        for ch in ['\t', '\n', '\x1b', '\u{202E}'] {
            let raw = format!("out{ch}dir/in.md");
            let got = safe_path(std::path::Path::new(&raw));
            assert!(!got.contains(ch), "U+{:04X}: {got:?}", u32::from(ch));
            assert_eq!(
                got,
                format!("out\\u{:04X}dir/in.md", u32::from(ch)),
                "U+{:04X}",
                u32::from(ch)
            );
        }
    }

    // ── T-10a/b/c: neutralize_source_for_render + colour path (── PF-014) ────────

    /// T-10a [PF-014 / AC-F2]: neutralize_source_for_render removes C0 controls
    /// (except \n/\t), DEL, and 2-byte C1 controls while preserving total byte length
    /// so that miette span offsets remain valid after substitution.
    #[test]
    fn neutralize_source_removes_c0_del_c1_preserving_byte_length() {
        // ASCII NUL (C0), DEL (0x7F), and U+0085 NEL (C1, 2-byte UTF-8) are hostile.
        // \n and \t are allowed through unchanged.
        let raw = "a\x00b\x7fc\u{0085}d\ne\tf";
        let out = neutralize_source_for_render(raw);
        // Byte length must be identical (span safety invariant).
        assert_eq!(out.len(), raw.len(), "byte length preserved");
        // Hostile bytes are replaced; safe bytes survive.
        assert!(!out.contains('\x00'), "NUL removed");
        assert!(!out.contains('\x7f'), "DEL removed");
        assert!(!out.contains('\u{0085}'), "C1 NEL removed");
        assert!(out.contains('\n'), "LF preserved");
        assert!(out.contains('\t'), "TAB preserved");
    }

    /// T-10b [reliability-8 / PF-014]: When the span starts AFTER a control character
    /// the substituted byte at that position must still form a valid char boundary so
    /// miette can slice the excerpt without panicking.
    #[test]
    fn neutralize_source_caret_alignment_with_span_after_control_char() {
        use miette::{GraphicalReportHandler, GraphicalTheme, NamedSource, SourceSpan};

        // "a<ESC>bc" where span covers 'b' (byte offset 2..3, AFTER the ESC byte).
        // If neutralization breaks the byte-length invariant, miette panics here.
        let raw = "a\x1bbc";
        let clean = neutralize_source_for_render(raw);
        assert_eq!(clean.len(), raw.len(), "byte length invariant");

        // Build a minimal miette report whose source excerpt exercises the span.
        #[derive(Debug, thiserror::Error, miette::Diagnostic)]
        #[error("test")]
        struct SpanErr {
            #[source_code]
            src: NamedSource<String>,
            #[label("here")]
            span: SourceSpan,
        }

        let report = miette::Report::new(SpanErr {
            src: NamedSource::new("test.mds", clean.into_owned()),
            span: (2, 1).into(), // byte 2..3 = 'b'
        });

        let mut buf = String::new();
        GraphicalReportHandler::new_themed(GraphicalTheme::unicode_nocolor())
            .render_report(&mut buf, report.as_ref())
            .expect("render must not panic after neutralization");
        // The caret must point at 'b', not produce garbage.
        assert!(buf.contains('b'), "caret points at b");
        // No raw ESC byte survives into the rendered output.
        assert!(!buf.contains('\x1b'), "no raw ESC in rendered output");
    }

    /// T-10c [testing-2 / PF-014]: miette's own SGR colour codes survive
    /// (render_error_sanitized never post-processes the frame) while a hostile
    /// OSC sequence embedded in the source is neutralised at the input stage.
    #[test]
    fn colour_path_miette_sgr_survives_hostile_osc_is_removed() {
        use miette::{GraphicalReportHandler, GraphicalTheme, NamedSource, SourceSpan};

        // A 2-byte C1 U+009D = OSC opener (hostile). After neutralize it becomes
        // U+00A0 NBSP, same byte length; no OSC survives into the render.
        // U+009D in UTF-8 is 0xC2 0x9D (2 bytes). We use the char directly.
        let hostile_char = '\u{009D}'; // C1 OSC opener
        let raw = format!("good{}text", hostile_char);
        let clean = neutralize_source_for_render(&raw);
        assert_eq!(clean.len(), raw.len(), "byte length preserved");
        assert!(
            !clean.contains(hostile_char),
            "C1 OSC neutralised in source"
        );

        #[derive(Debug, thiserror::Error, miette::Diagnostic)]
        #[error("colour test")]
        struct ColourErr {
            #[source_code]
            src: NamedSource<String>,
            #[label("here")]
            span: SourceSpan,
        }

        let src_len = clean.len();
        let report = miette::Report::new(ColourErr {
            src: NamedSource::new("colour.mds", clean.into_owned()),
            span: (0, src_len).into(),
        });

        // Colour-enabled renderer — miette will emit real SGR codes.
        let mut coloured = String::new();
        GraphicalReportHandler::new_themed(GraphicalTheme::unicode())
            .render_report(&mut coloured, report.as_ref())
            .expect("render must not panic");

        // miette's own ANSI codes must survive in the coloured output.
        assert!(
            coloured.contains('\x1b'),
            "miette SGR codes present in coloured output"
        );
        // But the hostile C1 byte is gone from the rendered string.
        assert!(
            !coloured.contains(hostile_char),
            "hostile C1 absent from rendered output"
        );
    }

    // ── sanitize_report: the CLI human message/help boundary (CWE-150 / #176) ────
    //
    // These are in-process unit tests so they can pin the COLOUR path, which the
    // subprocess e2e tests in `tests/security.rs` are structurally blind to (they set
    // `NO_COLOR=1` and pipe stderr).  Per the H4 test-determinism decision, colour is
    // selected explicitly via `GraphicalTheme` rather than inherited from the
    // environment.

    /// Render `report` through a colour-neutral handler — the deterministic in-process
    /// equivalent of what `render_error_sanitized` emits under `NO_COLOR=1`.
    fn render_nocolor(report: &miette::Report) -> String {
        use miette::{GraphicalReportHandler, GraphicalTheme};
        let mut buf = String::new();
        GraphicalReportHandler::new_themed(GraphicalTheme::unicode_nocolor())
            .render_report(&mut buf, report.as_ref())
            .expect("render must not panic");
        buf
    }

    /// T-ESC-1 [security-11 / PF-013 / #176]: an `MdsError` whose message *and* help
    /// both interpolate attacker-controlled text is escaped on both surfaces before
    /// miette renders it.
    ///
    /// `UndefinedVariable` is the vector because `name` lands in the `#[error(...)]`
    /// message and in the `#[diagnostic(help(...))]` text, so one input exercises both.
    #[test]
    fn sanitize_report_escapes_message_and_help() {
        let hostile_name = format!("bad{}[31mNAME", '\u{1b}');
        let report = sanitize_report(miette::Report::new(mds::MdsError::UndefinedVariable {
            name: hostile_name,
            span: None,
            src: None,
        }));
        let rendered = render_nocolor(&report);

        // Non-vacuity: the diagnostic actually rendered, with its help line.
        assert!(
            rendered.contains("undefined variable"),
            "non-vacuity: expected the undefined-variable message; got: {rendered:?}"
        );
        assert!(
            rendered.contains("help:"),
            "non-vacuity: expected a help line; got: {rendered:?}"
        );
        // Negative.
        assert!(
            !rendered.contains('\u{1b}'),
            "raw ESC must not survive into the rendered frame; got: {rendered:?}"
        );
        // Positive: escaped on BOTH surfaces, so the count is at least two.
        assert!(
            rendered.matches("\\u001B").count() >= 2,
            "ESC must be escaped in the message AND the help text; got: {rendered:?}"
        );
    }

    /// T-ESC-2 [security-11 / PF-004 / #176]: a CLI-authored `miette::miette!()` report
    /// — which does NOT downcast to `MdsError` — is escaped by the same boundary.
    #[test]
    fn sanitize_report_escapes_cli_authored_miette_message() {
        let hostile = format!("cannot write fo{}[2Jo.mds", '\u{1b}');
        let report = sanitize_report(miette::miette!("{hostile}"));
        let rendered = render_nocolor(&report);

        assert!(
            rendered.contains("cannot write"),
            "non-vacuity: expected the miette!() message; got: {rendered:?}"
        );
        assert!(
            !rendered.contains('\u{1b}'),
            "raw ESC must not survive a miette!() report; got: {rendered:?}"
        );
        assert!(
            rendered.contains("\\u001B"),
            "ESC must be escaped to the \\u001B literal; got: {rendered:?}"
        );
    }

    /// T-ESC-3 [security-11 / #176]: the widened hazard class (bidi controls, Trojan
    /// Source CVE-2021-42574) is escaped on this boundary too, not just C0/DEL/C1.
    #[test]
    fn sanitize_report_escapes_bidi_override_in_message() {
        let hostile = format!("alias{}reversed", '\u{202e}');
        let report = sanitize_report(miette::miette!("{hostile}"));
        let rendered = render_nocolor(&report);

        assert!(
            !rendered.contains('\u{202e}'),
            "raw U+202E must not survive; got: {rendered:?}"
        );
        assert!(
            rendered.contains("\\u202E"),
            "U+202E must be escaped to the \\u202E literal; got: {rendered:?}"
        );
    }

    /// T-ESC-4 [PF-014 / #176]: HUMAN mode — a real newline in the message survives, so
    /// multi-line diagnostic frames stay readable.  This is the one deliberate
    /// difference from the WIRE boundary (`MdsError::serialize`), which escapes `\n`.
    #[test]
    fn sanitize_report_preserves_newline_in_message() {
        let report = sanitize_report(miette::miette!("line one\nline two"));
        let rendered = render_nocolor(&report);

        assert!(
            rendered.contains("line one"),
            "non-vacuity: message must render; got: {rendered:?}"
        );
        assert!(
            !rendered.contains("\\u000A"),
            "HUMAN mode must NOT escape newlines; got: {rendered:?}"
        );
    }

    /// T-ESC-5 [security-11 / #176]: label TEXT is escaped while the label's byte SPAN
    /// is forwarded verbatim, so the caret still lands on the right columns.
    ///
    /// `LintDiagnostic::labels()` uses its own message as the label text, so this is a
    /// real untrusted-text surface and not a hypothetical one.
    #[test]
    fn sanitize_report_escapes_label_text_but_keeps_span() {
        let hostile_label = format!("here{}[31m", '\u{1b}');
        let diag = miette::MietteDiagnostic::new("outer message")
            .with_label(miette::LabeledSpan::at(2..5, hostile_label));
        let report =
            sanitize_report(miette::Report::new(diag).with_source_code("abcdefgh".to_string()));
        let rendered = render_nocolor(&report);

        assert!(
            rendered.contains("here"),
            "non-vacuity: the label must render; got: {rendered:?}"
        );
        assert!(
            !rendered.contains('\u{1b}'),
            "raw ESC must not survive in label text; got: {rendered:?}"
        );
        assert!(
            rendered.contains("\\u001B"),
            "label ESC must be escaped; got: {rendered:?}"
        );
        // Span geometry preserved: the source line and its caret still render.
        assert!(
            rendered.contains("abcdefgh"),
            "the labelled source excerpt must still render; got: {rendered:?}"
        );
    }

    /// T-ESC-6 [PF-014 / #176]: the regression this boundary exists to avoid.
    ///
    /// Rendering the sanitized report with a COLOUR theme must leave miette's own ANSI
    /// SGR codes intact (real ESC bytes present) while the hostile input is escaped to
    /// a literal.  An implementation that sanitized the rendered frame instead would
    /// strip miette's SGR into literal `\u001b[...` noise — this test fails loudly in
    /// that case, and the subprocess e2e tests cannot (they pin `NO_COLOR=1`).
    #[test]
    fn sanitize_report_colour_path_keeps_miette_sgr_and_escapes_hostile_input() {
        use miette::{GraphicalReportHandler, GraphicalTheme};

        let hostile = format!("hostile{}[31mtext", '\u{1b}');
        let report = sanitize_report(miette::miette!("{hostile}"));

        let mut coloured = String::new();
        GraphicalReportHandler::new_themed(GraphicalTheme::unicode())
            .render_report(&mut coloured, report.as_ref())
            .expect("render must not panic");

        // miette's own SGR codes survive — the frame was never post-processed.
        assert!(
            coloured.contains('\u{1b}'),
            "miette's own SGR codes must survive on the colour path; got: {coloured:?}"
        );
        // The hostile input is still escaped.
        assert!(
            coloured.contains("\\u001B"),
            "hostile ESC must be escaped even on the colour path; got: {coloured:?}"
        );
        // And miette's SGR was NOT itself escaped: the only escaped literal is the one
        // hostile byte, not the ~10 SGR sequences the frame contains.
        assert_eq!(
            coloured.matches("\\u001B").count(),
            1,
            "exactly one escaped literal (the hostile byte) — more means miette's own \
             SGR codes were escaped, which is the PF-014 regression; got: {coloured:?}"
        );
    }

    /// T-ESC-7 [#176]: clean input renders byte-identically with and without the
    /// sanitizing wrapper, so the boundary is inert on the overwhelmingly common path.
    #[test]
    fn sanitize_report_is_inert_on_clean_input() {
        let raw = miette::Report::new(mds::MdsError::UndefinedVariable {
            name: "user_name".to_string(),
            span: None,
            src: None,
        });
        let before = render_nocolor(&raw);
        let after = render_nocolor(&sanitize_report(raw));
        assert_eq!(
            before, after,
            "sanitizing must not alter the render of a clean diagnostic"
        );
    }

    // ── sanitize_report: the auxiliary diagnostic graph (PF-005 / #176) ─────────
    //
    // `source()` / `related()` / `diagnostic_source()` used to be reported as absent,
    // guarded only by a `debug_assert!` that no CLI error populates them. `debug_assert!`
    // is compiled out of release, so that invariant was real in tests and ABSENT in the
    // shipped binary: the first error type to grow a `#[source]` field would have had
    // its cause chain silently dropped from release stderr while CI stayed green.
    //
    // These tests are pure functional assertions on the `Diagnostic` impl, so they hold
    // identically in debug and release — which is the point.

    /// A two-link cause chain: an outer diagnostic whose `#[source]` carries hostile text.
    #[derive(Debug, thiserror::Error, miette::Diagnostic)]
    #[error("outer failure")]
    struct OuterWithCause {
        #[source]
        cause: InnerCause,
    }

    #[derive(Debug, thiserror::Error)]
    #[error("inner cause: {0}")]
    struct InnerCause(String);

    /// A diagnostic that hangs a hostile `related` diagnostic off itself.
    #[derive(Debug, thiserror::Error, miette::Diagnostic)]
    #[error("parent diagnostic")]
    struct ParentWithRelated {
        #[related]
        related: Vec<RelatedChild>,
    }

    #[derive(Debug, thiserror::Error, miette::Diagnostic)]
    #[error("related child: {0}")]
    #[diagnostic(help("child help: {0}"))]
    struct RelatedChild(String);

    /// The hostile fragment shared by the auxiliary-graph tests: one C0 byte, one
    /// 3-byte bidi control, and the 2-byte bidi control #176 added.
    fn hostile_fragment() -> String {
        format!("bad{}[31m{}{}end", '\u{1b}', '\u{202e}', '\u{061c}')
    }

    /// Negative + positive assertions shared by T-AUX-1/2/3.
    fn assert_aux_text_escaped(rendered: &str, surface: &str) {
        for raw in ['\u{1b}', '\u{202e}', '\u{061c}'] {
            assert!(
                !rendered.contains(raw),
                "{surface}: raw U+{:04X} must not survive into the rendered frame; \
                 got: {rendered:?}",
                raw as u32
            );
        }
        // Uppercase literals from a lowercase-hex source vector: proof the byte really
        // decoded and was really escaped rather than passing through as literal text.
        for escaped in ["\\u001B", "\\u202E", "\\u061C"] {
            assert!(
                rendered.contains(escaped),
                "{surface}: {escaped} must appear in the rendered frame; got: {rendered:?}"
            );
        }
    }

    /// T-AUX-1 [PF-005 / security-11 / PF-013 / #176]: a report carrying a `#[source]`
    /// cause chain renders that cause, escaped — neither leaked raw nor dropped.
    #[test]
    fn sanitize_report_escapes_and_preserves_the_cause_chain() {
        let report = sanitize_report(miette::Report::new(OuterWithCause {
            cause: InnerCause(hostile_fragment()),
        }));
        let rendered = render_nocolor(&report);

        // Non-vacuity: the cause is actually rendered. This is the assertion that fails
        // if `source()` reverts to returning `None` — the release-build silent drop.
        assert!(
            rendered.contains("inner cause"),
            "non-vacuity: the cause chain must still render; got: {rendered:?}"
        );
        assert!(
            rendered.contains("outer failure"),
            "non-vacuity: the outer message must still render; got: {rendered:?}"
        );
        assert_aux_text_escaped(&rendered, "cause chain");
    }

    /// T-AUX-2 [PF-005 / #176]: `related()` diagnostics — message AND help — are
    /// escaped and preserved.
    #[test]
    fn sanitize_report_escapes_and_preserves_related_diagnostics() {
        let report = sanitize_report(miette::Report::new(ParentWithRelated {
            related: vec![RelatedChild(hostile_fragment())],
        }));
        let rendered = render_nocolor(&report);

        assert!(
            rendered.contains("parent diagnostic"),
            "non-vacuity: the parent message must render; got: {rendered:?}"
        );
        assert!(
            rendered.contains("related child"),
            "non-vacuity: the related diagnostic must still render; got: {rendered:?}"
        );
        assert!(
            rendered.contains("child help"),
            "non-vacuity: the related diagnostic's help must still render; got: {rendered:?}"
        );
        assert_aux_text_escaped(&rendered, "related diagnostics");
    }

    /// T-AUX-3 [PF-005 / #176]: the walk is depth-bounded, so a self-referential
    /// `source()` cannot hang or overflow the stack during rendering.
    ///
    /// `Cycle::source()` returns `self`, an infinite chain. Construction must terminate.
    #[test]
    fn sanitize_report_bounds_a_cyclic_cause_chain() {
        #[derive(Debug)]
        struct Cycle;
        impl std::fmt::Display for Cycle {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("cyclic cause")
            }
        }
        impl std::error::Error for Cycle {
            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
                Some(&Cycle)
            }
        }
        #[derive(Debug, thiserror::Error, miette::Diagnostic)]
        #[error("outer")]
        struct Outer(#[source] Cycle);

        let wrapped = SanitizedReport::new(miette::Report::new(Outer(Cycle)));

        // Walk the materialised chain and assert it is finite and within the bound.
        let mut depth = 0usize;
        let mut node = wrapped.source.as_ref();
        while let Some(n) = node {
            depth += 1;
            assert!(
                depth <= MAX_AUX_DEPTH,
                "the cause-chain walk must be bounded by MAX_AUX_DEPTH"
            );
            node = n.source.as_deref();
        }
        // Non-vacuity: the bound was actually reached, so this is not passing because
        // the chain was empty.
        assert_eq!(
            depth, MAX_AUX_DEPTH,
            "an infinite chain must be truncated at exactly MAX_AUX_DEPTH"
        );
    }

    // ── eprint_warning: the CLI warning sanitization boundary (CWE-150 / PF-004 / #176) ──
    //
    // eprint_warning is a thin wrapper around mds::sanitize_control_chars + ewriteln!.
    // The tests below exercise the transformation directly (the pure function that the
    // wrapper applies) to keep assertions deterministic without capturing stderr.
    //
    // Test strategy — corrected.
    //
    // An earlier revision of this block claimed that "the only warning that interpolates
    // untrusted text is the resolver warning" (which needs a MAX_SOURCEMAP_SEGMENTS
    // overflow in a hostile-named module, so an e2e vector for it would be contrived),
    // and concluded that no e2e test was required because "every warning print in
    // main.rs and build.rs now calls eprint_warning". Both halves were false, and the
    // unreachability argument was the load-bearing one:
    //
    //   * lint.rs's unknown-`mds.json`-rule warning (added in e145e41) interpolates an
    //     arbitrary JSON object key — reachable in about thirty seconds by writing an
    //     mds.json into any linted directory. It is covered e2e by T-ESC-RULE-1 in
    //     tests/security.rs, whose vector now carries newlines as well as C0 and bidi
    //     controls, because routing it through eprint_warning (HUMAN, `\n` preserved)
    //     closed CWE-150 on it while leaving the CWE-117 line forgery open.
    //   * The walker's own depth-limit warning, ~40 lines up in THIS file, printed
    //     `dir.display()` through a bare eprintln!. It is neither main.rs nor build.rs,
    //     so the enumeration above walked straight past it. Covered e2e by T-ESC-WALK-1.
    //
    // The unit tests below stay — they pin the transformation deterministically without
    // capturing stderr — but they are no longer offered as a substitute for e2e vectors.
    //
    // Coverage is now enforced rather than enumerated: tests/print_discipline.rs fails if
    // ANY print macro under crates/mds-cli/src interpolates a value that is not passed
    // through safe_path / safe_file_display / safe_inline / sanitize_control_chars*, and
    // applies the same rule to `format!`s nested inside eprint_warning calls. That is
    // what makes a claim about warning-path coverage checkable instead of remembered.
    //
    // Guard-removal RED evidence (T-WARN-1):
    //   Replace `mds::sanitize_control_chars(&hostile)` with
    //   `std::borrow::Cow::Borrowed(hostile.as_str())` in the test body.
    //   The test fails with:
    //     assertion `left == right` failed: raw ESC must be absent from warning output
    //     left: true
    //     right: false
    //   because the unsanitized string still contains '\u{1b}'.
    //   Restoring the call makes the test green.

    /// T-WARN-1 [security-11 / PF-004 / PF-013 / #176]: a hostile warning string
    /// (one that interpolates a filename containing a raw ESC byte) is sanitized to
    /// its `\uXXXX` literal form — raw ESC is absent and the escaped form is present.
    ///
    /// This tests the exact transformation that `eprint_warning` applies before printing.
    #[test]
    fn eprint_warning_sanitizes_hostile_control_chars() {
        // Simulate the only real-world hostile vector: the resolver warning that
        // interpolates an untrusted module filename (mds-core/src/resolver.rs).
        let hostile = format!(
            "MAX_SOURCEMAP_SEGMENTS exceeded in imported module 'lib{}[2Jbar.mds'",
            '\u{1b}'
        );
        // This is exactly what eprint_warning applies before calling ewriteln!.
        let result = mds::sanitize_control_chars(&hostile);

        // Non-vacuity: the plain-text content is preserved.
        assert!(
            result.contains("MAX_SOURCEMAP_SEGMENTS"),
            "non-vacuity: warning text must be preserved; got: {result:?}"
        );
        assert!(
            result.contains("lib"),
            "non-vacuity: filename prefix must be preserved; got: {result:?}"
        );
        // Negative: raw ESC absent.
        assert!(
            !result.contains('\u{1b}'),
            "raw ESC must be absent from warning output; hostile = {hostile:?}"
        );
        // Positive: escaped form present.
        assert!(
            result.contains("\\u001B"),
            "ESC must be escaped to \\u001B literal; got: {result:?}"
        );
    }

    /// T-WARN-2 [PF-013 / #176]: a clean warning string passes through unchanged —
    /// the sanitization is inert on the overwhelmingly common path.
    ///
    /// This corresponds to the "clean string passes through unchanged" requirement from
    /// the task brief: eprint_warning must never mutate a warning that contains no
    /// hazardous bytes.
    #[test]
    fn eprint_warning_clean_string_passes_through_unchanged() {
        let clean = "MAX_SOURCEMAP_SEGMENTS exceeded in imported module 'lib.mds'";
        let result = mds::sanitize_control_chars(clean);
        assert_eq!(
            result.as_ref(),
            clean,
            "clean warning must pass through unchanged; got: {result:?}"
        );
    }

    /// T-WARN-3 [PF-013 / #176]: the widened hazard class (bidi controls, Trojan
    /// Source CVE-2021-42574) is escaped by eprint_warning too — not just C0/ESC.
    #[test]
    fn eprint_warning_sanitizes_bidi_control_in_warning_text() {
        // U+202E RIGHT-TO-LEFT OVERRIDE: injecting this into a warning message
        // reverses how the rest of the terminal line renders in bidi-aware terminals.
        let hostile = format!("warning: module 'lib{}evil.mds'", '\u{202e}');
        let result = mds::sanitize_control_chars(&hostile);
        assert!(
            !result.contains('\u{202e}'),
            "raw U+202E must be absent from warning output; got: {result:?}"
        );
        assert!(
            result.contains("\\u202E"),
            "U+202E must be escaped to \\u202E literal; got: {result:?}"
        );
    }

    // ── render_unified_diff / colorize_unified_diff ───────────────────────────

    #[test]
    fn render_unified_diff_empty_for_identical_input() {
        let rendered = render_unified_diff("same\n", "same\n", "label");
        assert!(rendered.is_empty());
    }

    #[test]
    fn render_unified_diff_contains_unified_markers_for_changed_input() {
        let rendered = render_unified_diff("a\n", "b\n", "label");
        assert!(rendered.contains("---"));
        assert!(rendered.contains("+++"));
        assert!(rendered.contains("-a"));
        assert!(rendered.contains("+b"));
    }

    #[test]
    fn colorize_unified_diff_wraps_add_remove_lines_with_ansi_when_requested() {
        let unified = "--- a\n+++ b\n@@ -1 +1 @@\n-old\n+new\n";
        let colorized = colorize_unified_diff(unified);
        assert!(colorized.contains("\x1b[32m+new\x1b[0m"));
        assert!(colorized.contains("\x1b[31m-old\x1b[0m"));
        assert!(colorized.contains("\x1b[36m--- a\x1b[0m"));
    }

    #[test]
    fn colorize_unified_diff_correctly_colors_content_starting_with_dashes_or_pluses() {
        // Regression: a removed line whose content starts with "-- " produces
        // "--- ..." in the rendered unified diff. The old global prefix check
        // matched `starts_with("---")` and mis-colored it CYAN (file header)
        // instead of RED (removal). Same defect for "++" content → "+++ " →
        // mis-colored CYAN instead of GREEN.
        let unified = "--- a\n+++ b\n@@ -1,2 +1,2 @@\n--- dashes content\n+++ plus content\n";
        let colorized = colorize_unified_diff(unified);
        // Inside the hunk: removal of a line whose content starts with "-- "
        assert!(colorized.contains("\x1b[31m--- dashes content\x1b[0m"));
        // Inside the hunk: addition of a line whose content starts with "++"
        assert!(colorized.contains("\x1b[32m+++ plus content\x1b[0m"));
        // File headers (before @@) must still be CYAN
        assert!(colorized.contains("\x1b[36m--- a\x1b[0m"));
        assert!(colorized.contains("\x1b[36m+++ b\x1b[0m"));
    }

    // ── io_cause / notify_cause: a cause with no path in it (#390) ─────────────

    /// The name of a directory no cause text could carry by chance. The tests look for
    /// this name, not for the whole path: tempfile and notify quote a path in its `Debug`
    /// spelling, which doubles each `\`, so on Windows a path as it displays never
    /// appears in their text.
    const SENTINEL_DIR: &str = "sentinel-cause-dir";

    /// An absolute path below [`SENTINEL_DIR`], a directory that does not exist — so an
    /// error about it is a real one, raised for that path.
    fn sentinel(dir: &tempfile::TempDir) -> PathBuf {
        dir.path().join(SENTINEL_DIR).join("leaf")
    }

    /// A library error that carries a path in its own text is shown by its kind alone:
    /// tempfile's `at path "…"`, and any other payload. An error of the operating system's
    /// keeps its text, which names no path. Controls: each error's own text carries the
    /// sentinel, so its absence below means the helper dropped it.
    #[test]
    fn io_cause_drops_the_path_an_error_carries() {
        let dir = tempfile::tempdir().unwrap();
        let sentinel = sentinel(&dir);
        let needle = SENTINEL_DIR;

        // tempfile wraps the error creating its file in one that names the file.
        let tempfile = tempfile::Builder::new()
            .tempfile_in(sentinel.parent().unwrap())
            .expect_err("no temporary file below a directory that does not exist");
        assert!(
            tempfile.to_string().contains(needle),
            "control: tempfile's text names the path: {tempfile}"
        );
        let cause = io_cause(&tempfile);
        assert!(!cause.contains(needle), "{cause}");
        assert!(!cause.contains("at path"), "{cause}");
        assert_eq!(cause, tempfile.kind().to_string(), "its kind's text");

        let custom = std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            format!("denied: {}", sentinel.display()),
        );
        assert!(custom.to_string().contains(needle), "control: {custom}");
        assert_eq!(io_cause(&custom), "permission denied");

        // The operating system's own error keeps its words and code.
        let os = std::fs::File::open(&sentinel).expect_err("the sentinel does not exist");
        assert!(os.raw_os_error().is_some(), "control: an OS error: {os:?}");
        assert_eq!(io_cause(&os), os.to_string());
        assert!(io_cause(&os).contains("(os error "), "{}", io_cause(&os));

        // An error made from a kind alone is that kind's text.
        let kind = std::io::Error::from(std::io::ErrorKind::NotFound);
        assert_eq!(io_cause(&kind), std::io::ErrorKind::NotFound.to_string());
    }

    /// A file watcher's error is shown by its kind's text, without the paths notify lists
    /// after it (` about ["…"]`): notify's own fixed texts as notify words them, an I/O
    /// error through [`io_cause`], and a backend's message as it gives it unless it names
    /// a path. Every kind notify has is listed. Controls: notify's own text of each carries
    /// the sentinel.
    #[test]
    fn notify_cause_drops_the_paths_a_watcher_error_lists() {
        let dir = tempfile::tempdir().unwrap();
        let sentinel = sentinel(&dir);
        let needle = SENTINEL_DIR;
        let listing = |e: notify::Error| e.add_path(sentinel.clone());
        let os = std::fs::File::open(&sentinel).expect_err("the sentinel does not exist");
        let os_text = os.to_string();
        let config = notify::Config::default();

        // (the error, its cause)
        let cases = [
            (
                listing(notify::Error::path_not_found()),
                "No path was found.".to_owned(),
            ),
            (
                listing(notify::Error::watch_not_found()),
                "No watch was found.".to_owned(),
            ),
            (
                listing(notify::Error::invalid_config(&config)),
                format!("Invalid configuration: {config:?}"),
            ),
            (
                listing(notify::Error::new(notify::ErrorKind::MaxFilesWatch)),
                "OS file watch limit reached.".to_owned(),
            ),
            (listing(notify::Error::io(os)), os_text),
            (
                listing(notify::Error::generic(
                    "Input watch path is neither a file nor a directory.",
                )),
                "Input watch path is neither a file nor a directory.".to_owned(),
            ),
            (
                listing(notify::Error::generic(&format!(
                    "Expected ack for {sentinel:?}"
                ))),
                WATCHER_ERROR.to_owned(),
            ),
            (
                listing(notify::Error::io(std::io::Error::other(format!(
                    "IO error for operation on {}",
                    sentinel.display()
                )))),
                std::io::ErrorKind::Other.to_string(),
            ),
        ];
        for (error, expected) in cases {
            let shown = error.to_string();
            assert!(shown.contains(needle), "control: {shown}");
            let cause = notify_cause(&error);
            assert!(!cause.contains(needle), "{cause}");
            assert!(!cause.contains(" about "), "{cause}");
            assert_eq!(cause, expected, "the cause of {shown:?}");
        }

        // A backend's message is kept as given; a line escapes it through `safe_inline`,
        // as it does every value it interpolates.
        let raw = format!("bad{}word", '\x1b');
        let cause = notify_cause(&notify::Error::generic(&raw));
        assert_eq!(cause, raw, "the cause is the backend's text");
        let shown = safe_inline(&cause);
        assert!(!shown.contains('\x1b'), "{shown:?}");
        assert!(
            shown.starts_with("bad") && shown.ends_with("word"),
            "{shown:?}"
        );
    }

    // ── render_error_sanitized never panics on a failing Display (#157) ─────────

    /// The six-character escape `sanitize_control_chars` writes for ESC, built at runtime
    /// so no escape sequence is written into this source.
    fn escaped_esc() -> String {
        format!("{}u001B", '\\')
    }

    /// A `Display` that always fails, standing in for a buggy third-party impl.
    struct Unformattable;

    impl std::fmt::Display for Unformattable {
        fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            Err(std::fmt::Error)
        }
    }

    /// Source text that serves a label's surrounding context but fails the exact-span
    /// read miette makes next, so miette's own render returns `fmt::Error` part-way
    /// through the frame.
    #[derive(Debug)]
    struct FailsNarrowReads(String);

    impl miette::SourceCode for FailsNarrowReads {
        fn read_span<'a>(
            &'a self,
            span: &miette::SourceSpan,
            context_lines_before: usize,
            context_lines_after: usize,
        ) -> std::result::Result<Box<dyn miette::SpanContents<'a> + 'a>, miette::MietteError>
        {
            if context_lines_before == 0 && context_lines_after == 0 {
                return Err(miette::MietteError::OutOfBounds);
            }
            miette::SourceCode::read_span(&self.0, span, context_lines_before, context_lines_after)
        }
    }

    /// A cause whose message cannot be formatted.
    #[derive(Debug)]
    struct UnformattableCause;

    impl std::fmt::Display for UnformattableCause {
        fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            Err(std::fmt::Error)
        }
    }

    impl std::error::Error for UnformattableCause {}

    /// A diagnostic whose surfaces fail to format one at a time, as each test asks.
    #[derive(Debug, Default)]
    struct Probe {
        message: String,
        message_fails: bool,
        code_fails: bool,
        help_fails: bool,
        cause: Option<UnformattableCause>,
        source: Option<FailsNarrowReads>,
    }

    impl std::fmt::Display for Probe {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            if self.message_fails {
                return Err(std::fmt::Error);
            }
            f.write_str(&self.message)
        }
    }

    impl std::error::Error for Probe {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            self.cause
                .as_ref()
                .map(|c| c as &(dyn std::error::Error + 'static))
        }
    }

    impl miette::Diagnostic for Probe {
        fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
            if self.code_fails {
                Some(Box::new(Unformattable))
            } else {
                Some(Box::new("mds::probe"))
            }
        }

        fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
            if self.help_fails {
                Some(Box::new(Unformattable))
            } else {
                Some(Box::new("probe help"))
            }
        }

        fn source_code(&self) -> Option<&dyn miette::SourceCode> {
            self.source.as_ref().map(|s| s as &dyn miette::SourceCode)
        }

        fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
            self.source.as_ref()?;
            Some(Box::new(std::iter::once(
                miette::LabeledSpan::new_primary_with_span(Some("here".to_string()), (0, 5)),
            )))
        }
    }

    /// A report whose own message cannot be formatted still renders — its code and help
    /// in the usual frame, a fixed placeholder where the message would be.
    #[test]
    fn a_report_whose_message_cannot_be_formatted_renders_a_placeholder() {
        let rendered = render_error_sanitized(miette::Report::new(Probe {
            message_fails: true,
            ..Probe::default()
        }));

        assert!(
            rendered.contains("mds::probe") && rendered.contains("probe help"),
            "the rest of the frame must render; got {rendered:?}"
        );
        assert!(
            rendered.contains("could not be formatted"),
            "the message's place must say it could not be formatted; got {rendered:?}"
        );
    }

    /// A code, help or cause whose `Display` fails costs only that surface: the message
    /// still renders, escaped, in the usual frame.
    #[test]
    fn a_report_whose_code_help_or_cause_cannot_be_formatted_keeps_its_message() {
        let rendered = render_error_sanitized(miette::Report::new(Probe {
            message: format!("cannot write fo{}[2Jo.mds", '\x1b'),
            code_fails: true,
            help_fails: true,
            cause: Some(UnformattableCause),
            ..Probe::default()
        }));

        assert!(
            rendered.contains("cannot write fo") && rendered.contains(&escaped_esc()),
            "the message must render, with ESC escaped; got {rendered:?}"
        );
        assert!(
            !rendered.contains('\x1b'),
            "no raw ESC may reach the rendered text; got {rendered:?}"
        );
        assert!(
            rendered.contains("could not be formatted"),
            "the unformattable cause must leave a placeholder, not vanish; got {rendered:?}"
        );
    }

    /// When miette's own render fails part-way (here: a source read fails after the
    /// frame has started), the whole frame is replaced by escaped plain text — never a
    /// panic, never half a frame.
    #[test]
    fn a_render_failure_falls_back_to_escaped_plain_text() {
        let rendered = render_error_sanitized(miette::Report::new(Probe {
            message: format!("cannot write fo{}[2Jo.mds\nsecond line", '\x1b'),
            source: Some(FailsNarrowReads("Hello world\n".to_string())),
            ..Probe::default()
        }));

        let esc = escaped_esc();
        let want = format!(
            "mds::probe\n\n  \u{00d7} cannot write fo{esc}[2Jo.mds\n  \u{2502} second line\n  help: probe help\n"
        );
        assert_eq!(
            rendered, want,
            "a failed render must fall back to the plain-text form, escaped"
        );
    }

    // ── The stderr writer, the stdout outcome and the exit code (#157) ──────────

    /// What a [`Sink`]'s `write` does.
    #[derive(Clone, Copy)]
    enum OnWrite {
        Accept,
        Fail(std::io::ErrorKind),
        /// Accept nothing: `write` returns `Ok(0)`, which `write_all` reports as
        /// `WriteZero`.
        Zero,
    }

    /// An in-memory stream whose `write` and `flush` fail as a test asks, counting the
    /// `write` calls so a dropped write can be told apart from a failed one.
    struct Sink {
        on_write: OnWrite,
        flush_fails: Option<std::io::ErrorKind>,
        writes: usize,
        bytes: Vec<u8>,
    }

    impl Sink {
        fn new(on_write: OnWrite) -> Self {
            Self {
                on_write,
                flush_fails: None,
                writes: 0,
                bytes: Vec::new(),
            }
        }

        fn failing_flush(kind: std::io::ErrorKind) -> Self {
            Self {
                flush_fails: Some(kind),
                ..Self::new(OnWrite::Accept)
            }
        }
    }

    impl std::io::Write for Sink {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.writes += 1;
            match self.on_write {
                OnWrite::Accept => {
                    self.bytes.extend_from_slice(buf);
                    Ok(buf.len())
                }
                OnWrite::Fail(kind) => Err(std::io::Error::from(kind)),
                OnWrite::Zero => Ok(0),
            }
        }

        fn flush(&mut self) -> std::io::Result<()> {
            match self.flush_fails {
                Some(kind) => Err(std::io::Error::from(kind)),
                None => Ok(()),
            }
        }
    }

    #[test]
    fn stderr_writer_writes_the_whole_text_and_records_nothing() {
        let state = OutputState::new();
        let mut sink = Sink::new(OnWrite::Accept);
        write_stderr_to(&state, &mut sink, format_args!("OK: {}\n", "x.mds"));

        assert_eq!(sink.bytes, b"OK: x.mds\n");
        assert_eq!(sink.writes, 1, "the rendered text goes out in one write");
        assert!(!state.stderr_closed() && !state.io_failed());
    }

    #[test]
    fn stderr_writer_treats_a_closed_pipe_as_sticky_and_drops_later_writes() {
        let state = OutputState::new();
        let mut closed = Sink::new(OnWrite::Fail(std::io::ErrorKind::BrokenPipe));
        write_stderr_to(&state, &mut closed, format_args!("first\n"));
        assert!(state.stderr_closed(), "a closed pipe must be recorded");
        assert!(!state.io_failed(), "a closed pipe is not an I/O failure");

        let mut later = Sink::new(OnWrite::Accept);
        write_stderr_to(&state, &mut later, format_args!("second\n"));
        assert_eq!(
            later.writes, 0,
            "every write after the pipe closed must be dropped"
        );
    }

    #[test]
    fn stderr_writer_records_any_other_failure_and_keeps_writing() {
        let state = OutputState::new();
        let mut full = Sink::new(OnWrite::Fail(std::io::ErrorKind::StorageFull));
        write_stderr_to(&state, &mut full, format_args!("first\n"));
        assert!(state.io_failed(), "a non-pipe failure must be recorded");
        assert!(!state.stderr_closed(), "a full disk is not a closed pipe");

        let mut later = Sink::new(OnWrite::Accept);
        write_stderr_to(&state, &mut later, format_args!("second\n"));
        assert_eq!(
            later.bytes, b"second\n",
            "an I/O failure must not stop later writes"
        );
        assert!(state.io_failed(), "the failure stays recorded");
    }

    #[test]
    fn stderr_writer_counts_a_short_write_and_a_failed_flush() {
        let short = OutputState::new();
        write_stderr_to(&short, &mut Sink::new(OnWrite::Zero), format_args!("x\n"));
        assert!(short.io_failed() && !short.stderr_closed());

        let flush_full = OutputState::new();
        let mut sink = Sink::failing_flush(std::io::ErrorKind::StorageFull);
        write_stderr_to(&flush_full, &mut sink, format_args!("x\n"));
        assert!(flush_full.io_failed() && !flush_full.stderr_closed());

        let flush_closed = OutputState::new();
        let mut sink = Sink::failing_flush(std::io::ErrorKind::BrokenPipe);
        write_stderr_to(&flush_closed, &mut sink, format_args!("x\n"));
        assert!(flush_closed.stderr_closed() && !flush_closed.io_failed());
    }

    #[test]
    fn stderr_writer_survives_a_display_that_fails() {
        let state = OutputState::new();
        let mut sink = Sink::new(OnWrite::Accept);
        write_stderr_to(
            &state,
            &mut sink,
            format_args!("before {} after\n", Unformattable),
        );

        assert_eq!(
            sink.bytes, b"before ",
            "the text ends where the Display failed"
        );
        assert!(
            !state.stderr_closed() && !state.io_failed(),
            "a formatting bug is not an output failure"
        );
    }

    /// #380: an asked clear goes in front of the first non-empty stderr text, in the same
    /// write, and only once; an empty text keeps it for the next.
    #[test]
    fn an_asked_clear_goes_before_the_first_printed_byte_once() {
        let state = OutputState::new();
        state.ask_clear();
        let mut sink = Sink::new(OnWrite::Accept);
        write_stderr_to(&state, &mut sink, format_args!(""));
        assert!(sink.bytes.is_empty(), "an empty text makes no clear");
        assert!(state.clear_is_asked(), "an empty text keeps the request");

        write_stderr_to(&state, &mut sink, format_args!("warning: w\n"));
        write_stderr_to(&state, &mut sink, format_args!("Recompiled\n"));
        let expected = format!("{CLEAR_SEQUENCE}warning: w\nRecompiled\n");
        assert_eq!(sink.bytes, expected.as_bytes());
        assert_eq!(sink.writes, 2, "the clear and its line go out in one write");
        assert!(!state.clear_is_asked());
    }

    /// #380: without a request, a cancelled request, or a closed stderr, no clear is
    /// written.
    #[test]
    fn no_clear_is_written_unless_one_is_asked_and_stderr_is_open() {
        let unasked = OutputState::new();
        let mut sink = Sink::new(OnWrite::Accept);
        write_stderr_to(&unasked, &mut sink, format_args!("x\n"));
        assert_eq!(sink.bytes, b"x\n");

        let cancelled = OutputState::new();
        cancelled.ask_clear();
        cancelled.cancel_clear();
        let mut sink = Sink::new(OnWrite::Accept);
        write_stderr_to(&cancelled, &mut sink, format_args!("x\n"));
        assert_eq!(sink.bytes, b"x\n");

        let closed = OutputState::new();
        closed.note_stderr_closed();
        closed.ask_clear();
        let mut sink = Sink::new(OnWrite::Accept);
        write_pending_clear_to(&closed, &mut sink);
        assert_eq!(sink.writes, 0, "a closed stderr gets no clear");
    }

    /// #380: before a command's product goes to stdout, an asked clear is made on its
    /// own, once.
    #[test]
    fn a_pending_clear_is_made_on_its_own_before_stdout_output() {
        let state = OutputState::new();
        state.ask_clear();
        let mut sink = Sink::new(OnWrite::Accept);
        write_pending_clear_to(&state, &mut sink);
        write_pending_clear_to(&state, &mut sink);
        assert_eq!(sink.bytes, CLEAR_SEQUENCE.as_bytes());
        assert_eq!(sink.writes, 1);
    }

    #[test]
    fn write_stdout_is_written_only_when_the_write_and_the_flush_succeed() {
        let state = OutputState::new();
        let mut ok = Sink::new(OnWrite::Accept);
        assert!(matches!(
            write_stdout_to(&state, &mut ok, b"compiled\n"),
            StdoutOutcome::Written
        ));
        assert_eq!(ok.bytes, b"compiled\n");
        assert!(
            !state.stdout_closed() && !state.io_failed(),
            "a write that succeeds records nothing"
        );

        let cases = [
            (
                "write hits a closed pipe",
                Sink::new(OnWrite::Fail(std::io::ErrorKind::BrokenPipe)),
                None,
            ),
            (
                "flush hits a closed pipe",
                Sink::failing_flush(std::io::ErrorKind::BrokenPipe),
                None,
            ),
            (
                "write fails",
                Sink::new(OnWrite::Fail(std::io::ErrorKind::StorageFull)),
                Some(std::io::ErrorKind::StorageFull),
            ),
            (
                "write is short",
                Sink::new(OnWrite::Zero),
                Some(std::io::ErrorKind::WriteZero),
            ),
            (
                "flush fails",
                Sink::failing_flush(std::io::ErrorKind::StorageFull),
                Some(std::io::ErrorKind::StorageFull),
            ),
        ];
        for (what, mut sink, failed_kind) in cases {
            let outcome = write_stdout_to(&OutputState::new(), &mut sink, b"compiled\n");
            match (failed_kind, &outcome) {
                (None, StdoutOutcome::Closed) => {}
                (Some(want), StdoutOutcome::Failed(e)) if e.kind() == want => {}
                _ => panic!("{what}: want Closed or Failed({failed_kind:?}); got {outcome:?}"),
            }
        }
    }

    /// Once stdout's reader is gone, nothing more is written to it: a later write, to
    /// the same stream or to one that would accept it, is `Closed` without a byte
    /// reaching the stream (#157).
    #[test]
    fn write_stdout_writes_nothing_once_stdout_is_closed() {
        let state = OutputState::new();
        let mut closed = Sink::new(OnWrite::Fail(std::io::ErrorKind::BrokenPipe));
        let first = write_stdout_to(&state, &mut closed, b"first\n");
        assert!(state.stdout_closed(), "a closed stdout must be recorded");
        assert!(!state.io_failed(), "a closed pipe is not an I/O failure");
        let second = write_stdout_to(&state, &mut closed, b"second\n");
        let mut later = Sink::new(OnWrite::Accept);
        let third = write_stdout_to(&state, &mut later, b"third\n");
        assert_eq!(
            (closed.writes, later.writes),
            (1, 0),
            "no write may follow a closed pipe; outcomes {first:?}, {second:?}, {third:?}"
        );
        assert!(
            matches!(
                (&first, &second, &third),
                (
                    StdoutOutcome::Closed,
                    StdoutOutcome::Closed,
                    StdoutOutcome::Closed
                )
            ),
            "got {first:?}, {second:?}, {third:?}"
        );
    }

    /// A stdout that fails for another reason is reported once while it keeps failing:
    /// the first failed write is `Failed`, and a later one that fails again is not, so a
    /// batch run reports the failure once. Every write is still attempted (#157).
    #[test]
    fn write_stdout_reports_only_the_first_other_failure() {
        let state = OutputState::new();
        // A success first: it must not use up the one report.
        let _ = write_stdout_to(&state, &mut Sink::new(OnWrite::Accept), b"ok\n");
        let mut full = Sink::new(OnWrite::Fail(std::io::ErrorKind::StorageFull));
        let first = write_stdout_to(&state, &mut full, b"first\n");
        let second = write_stdout_to(&state, &mut full, b"second\n");
        assert!(
            matches!(&first, StdoutOutcome::Failed(e) if e.kind() == std::io::ErrorKind::StorageFull),
            "the first failure is reported; got {first:?}"
        );
        assert!(
            !matches!(second, StdoutOutcome::Failed(_)),
            "a second failure must not be reported again; got {second:?}"
        );
        assert_eq!(full.writes, 2, "a write after a failure is still attempted");
        assert!(
            second.into_batch_result().is_ok(),
            "a batch run does not report a repeated failure"
        );

        let mut ok = Sink::new(OnWrite::Accept);
        let third = write_stdout_to(&state, &mut ok, b"third\n");
        assert!(
            matches!(third, StdoutOutcome::Written) && ok.bytes == b"third\n",
            "a write that succeeds after a failure is written; got {third:?}"
        );
        assert!(
            !state.stdout_closed() && !state.io_failed(),
            "the writer records only the stdout failure; the caller's report records the \
             I/O failure for the exit code"
        );
    }

    /// A stdout failure is reported once per failure episode: a write that lands ends
    /// the episode, so the next failure is new and reported again — a `mds watch -o -`
    /// session must not go silent on a stdout that failed, recovered and failed again.
    /// A write of no bytes proves nothing and ends nothing. The recorded I/O failure
    /// that lifts a batch run's exit code outlives the recovery (#157).
    #[test]
    fn write_stdout_reports_a_new_failure_after_stdout_recovers() {
        let state = OutputState::new();
        let mut full = Sink::new(OnWrite::Fail(std::io::ErrorKind::StorageFull));
        let first = write_stdout_to(&state, &mut full, b"one\n");
        assert!(
            matches!(&first, StdoutOutcome::Failed(e) if e.kind() == std::io::ErrorKind::StorageFull),
            "the first failure is reported; got {first:?}"
        );
        // What fmt and lint do with a reported failure: record it for the exit code.
        state.note_io_failure();
        let repeat = write_stdout_to(&state, &mut full, b"two\n");
        assert!(
            matches!(repeat, StdoutOutcome::FailedAgain),
            "a repeat before stdout recovers is not reported; got {repeat:?}"
        );

        let mut empty = Sink::new(OnWrite::Accept);
        let nothing = write_stdout_to(&state, &mut empty, b"");
        assert!(matches!(nothing, StdoutOutcome::Written), "got {nothing:?}");
        let still = write_stdout_to(&state, &mut full, b"three\n");
        assert!(
            matches!(still, StdoutOutcome::FailedAgain),
            "a write of no bytes does not show that stdout recovered; got {still:?}"
        );

        let mut ok = Sink::new(OnWrite::Accept);
        let recovered = write_stdout_to(&state, &mut ok, b"four\n");
        assert!(
            matches!(recovered, StdoutOutcome::Written) && ok.bytes == b"four\n",
            "stdout recovers; got {recovered:?}"
        );

        let again = write_stdout_to(&state, &mut full, b"five\n");
        assert!(
            matches!(&again, StdoutOutcome::Failed(e) if e.kind() == std::io::ErrorKind::StorageFull),
            "a failure after stdout recovered is a new one, reported again; got {again:?}"
        );
        let repeat_again = write_stdout_to(&state, &mut full, b"six\n");
        assert!(
            matches!(repeat_again, StdoutOutcome::FailedAgain),
            "the new failure's repeat is not reported; got {repeat_again:?}"
        );
        assert_eq!(full.writes, 5, "every write is attempted");

        assert!(
            state.io_failed() && !state.stdout_closed(),
            "the recovery clears neither the recorded I/O failure nor anything else"
        );
        assert_eq!(
            final_exit_code(0, &state, ExitPolicy::Batch),
            IO_FAILURE_EXIT,
            "a batch run that lost a stdout write still exits 2 after stdout recovered"
        );
    }

    /// A batch run keeps going past a closed stdout, and reports any other stdout
    /// failure as one `mds::io` error naming stdout (#157).
    #[test]
    fn a_batch_run_ignores_a_closed_stdout_and_reports_any_other_failure() {
        assert!(StdoutOutcome::Written.into_batch_result().is_ok());
        assert!(StdoutOutcome::Closed.into_batch_result().is_ok());
        assert!(
            StdoutOutcome::FailedAgain.into_batch_result().is_ok(),
            "a repeated failure was already reported"
        );

        let failed = StdoutOutcome::Failed(std::io::Error::new(
            std::io::ErrorKind::StorageFull,
            "no space left",
        ))
        .into_batch_result();
        match failed {
            Err(mds::MdsError::Io { message }) => {
                assert_eq!(
                    message,
                    format!(
                        "cannot write to stdout: {}",
                        std::io::ErrorKind::StorageFull
                    ),
                    "the error's kind, not the text it carries (#390)"
                );
            }
            other => panic!("want Err(MdsError::Io {{ .. }}); got {other:?}"),
        }
    }

    /// Every combination of verdict, recorded facts and policy that matters, with the
    /// code each one must exit with — written out, not recomputed.
    #[test]
    fn final_exit_code_table() {
        struct Case {
            verdict: i32,
            closed: bool,
            failed: bool,
            policy: ExitPolicy,
            want: i32,
        }
        const fn case(
            verdict: i32,
            closed: bool,
            failed: bool,
            policy: ExitPolicy,
            want: i32,
        ) -> Case {
            Case {
                verdict,
                closed,
                failed,
                policy,
                want,
            }
        }
        use ExitPolicy::{Batch, WatchSession};
        let cases = [
            // Nothing recorded: the verdict stands.
            case(0, false, false, Batch, 0),
            case(1, false, false, Batch, 1),
            case(2, false, false, Batch, 2),
            case(3, false, false, Batch, 3),
            case(101, false, false, Batch, 101),
            // A closed pipe never changes the code.
            case(0, true, false, Batch, 0),
            case(1, true, false, Batch, 1),
            case(3, true, false, Batch, 3),
            // Any other failure lifts a batch run to at least 2.
            case(0, false, true, Batch, 2),
            case(1, false, true, Batch, 2),
            case(2, false, true, Batch, 2),
            case(3, false, true, Batch, 3),
            case(101, false, true, Batch, 101),
            case(0, true, true, Batch, 2),
            case(1, true, true, Batch, 2),
            // A live watch session keeps its verdict whatever was recorded.
            case(0, false, false, WatchSession, 0),
            case(1, false, false, WatchSession, 1),
            case(0, true, false, WatchSession, 0),
            case(0, false, true, WatchSession, 0),
            case(1, false, true, WatchSession, 1),
            case(3, false, true, WatchSession, 3),
            case(0, true, true, WatchSession, 0),
        ];
        for c in cases {
            let state = OutputState::new();
            if c.closed {
                state.note_stderr_closed();
            }
            if c.failed {
                state.note_io_failure();
            }
            assert_eq!(
                final_exit_code(c.verdict, &state, c.policy),
                c.want,
                "verdict {} closed={} failed={} {:?}",
                c.verdict,
                c.closed,
                c.failed,
                c.policy
            );
        }
        // An internal error is a file failure, not a panic. Watch keeps its verdict.
        let report = miette::Report::new(mds::MdsError::Internal);
        for (verdict, policy, want) in [(1, Batch, 101), (0, WatchSession, 0), (1, WatchSession, 1)]
        {
            let state = OutputState::new();
            state.note_io_failure();
            state.note_resource_limited();
            note_file_failure(&state, &report);
            assert!(!state.panicked());
            assert_eq!(final_exit_code(verdict, &state, policy), want, "{policy:?}");
        }
    }

    /// A run exits under the batch rule until a watch session goes live, and under the
    /// session rule from then on — whenever its output failure was recorded (#157).
    #[test]
    fn the_session_rule_applies_only_once_a_watch_session_is_live() {
        let state = OutputState::new();
        assert_eq!(
            state.exit_policy(),
            ExitPolicy::Batch,
            "a fresh run is a batch"
        );
        state.note_io_failure();
        assert_eq!(
            final_exit_code(0, &state, state.exit_policy()),
            2,
            "before a session goes live, an output failure lifts the exit code"
        );

        state.note_watch_live();
        assert_eq!(state.exit_policy(), ExitPolicy::WatchSession);
        assert_eq!(
            final_exit_code(0, &state, state.exit_policy()),
            0,
            "a live session keeps its verdict, the failure recorded before it included"
        );
        state.note_io_failure();
        state.note_watch_live();
        assert_eq!(
            final_exit_code(1, &state, state.exit_policy()),
            1,
            "going live is sticky, and a failure recorded after it changes nothing"
        );
    }

    /// A file refused for a resource limit lifts a batch run to 3, whatever the other
    /// files did, and changes nothing for a live watch session or after a panic (#157).
    #[test]
    fn a_resource_limited_file_lifts_a_batch_run_to_3() {
        use ExitPolicy::{Batch, WatchSession};
        // (verdict, I/O failed, policy, exit code without a limit, exit code with one)
        let cases = [
            (0, false, Batch, 0, 3),
            (1, false, Batch, 1, 3),
            (2, false, Batch, 2, 3),
            (3, false, Batch, 3, 3),
            // Both classes: the worse one wins.
            (1, true, Batch, 2, 3),
            (2, true, Batch, 2, 3),
            // A verdict above 3 stands.
            (101, false, Batch, 101, 101),
            // A live watch session keeps its verdict.
            (0, false, WatchSession, 0, 0),
            (1, true, WatchSession, 1, 1),
        ];
        for (verdict, io_failed, policy, without, with) in cases {
            let state = OutputState::new();
            if io_failed {
                state.note_io_failure();
            }
            assert_eq!(
                final_exit_code(verdict, &state, policy),
                without,
                "control: verdict {verdict} io_failed={io_failed} {policy:?} without a limit"
            );
            state.note_resource_limited();
            assert!(state.resource_limited());
            assert_eq!(
                final_exit_code(verdict, &state, policy),
                with,
                "verdict {verdict} io_failed={io_failed} {policy:?} with a limit"
            );
        }

        let state = OutputState::new();
        state.note_resource_limited();
        state.note_panicked();
        assert_eq!(
            final_exit_code(1, &state, Batch),
            101,
            "a panic still wins over a resource limit"
        );
    }

    /// One file's failure is recorded by the class of the exit code that file would have
    /// alone: the I/O class as an I/O failure, a resource limit as a resource limit, and
    /// any other failure not at all (#157).
    #[test]
    fn a_file_failure_is_recorded_by_the_class_of_its_exit_code() {
        use mds::MdsError;
        // (the failure, I/O failed, resource limited)
        let cases = [
            (
                miette::Report::new(MdsError::Io {
                    message: "cannot read a.mds".to_owned(),
                }),
                true,
                false,
            ),
            (
                miette::Report::new(MdsError::not_mds_file("a.txt")),
                true,
                false,
            ),
            (
                miette::Report::new(MdsError::ResourceLimit {
                    message: "module has more than 256 @block declarations".to_owned(),
                }),
                false,
                true,
            ),
            (
                miette::Report::new(MdsError::YamlError {
                    message: "bad frontmatter".to_owned(),
                }),
                false,
                false,
            ),
            (miette::miette!("an error with no code"), false, false),
        ];
        for (report, io_failed, resource_limited) in cases {
            let state = OutputState::new();
            note_file_failure(&state, &report);
            assert_eq!(
                (state.io_failed(), state.resource_limited()),
                (io_failed, resource_limited),
                "{report}"
            );
        }
    }

    // ── Panics (#389) ─────────────────────────────────────────────────────────

    /// A panic makes the run exit 101, whatever its verdict, whatever else it recorded,
    /// and under either policy — a live watch session's included.
    #[test]
    fn a_panic_exits_101_whatever_else_was_recorded() {
        use ExitPolicy::{Batch, WatchSession};
        // (verdict, stderr closed, I/O failed, policy)
        let cases = [
            (0, false, false, Batch),
            (1, false, false, Batch),
            (2, false, true, Batch),
            (3, false, true, Batch),
            (0, true, false, Batch),
            (0, false, false, WatchSession),
            (1, true, true, WatchSession),
            (3, false, true, WatchSession),
        ];
        for (verdict, closed, failed, policy) in cases {
            let state = OutputState::new();
            if closed {
                state.note_stderr_closed();
            }
            if failed {
                state.note_io_failure();
            }
            assert!(
                final_exit_code(verdict, &state, policy) < 101,
                "control: verdict {verdict} closed={closed} failed={failed} {policy:?} \
                 exits below 101 until a panic is recorded"
            );
            state.note_panicked();
            assert!(state.panicked());
            assert_eq!(
                final_exit_code(verdict, &state, policy),
                101,
                "verdict {verdict} closed={closed} failed={failed} {policy:?}"
            );
        }
    }

    /// `RUST_BACKTRACE` asks for a backtrace when it is set to anything but `0`, and for
    /// each frame's address as well when it is `full` — as std reads it.
    #[test]
    fn rust_backtrace_picks_the_backtrace_a_panic_prints() {
        let cases = [
            (None, None),
            (Some("0"), None),
            (Some("1"), Some(BacktraceStyle::Short)),
            (Some("full"), Some(BacktraceStyle::Full)),
            (Some(""), Some(BacktraceStyle::Short)),
            (Some("short"), Some(BacktraceStyle::Short)),
        ];
        for (value, want) in cases {
            assert_eq!(
                BacktraceStyle::from_env(value.map(OsStr::new)),
                want,
                "RUST_BACKTRACE={value:?}"
            );
        }
    }

    /// The text is two fixed lines: that the CLI failed, and the issue tracker of the
    /// repository its manifest names.
    #[test]
    fn the_internal_compiler_error_text_names_the_issue_tracker() {
        let lines: Vec<&str> = ICE_TEXT.lines().collect();
        assert_eq!(lines.len(), 2, "{ICE_TEXT:?}");
        assert!(ICE_TEXT.ends_with('\n'), "{ICE_TEXT:?}");
        assert_eq!(lines[0], "mds: internal compiler error");
        let tracker = concat!(env!("CARGO_PKG_REPOSITORY"), "/issues");
        assert!(
            tracker.starts_with("https://github.com/") && tracker.len() > 26,
            "the manifest names a GitHub repository: {tracker}"
        );
        assert!(lines[1].ends_with(tracker), "{ICE_TEXT:?}");
        assert!(
            ICE_TEXT.chars().all(|c| c == '\n' || !c.is_control()),
            "{ICE_TEXT:?}"
        );
    }

    /// Each line of a backtrace is WIRE-escaped on its own and keeps its line break: an
    /// ESC, a CR or a bidi override inside a line becomes its escape; a tab stays.
    #[test]
    fn a_backtrace_is_escaped_line_by_line() {
        let esc = char::from(0x1b);
        let cr = char::from(0x0d);
        let rlo = char::from_u32(0x202E).expect("U+202E");
        let code = |c: char| format!("{}u{:04X}", '\\', u32::from(c));
        let text = format!("frame {esc}[2J\n\tat {rlo}file.rs{cr}\nlast");
        assert_eq!(
            escape_each_line(&text),
            format!(
                "frame {}[2J\n\tat {}file.rs{}\nlast\n",
                code(esc),
                code(rlo),
                code(cr)
            )
        );
        // Control: clean text comes back as it is, each line ended by its line break.
        assert_eq!(escape_each_line("a\nb\n"), "a\nb\n");
    }

    /// `write_backtrace` writes a header and this thread's frames — the writer's own among
    /// them — every line escaped, in one write; a write that fails is not retried and does
    /// not panic.
    #[test]
    fn write_backtrace_writes_escaped_frames_and_ignores_a_failed_write() {
        for style in [BacktraceStyle::Short, BacktraceStyle::Full] {
            let mut sink = Sink::new(OnWrite::Accept);
            write_backtrace(&mut sink, style);
            let text = String::from_utf8(sink.bytes).expect("a backtrace is UTF-8");
            assert!(text.starts_with("stack backtrace:\n"), "{style:?}: {text}");
            assert!(
                text.contains("write_backtrace"),
                "{style:?}: the frames include the writer's own; {text}"
            );
            assert!(
                text.split_terminator('\n')
                    .all(|line| mds::sanitize_control_chars_wire(line) == line),
                "{style:?}: every line is escaped; {text}"
            );
            assert_eq!(sink.writes, 1, "{style:?}: one write");
            for kind in [
                std::io::ErrorKind::BrokenPipe,
                std::io::ErrorKind::StorageFull,
            ] {
                let mut failing = Sink::new(OnWrite::Fail(kind));
                write_backtrace(&mut failing, style);
                assert_eq!(
                    failing.writes, 1,
                    "{style:?}: a failed write is not retried"
                );
            }
        }
    }

    /// The trigger's payload is one no panic output may show: the sentinel, a raw ESC and
    /// the absolute path of the working directory.
    #[cfg(debug_assertions)]
    #[test]
    fn the_trigger_s_payload_carries_a_sentinel_an_esc_and_an_absolute_path() {
        let payload = panic_trigger::payload();
        let here = std::env::current_dir().expect("the working directory");
        assert!(here.is_absolute(), "{here:?}");
        assert!(payload.contains(panic_trigger::SENTINEL), "{payload:?}");
        assert!(payload.contains(char::from(0x1b)), "{payload:?}");
        assert!(payload.contains(&here.display().to_string()), "{payload:?}");
    }

    /// The child's streams: what the harness and the test wrote to stdout, and stderr.
    fn streams(child: &std::process::Output) -> (String, String) {
        (
            String::from_utf8_lossy(&child.stdout).into_owned(),
            String::from_utf8_lossy(&child.stderr).into_owned(),
        )
    }

    /// A panic that unwinds to [`catch_panic`] is reported once and caught, and the run
    /// goes on: the thread is not left unwinding, so a second panic is caught as well,
    /// and the run then ends through [`exit`] with 101 (#389).
    ///
    /// Control: the child really ran the test (the harness announced it), and ended at the
    /// funnel, not in the harness.
    #[test]
    fn a_caught_panic_is_reported_once_and_the_run_goes_on() {
        const NAME: &str = "output::tests::a_caught_panic_is_reported_once_and_the_run_goes_on";
        if child_process::is_child(NAME) {
            install_panic_hook();
            let first = catch_panic(|| {
                panic!("first");
            });
            let second = catch_panic(|| {
                panic!("second");
            });
            if first.is_err() && second.is_err() {
                let _ = write_stdout(b"after both catches\n");
            }
            exit(0);
        }
        let child = child_process::run(NAME);
        let (report, shown) = streams(&child);
        assert!(
            report.contains("running 1 test"),
            "control: the child ran the test; stdout:\n{report}"
        );
        assert_eq!(
            child.status.code(),
            Some(101),
            "a run that caught a panic exits 101; stdout:\n{report}\nstderr:\n{shown}"
        );
        assert!(
            report.contains("after both catches") && !report.contains("test result"),
            "both panics were caught and the run went on to the exit; stdout:\n{report}"
        );
        assert_eq!(shown, ICE_TEXT.repeat(2), "one text per panic");
    }

    /// #380, #389: a panic's report cancels the clear a rebuild asked for. The report is
    /// not preceded by one, and no print after it makes one: it is never wiped.
    ///
    /// Controls: the child really ran the test; a clear asked for after the panic is made
    /// before the next line, so the funnel in the child does clear.
    #[test]
    fn a_panic_report_cancels_the_pending_clear() {
        const NAME: &str = "output::tests::a_panic_report_cancels_the_pending_clear";
        if child_process::is_child(NAME) {
            install_panic_hook();
            OUTPUT_STATE.ask_clear();
            let caught = catch_panic(|| {
                panic!("while a clear is asked for");
            });
            assert!(caught.is_err(), "the panic unwound to the catch");
            assert!(
                !OUTPUT_STATE.clear_is_asked(),
                "the report took the request"
            );
            ewriteln!("after the report");
            OUTPUT_STATE.ask_clear();
            ewriteln!("control");
            exit(0);
        }
        let child = child_process::run(NAME);
        let (report, shown) = streams(&child);
        assert!(
            report.contains("running 1 test"),
            "control: the child ran the test; stdout:\n{report}"
        );
        assert_eq!(
            shown,
            format!("{ICE_TEXT}after the report\n{CLEAR_SEQUENCE}control\n"),
            "no clear before the report or after it; the control's clear comes before its line"
        );
        assert_eq!(
            child.status.code(),
            Some(101),
            "a run that caught a panic exits 101; stdout:\n{report}\nstderr:\n{shown}"
        );
    }

    /// A panic that nothing catches ends the process at once with 101, after the text —
    /// before the test harness, which would catch it, sees it.
    #[test]
    fn a_panic_nothing_catches_ends_the_run_at_once_with_101() {
        const NAME: &str = "output::tests::a_panic_nothing_catches_ends_the_run_at_once_with_101";
        if child_process::is_child(NAME) {
            install_panic_hook();
            panic!("uncaught");
        }
        let child = child_process::run(NAME);
        let (report, shown) = streams(&child);
        assert!(
            report.contains("running 1 test"),
            "control: the child ran the test; stdout:\n{report}"
        );
        assert_eq!(
            child.status.code(),
            Some(101),
            "stdout:\n{report}\nstderr:\n{shown}"
        );
        assert!(
            !report.contains("test result"),
            "the process ended at the panic, before the harness could report it; \
             stdout:\n{report}"
        );
        assert_eq!(shown, ICE_TEXT, "the text, once");
    }

    /// A panic while the thread is unwinding from another — a value that panics when it
    /// is dropped — ends the process at once with 101 instead of the abort std would make
    /// of it; each panic prints the text.
    #[test]
    fn a_panic_while_unwinding_ends_the_run_with_101_not_an_abort() {
        const NAME: &str =
            "output::tests::a_panic_while_unwinding_ends_the_run_with_101_not_an_abort";
        struct PanicsWhenDropped;
        impl Drop for PanicsWhenDropped {
            fn drop(&mut self) {
                panic!("second");
            }
        }
        if child_process::is_child(NAME) {
            install_panic_hook();
            let _ = catch_panic(|| {
                let _armed = PanicsWhenDropped;
                panic!("first");
            });
            let _ = write_stdout(b"the run went on\n");
            exit(0);
        }
        let child = child_process::run(NAME);
        let (report, shown) = streams(&child);
        assert!(
            report.contains("running 1 test"),
            "control: the child ran the test; stdout:\n{report}"
        );
        assert_eq!(
            child.status.code(),
            Some(101),
            "exit 101, not an abort (a signal: None); stdout:\n{report}\nstderr:\n{shown}"
        );
        assert!(
            !report.contains("the run went on") && !report.contains("test result"),
            "the process ended at the second panic; stdout:\n{report}"
        );
        assert_eq!(shown, ICE_TEXT.repeat(2), "one text per panic");
    }

    /// A panic is recorded before the hook writes anything, so the run exits 101 even
    /// when the hook cannot write: here the test holds stderr's lock, and a helper
    /// thread's hook waits on it while the test ends the run through [`exit`].
    ///
    /// Controls: the child really ran the test and ended at the funnel; the hook's write
    /// never landed, so it really was waiting.
    #[test]
    fn a_panic_is_recorded_before_the_hook_writes() {
        const NAME: &str = "output::tests::a_panic_is_recorded_before_the_hook_writes";
        /// How long the test waits for the helper's panic to be recorded: 500 polls,
        /// 10 ms apart.
        const POLLS: u32 = 500;
        const POLL: std::time::Duration = std::time::Duration::from_millis(10);
        if child_process::is_child(NAME) {
            install_panic_hook();
            // Held until the process ends, so the helper's hook blocks in its write.
            let _held = std::io::stderr().lock();
            let _helper = std::thread::spawn(|| panic!("helper"));
            for _ in 0..POLLS {
                if OUTPUT_STATE.panicked() {
                    break;
                }
                std::thread::sleep(POLL);
            }
            let _ = write_stdout(b"at the funnel\n");
            exit(0);
        }
        let child = child_process::run(NAME);
        let (report, shown) = streams(&child);
        assert!(
            report.contains("running 1 test"),
            "control: the child ran the test; stdout:\n{report}"
        );
        assert!(
            report.contains("at the funnel") && !report.contains("test result"),
            "control: the child ended at the funnel; stdout:\n{report}"
        );
        assert_eq!(
            shown, "",
            "control: the hook's write waited on the held lock until the process ended"
        );
        assert_eq!(
            child.status.code(),
            Some(101),
            "a panic whose hook cannot write still makes the run exit 101; stdout:\n{report}"
        );
    }

    /// A panic that unwinds into a function that cannot unwind — an `extern "C"`
    /// function — makes Rust raise a second panic there, one that cannot unwind at all.
    /// The thread is already unwinding from the first, so the hook ends the run with 101
    /// before std can abort.
    #[test]
    fn a_panic_into_a_function_that_cannot_unwind_ends_the_run_with_101_not_an_abort() {
        const NAME: &str = "output::tests::\
            a_panic_into_a_function_that_cannot_unwind_ends_the_run_with_101_not_an_abort";
        extern "C" fn cannot_unwind() {
            panic!("first");
        }
        if child_process::is_child(NAME) {
            install_panic_hook();
            let _ = catch_panic(|| cannot_unwind());
            let _ = write_stdout(b"the run went on\n");
            exit(0);
        }
        let child = child_process::run(NAME);
        let (report, shown) = streams(&child);
        assert!(
            report.contains("running 1 test"),
            "control: the child ran the test; stdout:\n{report}"
        );
        assert_eq!(
            child.status.code(),
            Some(101),
            "exit 101, not an abort (a signal: None); stdout:\n{report}\nstderr:\n{shown}"
        );
        assert!(
            !report.contains("the run went on") && !report.contains("test result"),
            "the process ended at the second panic; stdout:\n{report}"
        );
        assert_eq!(shown, ICE_TEXT.repeat(2), "one text per panic");
    }

    /// A caught panic's payload is dropped when dropping it runs no code of the panic's
    /// own — a `String` or `&'static str` message, which is what `panic!` makes — and is
    /// forgotten otherwise: any other payload's destructor is arbitrary code, and a panic
    /// in it would be a panic outside any catch.
    ///
    /// Control: the counting payload's destructor does run when it is dropped.
    #[test]
    fn a_caught_payload_is_dropped_only_when_that_runs_no_code_of_its_own() {
        use std::sync::atomic::AtomicUsize;
        use std::sync::Arc;
        struct CountsDrops(Arc<AtomicUsize>);
        impl Drop for CountsDrops {
            fn drop(&mut self) {
                self.0.fetch_add(1, Ordering::SeqCst);
            }
        }
        assert_eq!(
            dispose_payload(Box::new(String::from("a formatted message"))),
            Disposal::Dropped,
            "a `String` message is dropped"
        );
        assert_eq!(
            dispose_payload(Box::new("a literal message")),
            Disposal::Dropped,
            "a `&'static str` message is dropped"
        );
        let drops = Arc::new(AtomicUsize::new(0));
        drop(CountsDrops(Arc::clone(&drops)));
        assert_eq!(
            drops.load(Ordering::SeqCst),
            1,
            "control: the counting payload's destructor runs when it is dropped"
        );
        assert_eq!(
            dispose_payload(Box::new(CountsDrops(Arc::clone(&drops)))),
            Disposal::Forgotten,
            "any other payload is forgotten"
        );
        assert_eq!(
            drops.load(Ordering::SeqCst),
            1,
            "a forgotten payload's destructor never runs"
        );
    }

    /// The variable that makes [`a_working_directory_that_is_gone_fails_closed_in_core_s_words`]
    /// run as its own child.
    #[cfg(unix)]
    const GONE_CWD_CHILD: &str = "MDS_OUTPUT_GONE_CWD_CHILD";

    /// Where the working directory is gone, [`current_dir`] fails in exactly the words,
    /// and with the code, mds-core gives a string compile that needs it (#390) — core's
    /// function is private, so its words are taken from `mds::check_str_with` with no
    /// base directory — and [`canonicalize_out_dir`], and [`resolve_output_base`] through
    /// it, refuse a relative out-dir with that error instead of anchoring it at `"."`.
    ///
    /// The test removes its own working directory, which is the whole process's, so it
    /// runs as a child: this test binary, this one test. Controls: the child really ran
    /// it (the harness reports it passed); an absolute out-dir needs no working
    /// directory, in either function; and where it exists, [`current_dir`] is it.
    ///
    /// Unix-only: Windows cannot remove a directory that is a process's working directory.
    #[cfg(unix)]
    #[test]
    fn a_working_directory_that_is_gone_fails_closed_in_core_s_words() {
        const NAME: &str =
            "output::tests::a_working_directory_that_is_gone_fails_closed_in_core_s_words";
        if std::env::var_os(GONE_CWD_CHILD).is_some_and(|value| value == NAME) {
            let dir = tempfile::tempdir().expect("a temp dir");
            let gone = dir.path().join("gone");
            std::fs::create_dir(&gone).expect("create the working directory");
            std::env::set_current_dir(&gone).expect("move into it");
            std::fs::remove_dir(&gone).expect("remove it");

            let ours = current_dir().expect_err("no working directory to determine");
            let core = mds::check_str_with("Hello!\n", None, None)
                .expect_err("core needs the working directory as the base");
            assert!(
                matches!(
                    (&ours, &core),
                    (mds::MdsError::Io { .. }, mds::MdsError::Io { .. })
                ),
                "both mds::io: {ours:?} / {core:?}"
            );
            assert_eq!(ours.to_string(), core.to_string(), "core's words exactly");
            assert!(
                ours.to_string()
                    .starts_with("cannot determine current directory: "),
                "{ours}"
            );
            let refused = canonicalize_out_dir(Some(&PathBuf::from("out")))
                .expect_err("a relative out-dir has no directory to resolve against");
            assert_eq!(refused.to_string(), ours.to_string());
            let absolute = dir.path().join("out");
            assert_eq!(
                canonicalize_out_dir(Some(&absolute)).expect("an absolute out-dir resolves"),
                Some(absolute.clone()),
                "control: an absolute out-dir needs no working directory"
            );
            assert_eq!(canonicalize_out_dir(None).expect("no out-dir"), None);

            // `resolve_output_base` is where a directory run resolves its out-dir: it
            // refuses a relative one in the same words, and never falls back to a
            // default route or to a base anchored at `"."`.
            let refused = resolve_output_base(Some(&PathBuf::from("out")), &None)
                .expect_err("a relative out-dir is refused, not resolved");
            assert_eq!(refused.to_string(), ours.to_string());
            assert!(
                matches!(
                    refused.downcast_ref::<mds::MdsError>(),
                    Some(mds::MdsError::Io { .. })
                ),
                "mds::io: {refused:?}"
            );
            match resolve_output_base(Some(&absolute), &None).expect("an absolute out-dir") {
                OutputBase::Dir {
                    canonical, shown, ..
                } => {
                    assert_eq!(canonical, absolute, "control: resolved without one");
                    assert_eq!(shown, absolute, "control: shown as typed");
                }
                other => panic!("control: want Dir; got {other:?}"),
            }
            return;
        }
        assert_eq!(
            current_dir().expect("the working directory exists"),
            std::env::current_dir().expect("the working directory exists"),
            "control: where it exists, it is the working directory"
        );
        let binary = std::env::current_exe().expect("the test binary's path");
        let child = std::process::Command::new(binary)
            .args([NAME, "--exact", "--nocapture", "--test-threads=1"])
            .env(GONE_CWD_CHILD, NAME)
            .output()
            .expect("the child runs");
        let report = String::from_utf8_lossy(&child.stdout);
        assert!(
            child.status.success() && report.contains("1 passed"),
            "the child ran the test and it passed; stdout:\n{report}\nstderr:\n{}",
            String::from_utf8_lossy(&child.stderr)
        );
    }
}