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
//! The one write primitive: every file a release build of `mds` writes goes through it —
//! [`write_compiled`] for `mds build` and `mds watch` outputs and `.map` sidecars (#425),
//! [`write_compiled_and_look`] for a directory build's outputs below an out-dir (#160),
//! [`atomic_write_file`] for `mds init --force`'s starter, [`create_new`] for `mds init`'s
//! starter without `--force`, [`replace_if_unchanged`] for `mds fmt` and `mds lint --fix`
//! rewrites of a file argument and [`replace_owing_sync`] for those of a directory run's
//! files, [`write_over_own`] for an `mds watch` output after its source's change of kind
//! (#227, #160) — and every file it removes, through [`remove_proven`]. A debug build also
//! writes, by path and outside it, the readiness marker `mds watch` creates for the test
//! suite (`MDS_TEST_READY`). `tests/write_funnel.rs` keeps it the only one, that marker's
//! module aside.
//!
//! # Replace by rename
//!
//! The bytes go to a temporary file beside the target, which is then renamed over it: on a
//! local filesystem a crash or a kill of the run, or a full disk, never leaves a truncated
//! file, and a reader sees the whole old file or the whole new one. A network or FUSE
//! filesystem can report a full disk only when the file is closed, which the write does
//! not check, so there a write that is not synced ([`Durability::RenameOnly`]) can rename
//! a truncated file into place. [`Durability`] says whether the bytes, and the rename, are
//! also forced to stable storage first.
//!
//! # Below the anchor (#160)
//!
//! A [`WriteTarget`] names its file below an 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`, which the repository names and the user does not — the directory
//! `mds.json` is in, with `build.output_dir`'s own directories below it. The anchor is
//! resolved by path, in the form the run holds it — as typed, or, for a directory-mode
//! `--out-dir` and the anchors `mds watch` derives from its entry or directory argument,
//! as resolved once when the run started — so a symlinked anchor is followed (a
//! symlinked directory argument is refused before anything is written, #413); `mds
//! watch` refuses a write whose out-dir, as the user named it, now leads to another
//! directory ([`out_dir_moved`]), and names the directory its check found to the write,
//! which refuses an anchor it opens that is not that one — on unix by the descriptor it
//! opened ([`DirIdentity`]) — and one that is gone, without making it again. Nothing
//! below it is: each directory is opened from the one above it without following a
//! symlink, and the file is created, checked and renamed in the last one. A symlink
//! planted below the anchor, or swapped in while the write runs, is refused (`mds::io`,
//! exit 2) by the path the user knows it by, and nothing is written through it. The walk
//! is made for every write and nothing it opens is held for the next write — a directory
//! run of `mds fmt` or `mds lint --fix` holds a directory its rewrites went in only to sync
//! it once they are all made ([`DirectorySyncs`]) — so a directory replaced between two
//! writes is the one the next write finds.
//!
//! On unix the walk is `openat(O_DIRECTORY | O_NOFOLLOW)` from the anchor's descriptor
//! (`mkdirat` first for a directory an output needs) — each directory, the anchor
//! included, opened for search alone (`O_PATH`) on Linux and Android, so one the user may
//! write to and search but not list takes a write, and to read elsewhere, where such a
//! directory refuses it — then `fstatat(AT_SYMLINK_NOFOLLOW)` on
//! the target — never an open of it, which a FIFO would block, and a FIFO, a socket or a
//! device is refused — the temporary file `openat(O_CREAT | O_EXCL | O_NOFOLLOW)` beside it —
//! unlinked again if anything after that fails — `fchmod` to the permission bits of the
//! file it replaces when one user owns both, the durability tier's syncs, and `renameat`
//! (`mod unix`).
//!
//! Windows has no descriptor-relative walk in std: each directory below the anchor is
//! checked with `symlink_metadata` and refused when it is a symlink or a junction — the
//! name-surrogate reparse points std's `is_symlink` reports; a cloud-sync placeholder is
//! not one and stays writable — and the write then goes by path (`mod windows`); the
//! anchor `mds watch` checked is compared by path too, just before the walk. A
//! directory swapped for a link between those checks and the write is followed: the
//! residual SECURITY.md and spec §7.2 document.
//!
//! # Rewrites over the bytes read (#160)
//!
//! `mds fmt` and `mds lint --fix` rewrite a file they have read. [`read_stamped`] reads it
//! again below its anchor and holds the directory it is in — on unix its descriptor — with
//! a stamp of the file; [`replace_if_unchanged`] renames the rewrite into that directory
//! only while the file there is still the one read, so an edit made after the read is not
//! overwritten and a directory swapped after it never receives the rewrite.
//!
//! The rewrite's bytes are synced before the rename, and its directory after it
//! ([`Durability::Fsync`]): [`replace_if_unchanged`] syncs the directory at once, for a
//! file argument; [`replace_owing_sync`] leaves that to a directory run, which syncs each
//! directory once, after the last of its files, and shows a rewrite's status line only then
//! ([`DirectorySyncs`]).
//!
//! # A new file, never over another (#160)
//!
//! [`create_new`] gives the temporary file the target's name only where nothing has that
//! name, at the moment it is given — not at an earlier look — so a file that appears in
//! between is left as it is and the write refused. On unix the commit is a rename that
//! never replaces (`renameat2(RENAME_NOREPLACE)` on Linux and Android,
//! `renameatx_np(RENAME_EXCL)` on Apple platforms); where the platform, the kernel or the
//! filesystem has none, a hard link of the temporary file to the target, which never
//! replaces either, and the temporary name removed; and on a filesystem without hard
//! links, the content written in place into a target created exclusively (`O_CREAT |
//! O_EXCL | O_NOFOLLOW`) — still never over another file, but no longer all or nothing: a
//! write that fails part-way removes the file again while its name is still that file,
//! and a crash or a kill while it is written leaves it partly written. Windows moves the
//! temporary file into place without `MOVEFILE_REPLACE_EXISTING`.
//!
//! # Never over an MDS module or a file the run reads (#425)
//!
//! [`write_compiled`] renames an output over whatever file is at its target, except an MDS
//! module — a `.mds` file, or a `.md` file whose frontmatter declares `type: mds`, as
//! mds-core judges one ([`mds::check_module_type`]), which a template may import — and a
//! file the run reads ([`Inputs`]): its entry, the modules its compile imported, the
//! `--vars` file and the `mds.json` in force. An output whose own frontmatter declares
//! `type: mds` — a module a template generates — is one too, and replaces a module as it
//! rewrites itself, whoever wrote the file there; it is judged the same way, by its text,
//! and still never replaces a file the run reads. Just before the rename the file at the
//! target is looked at in the directory the write is in, without following a symlink. A
//! regular `.mds` file there is a module by its name alone and is never read. A regular
//! `.md` file there — each name's extension taken in any case, which on a case-insensitive
//! volume names a `.md` or `.mds` file — is read as opened in that directory — on unix `openat(O_NOFOLLOW | O_NONBLOCK)` from the
//! walk's descriptor, never by path — past its first line only when that is a frontmatter
//! fence, and then no further than the end of the frontmatter, all mds-core's check looks
//! at, nor than [`mds::MAX_FILE_SIZE`] bytes; one that cannot be read is refused, since
//! nothing tells it is no module. Any regular file there is compared, on unix by its device and inode,
//! with each file the run reads, looked up by its path at that moment, so one an editor has
//! replaced since it was read is the one compared, and a hard link to one is that file. A
//! module or an input is refused, the write leaves no temporary file, and the file is left
//! as it is. A symlink put there by then is replaced, never written through, as for every
//! write; a module or an input put there in the instant between that look and the rename
//! is replaced too. Windows looks and reads by path, as its write goes, judges the target
//! by the name of the file it opens — less the dots and spaces it ends in, which Windows
//! drops, so `lib.md.` and `lib.md ` are `lib.md` — and compares the canonical paths of
//! the target and of each input, since std gives no file index there: a hard link to an
//! input is another path, and is written over by the rename; a target whose canonical
//! path cannot be had, but that is not gone, is refused, as a look that fails is on unix.
//! A name holding a `:`, stream syntax there — `lib.mds::$DATA` is `lib.mds` itself — is
//! refused on Windows before anything is opened ([`names_a_stream`]).
//!
//! # Over the caller's own file, or as a new one (#160)
//!
//! [`write_over_own`] replaces a file only while it holds exactly what its caller last
//! wrote there — read again as a rewrite reads its file, and replaced as a rewrite
//! replaces it, only while it is still that file — and otherwise writes as [`create_new`]
//! does: a file the caller did not write, or one changed since, is never replaced. A file
//! there that cannot be read again is neither, as nothing tells which: the write fails
//! with the read's cause, and the file is left as it is.
//!
//! # A removal proves its file first (#160)
//!
//! [`remove_proven`] removes a stale output, a stale `.map` sidecar or a deleted source's
//! output only once the file is shown to be the one to remove. The directory it is in is
//! walked to as a write's is — never created, a symlink below the anchor refused — and
//! the file is looked at without following a symlink: a symlink there is refused, never
//! removed, and anything else that is not a regular file is left unopened. On unix the
//! file is then opened in that directory (`openat(O_NOFOLLOW | O_NONBLOCK)`), `fstat` must
//! find a regular file, the caller's proof reads it, and `fstatat(AT_SYMLINK_NOFOLLOW)`
//! must find at the name the stamp `fstat` gave — the same device and inode, size, and
//! modification and status-change times, as a rewrite compares — before `unlinkat`
//! removes it from the directory the walk opened: a file put in its place after it was
//! opened is left, and so is the same file written over after the proof read it. Only one
//! put there, or an edit made, in the instant between that look and the removal is
//! removed instead, as is an edit that keeps the file's size and times on a filesystem
//! whose clock is coarser than the time it takes. Windows checks each directory below the
//! anchor as a write does, and removes by path: the file is closed after its proof,
//! looked at again by path — the same size, and modification and creation times — and
//! then removed by its name, so one put there in between is removed instead.
//!
//! A directory build learns whether anything has a stale output's name from the write of
//! the output beside it, which looks there just after its rename, without following a
//! symlink ([`write_compiled_and_look`]) — on unix with `fstatat(AT_SYMLINK_NOFOLLOW)` on
//! the descriptor its walk opened, before it closes it; on Windows by path, as its write
//! goes: a name nothing has needs no removal, and no walk is made for one; anything there,
//! and a look that fails, is dealt with as before — removed, if at all, only through
//! [`remove_proven`].
//!
//! # Contract (#226)
//!
//! This is replace-by-rename, not an in-place rewrite. The target receives a NEW inode, so
//! the write does NOT preserve hard links (other links keep the old content), ACLs,
//! extended attributes (xattrs), or owner/group of the original file; only the permission
//! bits are carried over (unix) — never a setuid, setgid or sticky bit, and only from a
//! file the user who writes owns: one another user owns lends none, and the new file has
//! the mode a new file is created with. Hard-link preservation is out of scope by
//! construction (it would require truncate-in-place and forfeit crash safety);
//! ACL/xattr/owner-group preservation is not planned — MDS only rewrites its own outputs
//! and `.mds` sources.

use std::borrow::Cow;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::path::{Component, Path, PathBuf};

use crate::output::{io_cause, safe_inline, safe_path, WriteTarget};

/// How hard [`atomic_write_file`] works to make the new bytes survive a crash.
///
/// Atomicity — a reader sees either the whole old file or the whole new one, never a
/// truncated mix — is unconditional: it comes from the rename, not from a sync. This knob
/// only chooses whether the data is forced to stable storage *before* that rename, and the
/// rename itself after it.
///
/// The split exists because the two families of file MDS writes have different recovery
/// costs, and on macOS `sync_all()` is `F_FULLFSYNC` — a full drive cache flush, ~7 ms per
/// file. Measured on a 500-template `mds watch` startup (#227): 1.44 s → 4.69 s, and the
/// `cli_watch` suite 4.2 s → 8.3 s.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Durability {
    /// `sync_all()` on the temporary file before the rename — `F_FULLFSYNC` on Apple
    /// platforms, and a plain `fsync` on a filesystem that refuses that — and, on unix, on
    /// its directory after it — where the filesystem can sync a directory at all: one that refuses it
    /// does not fail a write that has landed, and a directory sync that fails otherwise
    /// leaves the write landed, said apart from one that failed
    /// ([`Rewritten::NotSynced`]). A directory run's rewrites sync each directory once,
    /// after all of them in it ([`DirectorySyncs`]). For files whose content exists nowhere
    /// else: `mds fmt` and `mds lint --fix` rewrite the user's hand-authored `.mds` source in
    /// place, so bytes lost to a power failure are lost for good.
    Fsync,
    /// Rename only. For **derived** artifacts — compiled outputs and `.map` sidecars —
    /// which are reproducible by re-running `mds build`, and `mds init`'s fixed starter. A
    /// crash can leave the previous file or an unflushed new one; either way the fix is one
    /// more run, and paying `F_FULLFSYNC` per file to avoid it costs more than it saves.
    RenameOnly,
}

/// Whether a write creates the directories its file goes in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Parents {
    /// A compiled output or a `.map` sidecar: a missing anchor is created by path, as typed,
    /// and a missing directory below it inside the anchor, the first time a write needs it.
    Create,
    /// A rewrite of a file that was just read (`mds fmt`, `mds lint --fix`), or `mds
    /// init`'s starter: the directory must already be there, and nothing is created.
    Existing,
}

/// One directory as the filesystem tells it from another at the same path: its device
/// and inode on unix, with its birth time where the filesystem keeps one, since a
/// directory made where a deleted one was can be given the freed inode; its creation time
/// alone on Windows, where std gives no file index. `mds watch` checks its out-dir by it
/// before each write below it, and the write is made only in the directory the check
/// found ([`WriteTarget::below_checked_anchor`], #160).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct DirIdentity {
    #[cfg(unix)]
    dev: u64,
    #[cfg(unix)]
    ino: u64,
    created: Option<std::time::SystemTime>,
}

impl DirIdentity {
    /// The directory at `path`, through a symlink; `None` when there is none.
    pub(crate) fn of(path: &Path) -> Option<Self> {
        let meta = std::fs::metadata(path).ok().filter(|meta| meta.is_dir())?;
        Some(Self::of_metadata(&meta))
    }

    /// The directory `meta` describes.
    fn of_metadata(meta: &std::fs::Metadata) -> Self {
        #[cfg(unix)]
        use std::os::unix::fs::MetadataExt as _;

        Self {
            #[cfg(unix)]
            dev: meta.dev(),
            #[cfg(unix)]
            ino: meta.ino(),
            created: meta.created().ok(),
        }
    }
}

/// Write `content` to `target` atomically, below its anchor and through no symlink there
/// (see the module docs).
///
/// A symlink at the target itself — live or dangling — is refused rather than replaced,
/// and so, on unix, is a FIFO, a socket or a device, which the write never opens.
/// An existing file the user owns keeps its permission bits, never a setuid, setgid or
/// sticky bit (unix); a new one — and one replacing a file another user owns — is
/// created with mode `0666 & !umask`, as `std::fs::write` creates one. `parents` says
/// whether missing directories are created; `durability` whether the write is synced.
///
/// # Errors
///
/// Every failure is `mds::io` (exit 2, #157), worded `cannot write <file>: <cause>`
/// whichever step failed (#309): the file named by `target.shown`, the form the caller's
/// status line names it by, never by `target.path` (#390), and the cause naming no path
/// ([`io_cause`]). A symlink refused below the anchor is named in the cause, below the
/// anchor's shown form — `cannot write out/sub/x.md: refusing to follow a symlink at
/// out/sub` — and one at the target says `refusing to replace a symlink`; a FIFO, a
/// socket or a device there says `not a regular file`; an anchor that is not the directory
/// the caller checked ([`WriteTarget::below_checked_anchor`]), or that is gone — it is not
/// made again — is refused as [`out_dir_moved`] words it, before anything below it is
/// opened.
///
/// In the [`Durability::Fsync`] tier a directory that cannot be synced after the rename is
/// an error too, though the file holds `content`: `<file> written, but its directory could
/// not be synced: <cause>` ([`replace_if_unchanged`] gives it back apart, as
/// [`Rewritten::NotSynced`]).
pub(crate) fn atomic_write_file(
    target: &WriteTarget,
    content: &str,
    durability: Durability,
    parents: Parents,
) -> std::result::Result<(), mds::MdsError> {
    write_below_anchor(target, content, durability, parents, Commit::Replace(None))
        .map_err(|failure| worded(target, failure))?
        .synced(target)
        .map(drop)
}

/// Write a compiled output, or its `.map` sidecar, to `target` as [`atomic_write_file`]
/// writes one — [`Durability::RenameOnly`], since a rebuild reproduces it, creating the
/// directories it goes in — but never over one of `inputs`, the files the run reads, nor,
/// unless `content` is itself an MDS module, over one (#425; see the module docs): a `.mds`
/// file, or a `.md` file whose frontmatter declares `type: mds`, is a source a template
/// imports, and the
/// entry, an imported module, the `--vars` file or the `mds.json` in force is what the
/// output was made from — none is an output to replace. An output that declares
/// `type: mds` itself is a module a template generates, and replaces one as it rewrites
/// itself.
///
/// # Errors
///
/// As [`atomic_write_file`]; and, for an output that is no module, a module at the target
/// or a regular `.md` file there that cannot be read to tell, and a file the run reads,
/// are refused before the rename — `cannot write <file>: refusing to replace an MDS module
/// (an output that declares type: mds is a generated module, and is rebuilt from its
/// source)`, `cannot write <file>: cannot tell whether it is an MDS module: <cause>` with
/// the read's cause, or `cannot write <file>: refusing to replace a file this run reads` —
/// and left as they are, with no temporary file left behind.
pub(crate) fn write_compiled(
    target: &WriteTarget,
    content: &str,
    inputs: &Inputs,
) -> std::result::Result<(), mds::MdsError> {
    write_compiled_in(target, content, inputs).map(drop)
}

/// [`write_compiled`], giving back the directory the output went in — on unix still open.
fn write_compiled_in(
    target: &WriteTarget,
    content: &str,
    inputs: &Inputs,
) -> std::result::Result<imp::Dir, mds::MdsError> {
    write_below_anchor(
        target,
        content,
        Durability::RenameOnly,
        Parents::Create,
        Commit::Output {
            inputs,
            module: declares_a_module(content),
        },
    )
    .map_err(|failure| worded(target, failure))?
    .synced(target)
}

/// Write a compiled output as [`write_compiled`] does, then look at `beside`, a file in the
/// same directory — a directory build's stale output, the other kind's of the same name —
/// without following a symlink, and never reading it (#160): on unix in that directory as
/// the write's walk opened it, before it is closed; on Windows by path, as the write goes
/// (the residual the module docs describe). Where nothing has its name there is nothing to
/// prove or remove, and the second walk a removal makes is not needed; where something
/// has it, or the look cannot tell, the caller deals with it as before — removing it, if
/// at all, through [`remove_proven`], whose own walk and checks are made as for any
/// removal. A `beside` that is not in the directory the output went in is not looked at,
/// and is [`Beside::Something`].
///
/// # Errors
///
/// As [`write_compiled`]; nothing is looked at when the write fails.
pub(crate) fn write_compiled_and_look(
    target: &WriteTarget,
    content: &str,
    inputs: &Inputs,
    beside: &WriteTarget,
) -> std::result::Result<Beside, mds::MdsError> {
    let dir = write_compiled_in(target, content, inputs)?;
    Ok(match (Below::of(target), Below::of(beside)) {
        (Ok(written), Ok(beside))
            if written.anchor == beside.anchor && written.dirs == beside.dirs =>
        {
            imp::look(&dir, beside.name)
        }
        _ => Beside::Something,
    })
}

/// What [`write_compiled_and_look`] found at the name it looked at beside its output.
#[must_use]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Beside {
    /// Nothing had the name.
    Nothing,
    /// Something had it — a file, a symlink, a directory, anything — or the look could not
    /// tell: the caller deals with it.
    Something,
}

/// The files a run reads — its entry, the modules its compile imported, the `--vars` file
/// and the `mds.json` in force — which [`write_compiled`] never writes an output over
/// (#425). Each is held by its path and looked up again by every write, so the file there
/// then is the one compared: an editor that saves by replacing the file leaves no stale
/// identity behind. One can be held as a search instead ([`Inputs::and_found_from`]), made
/// only by a write that meets a file at its target.
#[derive(Debug, Clone, Default)]
pub(crate) struct Inputs {
    files: Vec<PathBuf>,
    found: Option<Found>,
}

/// An input found from a path rather than named — the `mds.json` nearest a directory run's
/// source (#425): the file `find` finds from `from`, if any.
#[derive(Debug, Clone)]
struct Found {
    from: PathBuf,
    find: fn(&Path) -> Option<PathBuf>,
}

impl Inputs {
    /// The files at `files`, each as the run reads it — through a symlink.
    pub(crate) fn new(files: impl IntoIterator<Item = PathBuf>) -> Self {
        Self {
            files: files.into_iter().collect(),
            found: None,
        }
    }

    /// These inputs and the file `find` finds from `from`. The search is made only by a
    /// write that meets a file at its target, and then at that moment, after the files
    /// named: where nothing is, nothing is replaced, so nothing needs to be found.
    #[must_use = "the search is part of the inputs only in the value returned"]
    pub(crate) fn and_found_from(self, from: &Path, find: fn(&Path) -> Option<PathBuf>) -> Self {
        Self {
            found: Some(Found {
                from: from.to_path_buf(),
                find,
            }),
            ..self
        }
    }

    /// Each input's path: the files named, then the one found, searched for only once
    /// every file named has been taken.
    fn paths(&self) -> impl Iterator<Item = Cow<'_, Path>> {
        let named = self.files.iter().map(|file| Cow::Borrowed(file.as_path()));
        let found = self
            .found
            .iter()
            .filter_map(|found| (found.find)(&found.from))
            .map(Cow::Owned);
        named.chain(found)
    }
}

/// Write `content` to `target` as [`atomic_write_file`] does, but only as a new file
/// (#160): the temporary file is given the target's name only where nothing has it at
/// that moment (see the module docs), so a file that appears after any earlier look at
/// the target — `mds init`'s own check included — is never replaced.
///
/// # Errors
///
/// [`NotCreated::Exists`] for a target that is there — before the write or appearing
/// while it runs: the file is left as it is and no temporary file is left behind, and the
/// caller words the refusal, as it words its own earlier look's. Any other failure is
/// [`NotCreated::Failed`], worded as [`atomic_write_file`] words it — a symlink at the
/// target is refused as it refuses one.
pub(crate) fn create_new(
    target: &WriteTarget,
    content: &str,
    durability: Durability,
    parents: Parents,
) -> std::result::Result<(), NotCreated> {
    match write_below_anchor(target, content, durability, parents, Commit::New) {
        Ok(landed) => landed.synced(target).map(drop).map_err(NotCreated::Failed),
        Err(Failure::Exists) => Err(NotCreated::Exists),
        Err(failure) => Err(NotCreated::Failed(worded(target, failure))),
    }
}

/// Why [`create_new`], or [`write_over_own`], did not write its file.
#[derive(Debug)]
pub(crate) enum NotCreated {
    /// Something has the target's name: it was there, or it appeared while the write ran
    /// — for [`write_over_own`], anything but the caller's own file, unchanged.
    Exists,
    /// The write failed, as [`atomic_write_file`] words a failure.
    Failed(mds::MdsError),
}

/// Write `content` to `target` over the file its caller wrote there — while it still holds
/// exactly `own`, what was last written, and only until the rename, as
/// [`replace_if_unchanged`] replaces the file it read — or else only where nothing has the
/// target's name, as [`create_new`] writes (#160). `own` is `None` when the caller wrote
/// nothing there. `mds watch` writes the output of a source's new kind so: a file the
/// session did not write, or one changed since it wrote it, is never replaced.
///
/// # Errors
///
/// [`NotCreated::Exists`] for anything else at the target — a file with other bytes, or
/// one changed before the rename, a symlink, a directory, a FIFO, a socket or a device —
/// left as it is, with no temporary file left behind. Any other failure is
/// [`NotCreated::Failed`], worded as [`atomic_write_file`] words it — a file at the
/// target that cannot be read again included, with the read's cause: whether it is still
/// the caller's cannot be told, and it is left as it is.
pub(crate) fn write_over_own(
    target: &WriteTarget,
    own: Option<&str>,
    content: &str,
    durability: Durability,
    parents: Parents,
) -> std::result::Result<(), NotCreated> {
    let held = match own {
        Some(own) => own_file(target, own),
        None => Ok(None),
    };
    let written = match held {
        Ok(Some(held)) => {
            pause_before_replace();
            imp::replace_held(held, content.as_bytes(), durability)
        }
        // Only a new file may take the name, and the commit, never the read, finds whether
        // something has it.
        Ok(None) => write_below_anchor(target, content, durability, parents, Commit::New),
        Err(failure) => Err(failure),
    };
    match written {
        Ok(landed) => landed.synced(target).map(drop).map_err(NotCreated::Failed),
        Err(
            Failure::Exists | Failure::Changed | Failure::LinkAtTarget | Failure::NotARegularFile,
        ) => Err(NotCreated::Exists),
        Err(failure) => Err(NotCreated::Failed(worded(target, failure))),
    }
}

/// [`write_over_own`]'s read of `target`, as a rewrite reads its file: held when it holds
/// exactly `own`; `None` when it is not the caller's — other bytes, gone, a symlink,
/// anything but a regular file — or when nothing is on the way to it, a directory below
/// the anchor gone since; and a read that fails otherwise — the file may not be read,
/// say — is the write's failure, never taken for a file that is not the caller's.
fn own_file(target: &WriteTarget, own: &str) -> std::result::Result<Option<imp::Held>, Failure> {
    let below = Below::of(target)?;
    match imp::read_stamped(&below, target.checked_anchor(), own.as_bytes()) {
        Ok(held) => Ok(Some(held)),
        Err(Failure::Changed | Failure::LinkAtTarget | Failure::NotARegularFile) => Ok(None),
        Err(Failure::Io(e)) if imp::nothing_below(&e) => Ok(None),
        Err(failure) => Err(failure),
    }
}

/// [`atomic_write_file`], [`write_compiled`] and [`create_new`] share this: resolve
/// `target` below its anchor, then write through it as `commit` says; the directory the
/// file went in is given back — on unix still open, for its caller to close.
fn write_below_anchor(
    target: &WriteTarget,
    content: &str,
    durability: Durability,
    parents: Parents,
    commit: Commit<'_>,
) -> std::result::Result<Landed, Failure> {
    let below = Below::of(target)?;
    let anchor = target.checked_anchor();
    imp::write(
        &below,
        anchor,
        content.as_bytes(),
        durability,
        parents,
        commit,
    )
}

/// A write that landed: its file holds the new bytes. `dir` is the directory it went in —
/// on unix still open — and `not_synced` the cause of a failed sync of that directory after
/// the rename, which only the [`Durability::Fsync`] tier makes, and only on unix.
struct Landed {
    dir: imp::Dir,
    not_synced: Option<std::io::Error>,
}

impl Landed {
    /// The directory the file went in, once it is synced as its tier asks; one that could
    /// not be synced is [`not_synced`]'s error instead, for a caller that has no way to say
    /// a write landed but was not synced.
    fn synced(self, target: &WriteTarget) -> std::result::Result<imp::Dir, mds::MdsError> {
        match self.not_synced {
            None => Ok(self.dir),
            Some(cause) => Err(not_synced(target, &cause)),
        }
    }
}

/// How the temporary file a write has filled takes the target's name.
#[derive(Debug, Clone, Copy)]
enum Commit<'i> {
    /// Renamed over whatever file is there — for a rewrite, only while that file still
    /// holds the stamp it was read with.
    Replace(Option<&'i imp::Stamp>),
    /// Renamed over whatever file is there, unless it is one of the files the run reads, or
    /// an MDS module while the output itself is none (`module`) ([`write_compiled`], #425).
    Output { inputs: &'i Inputs, module: bool },
    /// Given the name only where nothing has it ([`create_new`]).
    New,
}

/// A file `mds fmt` or `mds lint --fix` is about to rewrite, read again by
/// [`read_stamped`] and held for [`replace_if_unchanged`] (#160): the directory it was
/// read in, still open on unix, its name there, and a stamp of the file as it was read.
pub(crate) struct ReadForRewrite {
    target: WriteTarget,
    held: imp::Held,
}

/// Read `target` again for its rewrite, below its anchor and through no symlink there or
/// at the file, and hold it if its bytes are `read` — the text the rewrite was made from,
/// which the caller read by path, with every check a source read makes (#160).
///
/// What is held is the directory the file was read in — its descriptor, on unix — and a
/// stamp of the file: on unix its device, inode, size and modification and status-change
/// times; on Windows, which has no descriptor-relative walk in std, its size and its
/// modification and creation times, by path. [`replace_if_unchanged`] writes into that
/// directory, whatever its path leads to by then, and only over that file.
///
/// # Errors
///
/// `mds::io`, worded as [`atomic_write_file`] words a failure — a symlink below the
/// anchor or at the file is refused as it refuses one — and, for a file whose bytes are
/// not `read` any more, or that is gone, `cannot write <file>: changed since it was read;
/// not written`, the file named by `target.shown`.
pub(crate) fn read_stamped(
    target: &WriteTarget,
    read: &str,
) -> std::result::Result<ReadForRewrite, mds::MdsError> {
    let below = Below::of(target).map_err(|e| io_error(&target.shown, io_cause(&e)))?;
    let held = imp::read_stamped(&below, target.checked_anchor(), read.as_bytes())
        .map_err(|f| worded(target, f))?;
    Ok(ReadForRewrite {
        target: target.clone(),
        held,
    })
}

/// Replace the file `read` holds with `content`, by way of a temporary file in the
/// directory it was read in, unless it has changed since it was read (#160): just before
/// the rename the file is looked at again in that directory, and a stamp that differs
/// refuses the rewrite, leaving the file — the edit made to it — as it is, and no
/// temporary file.
///
/// A rewrite whose rename landed is [`Rewritten`], whether or not the directory could then
/// be synced: the file holds `content` either way, and the caller says so before it reports
/// a sync that failed ([`Rewritten::NotSynced`]).
///
/// # Errors
///
/// `mds::io`, the file left as it was: `cannot write <file>: changed since it was read; not
/// written` for a file that changed, else as [`atomic_write_file`] words a failure.
pub(crate) fn replace_if_unchanged(
    read: ReadForRewrite,
    content: &str,
    durability: Durability,
) -> std::result::Result<Rewritten, mds::MdsError> {
    pause_before_replace();
    let ReadForRewrite { target, held } = read;
    let landed =
        imp::replace_held(held, content.as_bytes(), durability).map_err(|f| worded(&target, f))?;
    Ok(match landed.not_synced {
        None => Rewritten::Done,
        Some(cause) => Rewritten::NotSynced(not_synced(&target, &cause)),
    })
}

/// A rewrite [`replace_if_unchanged`] made: its file holds the new bytes.
#[must_use]
#[derive(Debug)]
pub(crate) enum Rewritten {
    /// As its [`Durability`] tier asks.
    Done,
    /// The rename landed, but in the [`Durability::Fsync`] tier the directory it was made
    /// in could not be synced after it, so a crash may still undo it: the `mds::io` error
    /// `<file> written, but its directory could not be synced: <cause>`, for the caller to
    /// report in place of saying the file was written, as it may say so only for a write
    /// that is durable — the run exits 2.
    NotSynced(mds::MdsError),
}

/// Replace the file `read` holds with `content` as [`replace_if_unchanged`] does in the
/// [`Durability::Fsync`] tier — its bytes synced before the rename — but leave the sync of
/// the directory it is renamed in, which makes the rename itself durable, to the caller
/// (#160): the [`Renamed`] given back owes it, and a directory run of `mds fmt` or `mds lint
/// --fix` makes it through [`DirectorySyncs`], once for all its rewrites in that directory.
///
/// # Errors
///
/// As [`replace_if_unchanged`].
pub(crate) fn replace_owing_sync(
    read: ReadForRewrite,
    content: &str,
) -> std::result::Result<Renamed, mds::MdsError> {
    pause_before_replace();
    let ReadForRewrite { target, held } = read;
    let dir = imp::rename_held(held, content.as_bytes()).map_err(|f| worded(&target, f))?;
    Ok(Renamed { target, dir })
}

/// A rewrite [`replace_owing_sync`] made: its file holds the new bytes, and the sync of the
/// directory they were renamed in is still owed — until [`DirectorySyncs`] makes it, a crash
/// may undo the rename. On unix it holds that directory open.
#[must_use]
pub(crate) struct Renamed {
    target: WriteTarget,
    dir: imp::Dir,
}

/// The directory syncs a directory run of `mds fmt` or `mds lint --fix` owes its rewrites
/// (#160). Each directory a rewrite was renamed in is synced once, when the run is past the
/// last of its files there — every file of the run counts, rewritten or not — rather than
/// once for each rewrite, and only then is each of those rewrites given back to be shown
/// ([`Synced`]): a status line shown for a rewrite still means its rename is durable.
///
/// The directory synced is the one its first owed rewrite was renamed in, held open on
/// unix; a later rewrite renamed into another directory at the same path — one swapped in
/// meanwhile — has the owed ones before it synced first, and starts owing anew. In the order
/// both runs take their files — the walk's, and `mds lint`'s sorted keys — the files below a
/// directory come together, so only the directories of the current file and of those above
/// it owe a sync at once: a run holds no more of them open than its walk is deep.
pub(crate) struct DirectorySyncs<T> {
    /// For each file of the run, by its place in the run, its directory: an index into
    /// `last` and `owed`.
    directory_of: Vec<usize>,
    /// For each directory, the place of the run's last file in it.
    last: Vec<usize>,
    /// For each directory, the rewrites renamed in it whose sync is owed.
    owed: Vec<Option<Owed<T>>>,
}

/// Rewrites whose directory's sync is owed, and that directory.
struct Owed<T> {
    dir: imp::Dir,
    files: Vec<(WriteTarget, T)>,
}

impl<T> DirectorySyncs<T> {
    /// What a run over `files`, in the order it takes them, owes: nothing yet. A file's
    /// directory is its path's parent, as the run names it.
    pub(crate) fn new<'p>(files: impl IntoIterator<Item = &'p Path>) -> Self {
        let files = files.into_iter();
        let mut directories: HashMap<&Path, usize> = HashMap::new();
        let mut directory_of = Vec::with_capacity(files.size_hint().0);
        let mut last: Vec<usize> = Vec::new();
        for (place, file) in files.enumerate() {
            let parent = file.parent().unwrap_or(Path::new(""));
            let directory = *directories.entry(parent).or_insert_with(|| {
                last.push(place);
                last.len() - 1
            });
            if let Some(at) = last.get_mut(directory) {
                *at = place;
            }
            directory_of.push(directory);
        }
        let owed = std::iter::repeat_with(|| None).take(last.len()).collect();
        Self {
            directory_of,
            last,
            owed,
        }
    }

    /// `renamed` is the rewrite of the run's file at `place`, and `item` what its caller
    /// shows for it once its directory is synced: owed until the run is past its
    /// directory's last file ([`DirectorySyncs::past`]). What comes back is what was owed
    /// before it in another directory at the same path, synced now ([`Flushed`]); a place
    /// the run did not name is synced at once, and comes back itself.
    pub(crate) fn landed(&mut self, place: usize, renamed: Renamed, item: T) -> Option<Flushed<T>> {
        let Renamed { target, dir } = renamed;
        let owed = self
            .directory_of
            .get(place)
            .and_then(|&directory| self.owed.get_mut(directory));
        let Some(owed) = owed else {
            return Some(flush(Owed {
                dir,
                files: vec![(target, item)],
            }));
        };
        if let Some(batch) = owed
            .as_mut()
            .filter(|batch| imp::same_directory(&batch.dir, &dir))
        {
            // One directory: the one already held is synced for both.
            batch.files.push((target, item));
            return None;
        }
        owed.replace(Owed {
            dir,
            files: vec![(target, item)],
        })
        .map(flush)
    }

    /// The run is past its file at `place`: when that was the last of its directory's
    /// files, what is owed there is synced now, and comes back ([`Flushed`]).
    pub(crate) fn past(&mut self, place: usize) -> Option<Flushed<T>> {
        let &directory = self.directory_of.get(place)?;
        if self.last.get(directory) != Some(&place) {
            return None;
        }
        self.owed.get_mut(directory)?.take().map(flush)
    }
}

/// Sync `owed`'s directory, then close it.
fn flush<T>(owed: Owed<T>) -> Flushed<T> {
    let Owed { dir, files } = owed;
    let failure = imp::sync_owed(&dir).err();
    drop(dir);
    Flushed {
        files: files.into_iter(),
        failure,
    }
}

/// The rewrites one directory sync was made for, in the order they were renamed: each comes
/// out once, as [`Synced`] says that sync went.
pub(crate) struct Flushed<T> {
    files: std::vec::IntoIter<(WriteTarget, T)>,
    failure: Option<std::io::Error>,
}

impl<T> Iterator for Flushed<T> {
    type Item = Synced<T>;

    fn next(&mut self) -> Option<Synced<T>> {
        let (target, item) = self.files.next()?;
        Some(match &self.failure {
            None => Synced::Durable(item),
            Some(cause) => Synced::NotSynced(item, not_synced(&target, cause)),
        })
    }
}

/// What became of a rewrite whose directory's sync a run owed ([`DirectorySyncs`]), with what
/// its caller shows for it.
#[must_use]
#[derive(Debug)]
pub(crate) enum Synced<T> {
    /// Its directory is synced: the caller shows the rewrite done.
    Durable(T),
    /// Its directory could not be synced — the one failure for every rewrite owed there — so
    /// a crash may still undo it, though the file holds it: the `mds::io` error `<file>
    /// written, but its directory could not be synced: <cause>`, for the caller to report in
    /// place of the rewrite's status line — the run exits 2.
    NotSynced(T, mds::MdsError),
}

/// Remove `target` once it is shown to be a regular file `proof` accepts, below its anchor
/// and through no symlink there or at the file (#160; see the module docs): `proof` reads
/// the file as opened in the directory the walk reached, and the name is removed from that
/// directory only while it is still that file. A target that names the directory its
/// caller checked ([`WriteTarget::below_checked_anchor`]) is removed only below that one,
/// as a write is made only there. Nothing is created, and a file that is not there —
/// nor, below the anchor, a directory on its way — is nothing to remove.
///
/// # Errors
///
/// [`NotRemoved`], the file left as it is, with a cause that names no path but the
/// shown form of a refused directory, for the caller to word after the file's name.
pub(crate) fn remove_proven(
    target: &WriteTarget,
    proof: impl FnOnce(&mut std::fs::File) -> std::io::Result<bool>,
) -> std::result::Result<Removal, NotRemoved> {
    let below = Below::of(target).map_err(|e| NotRemoved::Failed(safe_inline(io_cause(&e))))?;
    imp::remove(&below, target.checked_anchor(), proof).map_err(|f| not_removed(target, f))
}

/// What [`remove_proven`] found at its file, and did.
#[must_use]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Removal {
    /// The file was proven, and is removed.
    Removed,
    /// Nothing has its name, nor — below the anchor — a directory on its way.
    Missing,
    /// A regular file its proof does not accept: left as it is.
    Kept,
}

/// Why [`remove_proven`] did not remove a file that is, or may be, there.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum NotRemoved {
    /// Not a regular file — a directory, a FIFO, a socket or a device: never opened.
    NotAFile,
    /// A symlink, live or dangling: refused, never followed — mds writes none.
    Link,
    /// It could not be looked at or read, so nothing is known of it: the cause, escaped.
    Unreadable(String),
    /// Refused — a symlink below the anchor, an anchor that is not the directory checked,
    /// another file at its name by the time it was to go — or the removal failed: the
    /// cause, escaped.
    Failed(String),
}

impl NotRemoved {
    /// The refusal of a removal below an out-dir that now leads to a different directory
    /// than the one the `mds watch` session started with, as [`out_dir_moved`] refuses a
    /// write there (#160).
    pub(crate) fn out_dir_moved() -> Self {
        Self::Failed(OUT_DIR_MOVED.to_owned())
    }

    /// Why the file was not removed, as its caller's message gives it after the file's
    /// name.
    pub(crate) fn cause(&self) -> &str {
        match self {
            Self::NotAFile => NOT_A_REGULAR_FILE,
            Self::Link => SYMLINK_REMOVAL_REFUSAL,
            Self::Unreadable(cause) | Self::Failed(cause) => cause,
        }
    }
}

/// `failure`, a removal of `target` that did not happen, as [`NotRemoved`] gives it.
fn not_removed(target: &WriteTarget, failure: Failure) -> NotRemoved {
    let cause = |e: &std::io::Error| safe_inline(io_cause(e));
    match failure {
        Failure::NotARegularFile => NotRemoved::NotAFile,
        Failure::Unreadable(e) => NotRemoved::Unreadable(cause(&e)),
        Failure::AnchorMoved => NotRemoved::out_dir_moved(),
        Failure::Changed => NotRemoved::Failed(CHANGED_WHILE_CHECKED.to_owned()),
        Failure::LinkBelowAnchor { depth } => NotRemoved::Failed(format!(
            "{FOLLOW_REFUSAL} at {}",
            safe_path(&shown_directory(target, depth))
        )),
        Failure::LinkAtTarget => NotRemoved::Link,
        // Only a new file's commit meets a file at its name, and only an output's refuses a
        // module or an input; a removal never does either.
        Failure::Exists => NotRemoved::Failed(cause(&std::io::ErrorKind::AlreadyExists.into())),
        Failure::Module => NotRemoved::Failed(MODULE_REFUSAL.to_owned()),
        Failure::Input => NotRemoved::Failed(INPUT_REFUSAL.to_owned()),
        Failure::UnreadMarkdown(e) | Failure::Io(e) => NotRemoved::Failed(cause(&e)),
    }
}

/// `failure`, a write of `target` that did not land, as the `mds::io` error it reports.
fn worded(target: &WriteTarget, failure: Failure) -> mds::MdsError {
    match failure {
        Failure::AnchorMoved => out_dir_moved(target),
        Failure::Changed => io_error(&target.shown, CHANGED_SINCE_READ.to_owned()),
        // Only a new file's commit meets a file at its target, and [`create_new`] hands that
        // to its caller to word; any other write that did would have failed like any other.
        Failure::Exists => io_error(
            &target.shown,
            io_cause(&std::io::ErrorKind::AlreadyExists.into()),
        ),
        Failure::LinkBelowAnchor { depth } => io_error(
            &target.shown,
            format!(
                "{FOLLOW_REFUSAL} at {}",
                safe_path(&shown_directory(target, depth))
            ),
        ),
        Failure::LinkAtTarget => io_error(&target.shown, SYMLINK_REFUSAL.to_owned()),
        Failure::Module => io_error(
            &target.shown,
            format!("{MODULE_REFUSAL} ({MODULE_WAY_OUT})"),
        ),
        Failure::Input => io_error(&target.shown, INPUT_REFUSAL.to_owned()),
        Failure::UnreadMarkdown(e) => mds::MdsError::Io {
            message: format!(
                "cannot write {}: {MODULE_UNKNOWN}: {}",
                safe_path(&target.shown),
                safe_inline(io_cause(&e))
            ),
        },
        Failure::NotARegularFile => io_error(&target.shown, NOT_A_REGULAR_FILE.to_owned()),
        // Only a removal's look at its file, or its proof's read, fails as unreadable.
        Failure::Unreadable(e) | Failure::Io(e) => io_error(&target.shown, io_cause(&e)),
    }
}

/// Why `mds init` refuses a target that is there — found by its own look, or met by
/// [`create_new`]'s commit ([`NotCreated::Exists`]) — after the file's name.
pub(crate) const ALREADY_EXISTS: &str = "already exists (use --force to overwrite)";

/// Why [`atomic_write_file`] refuses to replace a symlink at its target.
const SYMLINK_REFUSAL: &str = "refusing to replace a symlink";

/// Why [`remove_proven`] refuses to remove a symlink at its file: mds writes none.
const SYMLINK_REMOVAL_REFUSAL: &str = "refusing to remove a symlink";

/// Why [`write_compiled`] refuses to replace an MDS module (#425).
const MODULE_REFUSAL: &str = "refusing to replace an MDS module";

/// The way out of [`MODULE_REFUSAL`], after it in brackets: an output that declares `type:
/// mds` is a module itself, so it may replace one (#425). An `mds::io` error has no help of
/// its own to carry it, so it ends the cause.
const MODULE_WAY_OUT: &str =
    "an output that declares type: mds is a generated module, and is rebuilt from its source";

/// Why [`write_compiled`] refuses to replace one of the files the run reads (#425).
const INPUT_REFUSAL: &str = "refusing to replace a file this run reads";

/// Why [`write_compiled`] refuses to replace a `.md` file it cannot read, before the
/// read's cause: nothing tells it is no MDS module (#425).
const MODULE_UNKNOWN: &str = "cannot tell whether it is an MDS module";

/// Why [`replace_if_unchanged`] leaves a file that is not as it was read.
const CHANGED_SINCE_READ: &str = "changed since it was read; not written";

/// Why [`remove_proven`] leaves a file whose name, by the time it was to be removed, was
/// another file's than the one its proof read.
const CHANGED_WHILE_CHECKED: &str = "changed while it was checked";

/// Why [`atomic_write_file`] refuses to replace, and [`remove_proven`] to remove, a FIFO, a
/// socket, a device or a directory.
const NOT_A_REGULAR_FILE: &str = "not a regular file";

/// Why [`atomic_write_file`] refuses a symlink at a directory below the anchor.
const FOLLOW_REFUSAL: &str = "refusing to follow a symlink";

/// Why a `mds watch` session refuses a write below an out-dir that now leads elsewhere.
const OUT_DIR_MOVED: &str = "the output directory now resolves to a different directory; \
                             restart mds watch to follow it";

/// The `mds::io` refusal of a write below an out-dir whose path, as the user named it,
/// now leads to a different directory than the one the `mds watch` session started with
/// (#160): `cannot write <file>: …`, the file named by `target.shown`, as every failure
/// to write it is.
pub(crate) fn out_dir_moved(target: &WriteTarget) -> mds::MdsError {
    io_error(&target.shown, OUT_DIR_MOVED.to_owned())
}

/// The `mds::io` error for a write that failed: `shown`, the file, escaped (#390), then
/// the cause, escaped too.
fn io_error(shown: &Path, cause: String) -> mds::MdsError {
    mds::MdsError::Io {
        message: format!("cannot write {}: {}", safe_path(shown), safe_inline(cause)),
    }
}

/// Why a write that landed may not survive a crash, after the file's name: the directory
/// its rename was made in could not be synced ([`Durability::Fsync`]).
const NOT_SYNCED: &str = "written, but its directory could not be synced";

/// The `mds::io` error for a write of `target` that landed in a directory that could not
/// then be synced, `e` the sync's failure: `<file> written, but its directory could not be
/// synced: <cause>`, the file named by `target.shown` and both escaped, as a failed write
/// names them ([`io_error`]).
fn not_synced(target: &WriteTarget, e: &std::io::Error) -> mds::MdsError {
    mds::MdsError::Io {
        message: format!(
            "{} {NOT_SYNCED}: {}",
            safe_path(&target.shown),
            safe_inline(io_cause(e))
        ),
    }
}

/// `target`'s shown form cut after the directory `depth` levels below the anchor: the
/// directory a refused symlink is, as the user knows it. `shown` ends in the same names
/// below the anchor as `path` does, so the cut is counted from its end.
fn shown_directory(target: &WriteTarget, depth: usize) -> PathBuf {
    let components: Vec<Component<'_>> = target.shown.components().collect();
    match components.len().checked_sub(target.below_anchor()) {
        Some(above) if above + depth < components.len() => {
            components[..=above + depth].iter().collect()
        }
        _ => target.shown.clone(),
    }
}

/// What failed in a write, before it is worded.
#[derive(Debug)]
enum Failure {
    /// The anchor opened is not the directory the caller checked.
    AnchorMoved,
    /// The file a rewrite read is not as it was read: its bytes, or its stamp, differ, or
    /// it is gone; or another file has the name of the one a removal proved.
    Changed,
    /// A new file's target is there, or appeared before the commit ([`create_new`]).
    Exists,
    /// The directory `depth` levels below the anchor is a symlink.
    LinkBelowAnchor { depth: usize },
    /// The target itself is a symlink.
    LinkAtTarget,
    /// An output's target is an MDS module ([`write_compiled`], #425).
    Module,
    /// An output's target is one of the files the run reads ([`write_compiled`], #425).
    Input,
    /// An output's target, a `.md` file, could not be opened or read to tell whether it
    /// is an MDS module ([`write_compiled`], #425).
    UnreadMarkdown(std::io::Error),
    /// The target itself is a FIFO, a socket or a device — or, for a removal, a
    /// directory.
    NotARegularFile,
    /// A file to be removed could not be looked at, or its proof could not read it.
    Unreadable(std::io::Error),
    /// Anything else.
    Io(std::io::Error),
}

impl From<std::io::Error> for Failure {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}

#[cfg(unix)]
impl From<rustix::io::Errno> for Failure {
    fn from(e: rustix::io::Errno) -> Self {
        Self::Io(e.into())
    }
}

/// A target split at its anchor: the directory the write resolves by path, the directories
/// below it in order, and the file's name.
#[derive(Debug, PartialEq, Eq)]
struct Below<'a> {
    anchor: PathBuf,
    dirs: Vec<&'a OsStr>,
    name: &'a OsStr,
}

impl<'a> Below<'a> {
    /// `target`'s last [`WriteTarget::below_anchor`] components, each a plain name — never
    /// `..` or `.` — and the anchor above them (`.` when that is nothing).
    ///
    /// # Errors
    ///
    /// "is a directory" when the last component is not a name (`.`, `..`, a root: a
    /// directory, never a file) or the path ends in a separator, or in a separator and a
    /// `.` (`out/`, `out/.`), which `Path::components` drops; "invalid input" when one above
    /// it is not a name, or when the path has fewer components than the target says lie
    /// below its anchor; and on Windows "invalid filename" when the name is in stream
    /// syntax ([`names_a_stream`]).
    fn of(target: &'a WriteTarget) -> std::io::Result<Self> {
        if ends_as_a_directory(&target.path) {
            return Err(std::io::ErrorKind::IsADirectory.into());
        }
        let components: Vec<Component<'a>> = target.path.components().collect();
        let below = target.below_anchor();
        let above = components
            .len()
            .checked_sub(below)
            .filter(|_| below > 0)
            .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::InvalidInput))?;
        let (anchor, under) = components.split_at(above);
        let Some((last, dirs)) = under.split_last() else {
            return Err(std::io::ErrorKind::InvalidInput.into());
        };
        let Component::Normal(name) = *last else {
            return Err(std::io::ErrorKind::IsADirectory.into());
        };
        if cfg!(windows) && names_a_stream(name) {
            return Err(std::io::ErrorKind::InvalidFilename.into());
        }
        let dirs = dirs
            .iter()
            .map(|component| match component {
                Component::Normal(dir) => Ok(*dir),
                _ => Err(std::io::Error::from(std::io::ErrorKind::InvalidInput)),
            })
            .collect::<std::io::Result<Vec<&'a OsStr>>>()?;
        let anchor = if anchor.is_empty() {
            PathBuf::from(".")
        } else {
            anchor.iter().collect()
        };
        Ok(Self { anchor, dirs, name })
    }
}

/// Whether `name` holds a `:`, which Windows reads as NTFS stream syntax (#425):
/// `lib.mds::$DATA` names the file `lib.mds` itself and `lib.md:x` a stream of `lib.md`,
/// so a write by such a name lands on a file its name does not say — one the module check,
/// which goes by the name, would not see. [`Below::of`] refuses such a name there; on unix
/// a `:` is an ordinary character.
fn names_a_stream(name: &OsStr) -> bool {
    name.as_encoded_bytes().contains(&b':')
}

/// Whether `path` ends in a separator, or in a separator and a `.`: the spelling of a
/// directory, whatever the name before it.
fn ends_as_a_directory(path: &Path) -> bool {
    // A separator is ASCII on every platform, and no byte of a multi-byte character is.
    let separator = |byte: &u8| std::path::is_separator(char::from(*byte));
    match path.as_os_str().as_encoded_bytes() {
        [.., last] if separator(last) => true,
        [.., before, b'.'] => separator(before),
        _ => false,
    }
}

/// Whether `name` can be a `.md` file's: an MDS module when its frontmatter declares
/// `type: mds` (#425). The extension is taken in any case, since on a case-insensitive
/// volume `LIB.MD` is the file `lib.md`, which mds-core judges by its name on disk.
fn names_markdown(name: &OsStr) -> bool {
    Path::new(name)
        .extension()
        .is_some_and(|ext| ext.eq_ignore_ascii_case("md"))
}

/// Whether `name` can be a `.mds` file's: an MDS source, which mds-core takes for a module
/// by its name alone, whatever it holds (#425). The extension is taken in any case, as
/// [`names_markdown`] takes it.
fn names_source(name: &OsStr) -> bool {
    Path::new(name)
        .extension()
        .is_some_and(|ext| ext.eq_ignore_ascii_case("mds"))
}

/// `name`, the last component of a path, as code units — UTF-16 on Windows — less the
/// dots and spaces it ends in, which Windows drops from the last component of a path it
/// opens: there `lib.md.` and `lib.md ` are the file `lib.md`, so the name a write is
/// judged by is this one (#425). A name of nothing but dots and spaces is kept whole.
#[cfg(any(windows, test))]
fn as_windows_opens<T: Copy + Into<u32>>(name: &[T]) -> &[T] {
    match name
        .iter()
        .rposition(|&unit| !matches!(unit.into(), 0x2E | 0x20))
    {
        Some(last) => &name[..=last],
        None => name,
    }
}

/// Whether `file`, opened at a `.md` file's name ([`names_markdown`]), is an MDS module an
/// output must never replace (#425): its frontmatter declares `type: mds`, as mds-core's
/// own check takes a module ([`mds::check_module_type`]). That check looks no further
/// than the frontmatter — from the fence on the first line to the first `\n---` after it —
/// so no more is read: nothing past a first line that is no fence, and past a fence one
/// read at a time until the close, at most one read beyond it, and no further than
/// [`mds::MAX_FILE_SIZE`] bytes in all — a fence that does not close by then is no module,
/// as mds-core reads no more of any module. Bytes that are not UTF-8 are judged with each
/// replaced.
fn is_mds_module(file: &mut std::fs::File) -> std::io::Result<bool> {
    /// The longest frontmatter fence: `---` and a CRLF.
    const FENCE: &[u8] = b"---\r\n";
    /// What closes the frontmatter for mds-core: the first `---` that begins a line.
    const CLOSE: &[u8] = b"\n---";
    /// How much one read past the fence takes.
    const ONE_READ: u64 = 8 * 1024;
    let fence = u64::try_from(FENCE.len()).unwrap_or(u64::MAX);
    let mut head = mds::read_at_most(file, fence, 0)?;
    let after_fence = if head.starts_with(b"---\n") {
        FENCE.len() - 1
    } else if head.starts_with(FENCE) {
        FENCE.len()
    } else {
        return Ok(false);
    };
    // Where the close is looked for: from the end of the fence, then from just before the
    // bytes the last read added, so a close split between two reads is found.
    let mut from = after_fence;
    for _ in 0..=mds::MAX_FILE_SIZE / ONE_READ {
        if let Some(at) = head[from..]
            .windows(CLOSE.len())
            .position(|bytes| bytes == CLOSE)
        {
            head.truncate(from + at + CLOSE.len());
            break;
        }
        let held = u64::try_from(head.len()).unwrap_or(u64::MAX);
        let more = mds::read_at_most(
            file,
            ONE_READ.min(mds::MAX_FILE_SIZE.saturating_sub(held)),
            0,
        )?;
        if more.is_empty() {
            break;
        }
        from = head.len().saturating_sub(CLOSE.len() - 1).max(after_fence);
        head.extend(more);
    }
    Ok(declares_a_module(&String::from_utf8_lossy(&head)))
}

/// Whether `text`, a `.md` file's, declares `type: mds` in its frontmatter: an MDS module,
/// as mds-core's own check takes one ([`mds::check_module_type`], #425). The check is given
/// a constant `.md` key — mds-core judges a `.md` key by the text alone — so no path
/// becomes text.
fn declares_a_module(text: &str) -> bool {
    const MARKDOWN_KEY: &str = "module.md";
    let key = mds::ModuleRef::keyed(MARKDOWN_KEY).typed(MARKDOWN_KEY);
    mds::check_module_type(key, text).is_ok()
}

/// The name every temporary file starts with, so a crash's leftover is recognisable.
const TEMP_PREFIX: &str = ".mds-tmp-";

/// The extension every temporary file ends with: never `mds`, so no directory walk takes
/// one for a source.
const TEMP_SUFFIX: &str = ".tmp";

#[cfg(unix)]
use unix as imp;
#[cfg(windows)]
use windows as imp;

#[cfg(unix)]
mod unix {
    use std::ffi::{OsStr, OsString};
    use std::fs::File;
    use std::io::Write as _;
    use std::os::fd::{AsFd as _, BorrowedFd, OwnedFd};
    use std::path::Path;

    use rustix::fs::{self, AtFlags, FileType, Mode, OFlags, CWD};
    use rustix::io::Errno;

    use super::{
        Below, Beside, Commit, DirIdentity, Durability, Failure, Inputs, Landed, Parents, Removal,
        TEMP_PREFIX, TEMP_SUFFIX,
    };

    /// How the walk opens a directory: for search alone (`O_PATH`) on Linux and Android, so
    /// a directory the user may write to and search but not list — a drop box, `-wx` —
    /// takes a write, as it did before the walk; rustix offers no such open elsewhere, so
    /// there the directory is opened to read, which such a directory refuses.
    #[cfg(any(target_os = "linux", target_os = "android"))]
    const SEARCH: OFlags = OFlags::PATH;

    /// How the walk opens a directory: to read, as no search-only open is to be had here.
    #[cfg(not(any(target_os = "linux", target_os = "android")))]
    const SEARCH: OFlags = OFlags::RDONLY;

    /// The anchor: a directory, resolved by path — through a symlink the user named.
    const ANCHOR: OFlags = SEARCH.union(OFlags::DIRECTORY).union(OFlags::CLOEXEC);

    /// A directory below the anchor: never through a symlink.
    const BELOW: OFlags = SEARCH
        .union(OFlags::DIRECTORY)
        .union(OFlags::NOFOLLOW)
        .union(OFlags::CLOEXEC);

    /// The directory a rewrite's rename was made in, opened again from the walk's
    /// descriptor to read, the one way it can be synced: an `O_PATH` descriptor cannot be.
    const TO_SYNC: OFlags = OFlags::RDONLY
        .union(OFlags::DIRECTORY)
        .union(OFlags::CLOEXEC);

    /// The temporary file: a new file, never through a symlink.
    const TEMP: OFlags = OFlags::WRONLY
        .union(OFlags::CREATE)
        .union(OFlags::EXCL)
        .union(OFlags::NOFOLLOW)
        .union(OFlags::CLOEXEC);

    /// The file a new file's commit writes in place, on a filesystem without hard links: a
    /// new file, never one already there, and never through a symlink.
    const IN_PLACE: OFlags = OFlags::WRONLY
        .union(OFlags::CREATE)
        .union(OFlags::EXCL)
        .union(OFlags::NOFOLLOW)
        .union(OFlags::CLOEXEC);

    /// A file a rewrite reads again, a removal's proof reads, or an output's target read to
    /// tell an MDS module (#425): never through a symlink, and never waiting on a FIFO put
    /// in its place, which the read then refuses as no longer the file read, the removal as
    /// not a regular file, and the output's look as no module.
    const READ: OFlags = OFlags::RDONLY
        .union(OFlags::NOFOLLOW)
        .union(OFlags::NONBLOCK)
        .union(OFlags::CLOEXEC);

    /// The mode a new file asks for: `0666`, which the umask then narrows, as for
    /// `std::fs::write`.
    const NEW_FILE: Mode = Mode::from_raw_mode(0o666);

    /// The mode a file that replaces another is created with: owner-only, so its bytes are
    /// never readable by anyone the file it replaces did not allow.
    const OWNER_ONLY: Mode = Mode::RUSR.union(Mode::WUSR);

    /// The bits of its mode a replaced file lends the file that replaces it: read, write
    /// and execute for its owner, its group and others — never setuid, setgid or sticky.
    const PERMISSION_BITS: fs::RawMode = 0o777;

    /// The mode a directory a write creates asks for: `0777`, narrowed by the umask.
    const NEW_DIR: Mode = Mode::from_raw_mode(0o777);

    /// How many temporary names a write tries before it gives up: each is random, so a
    /// clash is another writer's file or a leftover, and sixteen in a row is not chance.
    pub(super) const MAX_TEMP_ATTEMPTS: usize = 16;

    /// The directory a write's file went in: the descriptor its walk opened, closed when it
    /// drops.
    pub(super) type Dir = OwnedFd;

    /// Write `content` to `below.name` in the directory [`walk`] opens, as `commit` says,
    /// and give that directory back.
    pub(super) fn write(
        below: &Below<'_>,
        anchor: Option<DirIdentity>,
        content: &[u8],
        durability: Durability,
        parents: Parents,
        commit: Commit<'_>,
    ) -> Result<Landed, Failure> {
        let dir = walk(below, anchor, parents)?;
        replace(dir, below.name, content, durability, commit)
    }

    /// Whether anything has `name` in `dir`, looked at without following a symlink: only a
    /// name nothing has is [`Beside::Nothing`]; a failed look is [`Beside::Something`].
    pub(super) fn look(dir: &Dir, name: &OsStr) -> Beside {
        match fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW) {
            Err(Errno::NOENT) => Beside::Nothing,
            _ => Beside::Something,
        }
    }

    /// Open the directory `below.name` is in: the anchor by path — and, when `anchor`
    /// names the directory it must be, refuse another, and one gone, which is never made
    /// again by path — then each directory below it from the one above without following
    /// a symlink.
    fn walk(
        below: &Below<'_>,
        anchor: Option<DirIdentity>,
        parents: Parents,
    ) -> Result<OwnedFd, Failure> {
        let mut dir = match anchor {
            Some(checked) => match open_anchor(&below.anchor, Parents::Existing) {
                Ok(dir) => opened_as_checked(dir, checked)?,
                Err(Failure::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {
                    return Err(Failure::AnchorMoved)
                }
                Err(failure) => return Err(failure),
            },
            None => open_anchor(&below.anchor, parents)?,
        };
        for (depth, name) in below.dirs.iter().enumerate() {
            let next = open_below(dir.as_fd(), name, parents)
                .map_err(|errno| below_failure(dir.as_fd(), name, depth, errno))?;
            dir = next;
        }
        Ok(dir)
    }

    /// A file as a rewrite read it (#160): its device and inode, its size, and the times
    /// it was last modified and last changed, each to the nanosecond where the filesystem
    /// keeps one. Writing to the file, renaming another over it, or changing its mode
    /// changes at least one of them — within the resolution of the filesystem's clock.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(super) struct Stamp {
        device: i128,
        inode: i128,
        size: i128,
        modified: (i128, i128),
        changed: (i128, i128),
    }

    impl Stamp {
        /// The stamp `stat` gives. Every field widens without loss, whatever integer type
        /// the platform gives it.
        fn of(stat: &fs::Stat) -> Self {
            Self {
                device: i128::from(stat.st_dev),
                inode: i128::from(stat.st_ino),
                size: i128::from(stat.st_size),
                modified: (i128::from(stat.st_mtime), i128::from(stat.st_mtime_nsec)),
                changed: (i128::from(stat.st_ctime), i128::from(stat.st_ctime_nsec)),
            }
        }

        /// Whether `name` in `dir`, looked at without following a symlink, is still the
        /// file this stamp was taken of, unchanged.
        fn holds(&self, dir: BorrowedFd<'_>, name: &OsStr) -> bool {
            fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW)
                .is_ok_and(|stat| Self::of(&stat) == *self)
        }
    }

    /// A file a rewrite read, held for its replace: the directory it was read in, still
    /// open, its name there, and its stamp.
    pub(super) struct Held {
        dir: OwnedFd,
        name: OsString,
        stamp: Stamp,
    }

    /// Read `below.name` again in the directory [`walk`] opens — below `anchor`, the
    /// directory checked, when there is one — without following a symlink, and hold it if
    /// its bytes are `read`: the stamp is taken of the file opened, before its bytes are
    /// read, so a change made while they are read changes it too.
    pub(super) fn read_stamped(
        below: &Below<'_>,
        anchor: Option<DirIdentity>,
        read: &[u8],
    ) -> Result<Held, Failure> {
        let dir = walk(below, anchor, Parents::Existing)?;
        let mut file = match open_to_read(dir.as_fd(), below.name) {
            Ok(file) => file,
            Err(Errno::LOOP) => return Err(Failure::LinkAtTarget),
            Err(Errno::NOENT) => return Err(Failure::Changed),
            // A socket refuses the open, and so can a device: no longer the file read, as
            // nothing but a regular file is (below) — not a file that cannot be read.
            Err(_) if is_no_regular_file(dir.as_fd(), below.name) => return Err(Failure::Changed),
            Err(e) => return Err(e.into()),
        };
        let stat = fs::fstat(&file)?;
        if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile {
            return Err(Failure::Changed);
        }
        // One byte more than was read tells a file that grew from one that did not.
        let expected = u64::try_from(read.len()).unwrap_or(u64::MAX);
        if mds::read_at_most(&mut file, expected.saturating_add(1), expected)? != read {
            return Err(Failure::Changed);
        }
        Ok(Held {
            dir,
            name: below.name.to_owned(),
            stamp: Stamp::of(&stat),
        })
    }

    /// Replace the file `held` was read from with `content`, in the directory it was read
    /// in, unless its stamp has changed by the time of the rename.
    pub(super) fn replace_held(
        held: Held,
        content: &[u8],
        durability: Durability,
    ) -> Result<Landed, Failure> {
        let commit = Commit::Replace(Some(&held.stamp));
        replace(held.dir, &held.name, content, durability, commit)
    }

    /// Replace the file `held` was read from with `content` as [`replace_held`] does in the
    /// [`Durability::Fsync`] tier, but without the directory's sync after the rename: the
    /// directory is given back for its caller to sync ([`sync_owed`]).
    pub(super) fn rename_held(held: Held, content: &[u8]) -> Result<Dir, Failure> {
        let commit = Commit::Replace(Some(&held.stamp));
        put(held.dir, &held.name, content, Durability::Fsync, commit)
    }

    /// Sync `dir`, a directory a rewrite was renamed into by [`rename_held`]
    /// ([`sync_directory`]).
    pub(super) fn sync_owed(dir: &Dir) -> std::io::Result<()> {
        sync_directory(dir.as_fd())
    }

    /// Whether `a` and `b` are one directory: the same device and inode, which neither can
    /// lose to another directory while it is open. One that cannot be looked at is taken
    /// for another, so that each is synced.
    pub(super) fn same_directory(a: &Dir, b: &Dir) -> bool {
        match (fs::fstat(a), fs::fstat(b)) {
            (Ok(a), Ok(b)) => a.st_dev == b.st_dev && a.st_ino == b.st_ino,
            _ => false,
        }
    }

    /// Remove `below.name` from the directory [`walk`] opens — creating none — once it is
    /// a regular file `proof` accepts, and only while the name is still that file (#160).
    /// It is looked at without following a symlink first, so anything but a regular file
    /// is never opened; then opened without following one, and never waiting on a FIFO
    /// put in its place; its [`Stamp`], taken of the file opened before `proof` reads it,
    /// must be the name's again, looked at once `proof` has read it, before it is
    /// unlinked.
    pub(super) fn remove(
        below: &Below<'_>,
        anchor: Option<DirIdentity>,
        proof: impl FnOnce(&mut File) -> std::io::Result<bool>,
    ) -> Result<Removal, Failure> {
        let dir = match walk(below, anchor, Parents::Existing) {
            Ok(dir) => dir,
            Err(Failure::Io(e)) if nothing_below(&e) => return Ok(Removal::Missing),
            Err(failure) => return Err(failure),
        };
        let name = below.name;
        match fs::statat(&dir, name, AtFlags::SYMLINK_NOFOLLOW) {
            Ok(stat) => match FileType::from_raw_mode(stat.st_mode) {
                FileType::RegularFile => {}
                FileType::Symlink => return Err(Failure::LinkAtTarget),
                _ => return Err(Failure::NotARegularFile),
            },
            // A name too long for the file system names no file: none can be there.
            Err(Errno::NOENT | Errno::NAMETOOLONG) => return Ok(Removal::Missing),
            Err(e) => return Err(Failure::Unreadable(e.into())),
        }
        let mut file = match open_to_read(dir.as_fd(), name) {
            Ok(file) => file,
            Err(Errno::LOOP) => return Err(Failure::LinkAtTarget),
            Err(Errno::NOENT) => return Ok(Removal::Missing),
            Err(e) => return Err(Failure::Unreadable(e.into())),
        };
        let opened = fs::fstat(&file).map_err(|e| Failure::Unreadable(e.into()))?;
        if FileType::from_raw_mode(opened.st_mode) != FileType::RegularFile {
            return Err(Failure::NotARegularFile);
        }
        // Taken of the file opened before `proof` reads it, so an edit made while or after
        // it is read changes it too.
        let stamp = Stamp::of(&opened);
        if !proof(&mut file).map_err(Failure::Unreadable)? {
            return Ok(Removal::Kept);
        }
        drop(file);
        // The file proven must still be the one at the name, unchanged: another put there
        // since, or the same file written over after it was read, is left as it is.
        match fs::statat(&dir, name, AtFlags::SYMLINK_NOFOLLOW) {
            Ok(now) if Stamp::of(&now) == stamp => {}
            Ok(_) => return Err(Failure::Changed),
            Err(Errno::NOENT) => return Ok(Removal::Missing),
            Err(e) => return Err(e.into()),
        }
        match fs::unlinkat(&dir, name, AtFlags::empty()) {
            Ok(()) => Ok(Removal::Removed),
            Err(Errno::NOENT) => Ok(Removal::Missing),
            Err(e) => Err(e.into()),
        }
    }

    /// Whether `e`, from the walk to a file to be removed or read again, says a directory
    /// on its way is not there, or is no directory: then no file is there.
    pub(super) fn nothing_below(e: &std::io::Error) -> bool {
        matches!(Errno::from_io_error(e), Some(Errno::NOENT | Errno::NOTDIR))
    }

    /// Open `name` in `dir` to read it: a rewrite's second read, or a removal's proof.
    fn open_to_read(dir: BorrowedFd<'_>, name: &OsStr) -> Result<File, Errno> {
        fs::openat(dir, name, READ, Mode::empty()).map(File::from)
    }

    /// Open the anchor by path, creating it first when it is missing and `parents` says so.
    ///
    /// A missing anchor that cannot be created because a name on its path is taken has a
    /// symlink that leads nowhere there (an existing file fails the open as not a directory
    /// instead): it is reported as the missing directory it is, not as the name creating
    /// it found.
    fn open_anchor(anchor: &Path, parents: Parents) -> Result<OwnedFd, Failure> {
        let open = || {
            search_or_read(ANCHOR, SEARCH, |flags| {
                fs::openat(CWD, anchor, flags, Mode::empty())
            })
        };
        match open() {
            Err(Errno::NOENT) if parents == Parents::Create => {
                std::fs::create_dir_all(anchor).map_err(|e| {
                    if e.kind() == std::io::ErrorKind::AlreadyExists {
                        Errno::NOENT.into()
                    } else {
                        e
                    }
                })?;
                Ok(open()?)
            }
            opened => Ok(opened?),
        }
    }

    /// A directory opened with `flags` by `open`; where they hold `search` — a flag of its
    /// own, `O_PATH` — and a kernel or a filesystem refuses that open (`EINVAL`), opened
    /// again without it, to read.
    pub(super) fn search_or_read<T>(
        flags: OFlags,
        search: OFlags,
        open: impl Fn(OFlags) -> Result<T, Errno>,
    ) -> Result<T, Errno> {
        match open(flags) {
            Err(Errno::INVAL) if !search.is_empty() && flags.contains(search) => {
                open(flags.difference(search))
            }
            opened => opened,
        }
    }

    /// `dir`, the anchor as opened, when it is the directory `checked`: one the caller
    /// checked a moment before, by path, so a link swapped onto that path since then has
    /// led the open to another directory, which is refused before anything below it is
    /// opened.
    fn opened_as_checked(dir: OwnedFd, checked: DirIdentity) -> Result<OwnedFd, Failure> {
        let dir = File::from(dir);
        if DirIdentity::of_metadata(&dir.metadata()?) == checked {
            Ok(OwnedFd::from(dir))
        } else {
            Err(Failure::AnchorMoved)
        }
    }

    /// What a failed open of the directory `name` in `dir`, `depth` levels below the
    /// anchor, comes to: a symlink refusal when the open said `ELOOP` — which an
    /// `O_NOFOLLOW` open of one name says for a symlink alone, even if the link is gone by
    /// the time it could be looked at again — or when `name` is a symlink now (Linux can
    /// say `ENOTDIR` for one opened `O_DIRECTORY`, as for a file); else the open's own
    /// failure.
    pub(super) fn below_failure(
        dir: BorrowedFd<'_>,
        name: &OsStr,
        depth: usize,
        errno: Errno,
    ) -> Failure {
        if errno == Errno::LOOP || is_symlink(dir, name) {
            Failure::LinkBelowAnchor { depth }
        } else {
            Failure::from(errno)
        }
    }

    /// Open the directory `name` in `dir` without following a symlink, creating it first
    /// when it is missing and `parents` says so.
    fn open_below(dir: BorrowedFd<'_>, name: &OsStr, parents: Parents) -> Result<OwnedFd, Errno> {
        let open = || {
            search_or_read(BELOW, SEARCH, |flags| {
                fs::openat(dir, name, flags, Mode::empty())
            })
        };
        match open() {
            Err(Errno::NOENT) if parents == Parents::Create => {
                match fs::mkdirat(dir, name, NEW_DIR) {
                    Ok(()) | Err(Errno::EXIST) => {}
                    Err(e) => return Err(e),
                }
                open()
            }
            opened => opened,
        }
    }

    /// Whether `name` in `dir` is a symlink, looked at without following it.
    fn is_symlink(dir: BorrowedFd<'_>, name: &OsStr) -> bool {
        fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW)
            .is_ok_and(|stat| FileType::from_raw_mode(stat.st_mode) == FileType::Symlink)
    }

    /// Whether `name` in `dir`, looked at without following a symlink, is something other
    /// than a regular file; a look that fails tells nothing, and is not.
    fn is_no_regular_file(dir: BorrowedFd<'_>, name: &OsStr) -> bool {
        fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW)
            .is_ok_and(|stat| FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile)
    }

    /// Put `content` at `name` in `dir`, by way of a temporary file beside it, as `commit`
    /// says: renamed over the file there — when it stamps the file a rewrite read, only if
    /// the file there still holds it, and for an output only if it is no MDS module, each
    /// looked at just before the rename ([`ready_to_replace`]) — or given the name only
    /// where nothing has it ([`commit_new`]); and give `dir` back. In the
    /// [`Durability::Fsync`] tier `dir` is then synced ([`sync_directory`]): the rename has
    /// landed by then, so a sync that fails is told apart from a write that failed.
    fn replace(
        dir: OwnedFd,
        name: &OsStr,
        content: &[u8],
        durability: Durability,
        commit: Commit<'_>,
    ) -> Result<Landed, Failure> {
        let dir = put(dir, name, content, durability, commit)?;
        let not_synced = match durability {
            Durability::Fsync => sync_directory(dir.as_fd()).err(),
            Durability::RenameOnly => None,
        };
        Ok(Landed { dir, not_synced })
    }

    /// All [`replace`] does before the directory's sync: put `content` at `name` in `dir`,
    /// the file synced as `durability` asks, and give `dir` back.
    fn put(
        dir: OwnedFd,
        name: &OsStr,
        content: &[u8],
        durability: Durability,
        commit: Commit<'_>,
    ) -> Result<OwnedFd, Failure> {
        // The target is looked at, never opened: a FIFO would block the open.
        let replaced = match fs::statat(&dir, name, AtFlags::SYMLINK_NOFOLLOW) {
            Ok(stat) => match (FileType::from_raw_mode(stat.st_mode), commit) {
                (FileType::Symlink, _) => return Err(Failure::LinkAtTarget),
                // A new file is never put where anything is.
                (_, Commit::New) => return Err(Failure::Exists),
                (FileType::RegularFile, _) => Some(stat),
                // A directory has no mode a file should take: the rename below refuses to
                // replace it, and the temporary file is unlinked again.
                (FileType::Directory, _) => None,
                _ => return Err(Failure::NotARegularFile),
            },
            Err(Errno::NOENT) => None,
            Err(e) => return Err(e.into()),
        };
        let (mut temp, file) = match &replaced {
            Some(replaced) => create_replacement(dir.as_fd(), replaced)?,
            None => create_temp(dir.as_fd(), NEW_FILE, temp_names())?,
        };
        fill(file, content, durability)?;
        match commit {
            Commit::Replace(_) | Commit::Output { .. } => {
                // The temporary file is unlinked again as `temp` drops.
                ready_to_replace(dir.as_fd(), name, commit)?;
                fs::renameat(dir.as_fd(), &temp.name, dir.as_fd(), name)?;
                temp.renamed = true;
                drop(temp);
            }
            Commit::New => {
                // A file that appears while the run pauses here is met by the commit
                // itself, not by the look above.
                super::pause_before_replace();
                commit_new(temp, name, content, durability, &NO_CLOBBER)?;
            }
        }
        Ok(dir)
    }

    /// The temporary file that is to replace the regular file `replaced` describes, in
    /// `dir` (#160): created owner-only, then given that file's permission bits when the
    /// user who owns that file owns this one too ([`kept_mode`]). Beside a file another
    /// user owns it is made again as a new file is, its mode the umask's: that user chose
    /// that file's mode, and lends it to no one else's file.
    fn create_replacement<'d>(
        dir: BorrowedFd<'d>,
        replaced: &fs::Stat,
    ) -> Result<(Temp<'d>, File), Failure> {
        let (temp, file) = create_temp(dir, OWNER_ONLY, temp_names())?;
        let same_owner = fs::fstat(&file)?.st_uid == replaced.st_uid;
        match kept_mode(replaced.st_mode, same_owner) {
            Some(mode) => {
                fs::fchmod(&file, mode)?;
                Ok((temp, file))
            }
            None => {
                // Unlinked again as it drops, before the new file is created.
                drop((temp, file));
                Ok(create_temp(dir, NEW_FILE, temp_names())?)
            }
        }
    }

    /// The mode a file with mode `st_mode` lends the file that replaces it: its permission
    /// bits alone ([`PERMISSION_BITS`]), and only when one user owns both (`same_owner`) —
    /// else none.
    pub(super) fn kept_mode(st_mode: fs::RawMode, same_owner: bool) -> Option<Mode> {
        same_owner.then(|| Mode::from_raw_mode(st_mode & PERMISSION_BITS))
    }

    /// Whether the rename over `name` in `dir` may go on, as `commit` says, looked at just
    /// before it: a rewrite's file must still hold the stamp it was read with, and an
    /// output's target must be no file the run reads, nor an MDS module unless the output
    /// is one (#425).
    fn ready_to_replace(
        dir: BorrowedFd<'_>,
        name: &OsStr,
        commit: Commit<'_>,
    ) -> Result<(), Failure> {
        match commit {
            Commit::Replace(Some(stamp)) if !stamp.holds(dir, name) => Err(Failure::Changed),
            Commit::Output { inputs, module } => never_over_an_input(dir, name, inputs, module),
            _ => Ok(()),
        }
    }

    /// Refuse the rename over `name` in `dir` when the file there is one of `inputs`, or an
    /// MDS module while the output is none (`module`) (#425). It is looked at without
    /// following a symlink: nothing there, a symlink — which the rename replaces, never
    /// writing through it — and anything else that is no regular file are neither. For an
    /// output that is no module, a regular file there is judged by its name and, for a
    /// `.md` file's, read as opened in `dir` ([`is_a_module`]); any regular file is compared
    /// with each of `inputs` by its device and inode ([`is_an_input`]).
    fn never_over_an_input(
        dir: BorrowedFd<'_>,
        name: &OsStr,
        inputs: &Inputs,
        module: bool,
    ) -> Result<(), Failure> {
        let stat = match fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW) {
            Ok(stat) if FileType::from_raw_mode(stat.st_mode) == FileType::RegularFile => stat,
            Ok(_) | Err(Errno::NOENT) => return Ok(()),
            Err(e) => return Err(e.into()),
        };
        if !module && is_a_module(dir, name)? {
            return Err(Failure::Module);
        }
        if is_an_input(inputs, &stat) {
            return Err(Failure::Input);
        }
        Ok(())
    }

    /// Whether the file `stat` describes is one of `inputs`: the same device and inode as
    /// the file each names now, looked up through a symlink as the run read it.
    fn is_an_input(inputs: &Inputs, stat: &fs::Stat) -> bool {
        inputs.paths().any(|file| {
            fs::stat(&*file)
                .is_ok_and(|input| input.st_dev == stat.st_dev && input.st_ino == stat.st_ino)
        })
    }

    /// Whether `name` in `dir`, a regular file a moment ago, is an MDS module (#425): a
    /// `.mds` file by its name alone ([`super::names_source`]), never read; a `.md` file
    /// ([`super::names_markdown`]) opened in `dir` — never by path — without following a
    /// symlink, and read there, that [`super::is_mds_module`] takes for one. Any other name
    /// is none, and so is a `.md` file gone since, a symlink or anything else that is no
    /// regular file by then; a `.md` file that cannot be opened or read is
    /// [`Failure::UnreadMarkdown`].
    fn is_a_module(dir: BorrowedFd<'_>, name: &OsStr) -> Result<bool, Failure> {
        if super::names_source(name) {
            return Ok(true);
        }
        if !super::names_markdown(name) {
            return Ok(false);
        }
        let judge = || -> std::io::Result<bool> {
            let mut file = match open_to_read(dir, name) {
                Ok(file) => file,
                // Gone since the look, or a symlink put there since: no module to replace.
                Err(Errno::NOENT | Errno::LOOP) => return Ok(false),
                Err(e) => return Err(e.into()),
            };
            let opened = fs::fstat(&file)?;
            if FileType::from_raw_mode(opened.st_mode) != FileType::RegularFile {
                return Ok(false);
            }
            super::is_mds_module(&mut file)
        };
        judge().map_err(Failure::UnreadMarkdown)
    }

    /// Write `content` to `file` and, in the [`Durability::Fsync`] tier, sync it; then
    /// close it, unchecked — a full disk that a network or FUSE filesystem reports only
    /// then goes unseen by a write that is not synced (the module docs' scope).
    fn fill(mut file: File, content: &[u8], durability: Durability) -> std::io::Result<()> {
        file.write_all(content)?;
        if durability == Durability::Fsync {
            sync_file(&file)?;
        }
        Ok(())
    }

    /// Force `file`'s bytes to stable storage: `File::sync_all`, which is `F_FULLFSYNC` on
    /// Apple platforms — a flush of the drive's cache too — and, on a filesystem that
    /// refuses that, a plain `fsync` ([`full_or_plain`]). A sync refused both ways fails the
    /// write, as any other failed sync does.
    fn sync_file(file: &File) -> std::io::Result<()> {
        full_or_plain(
            || file.sync_all(),
            || fs::fsync(file).map_err(std::io::Error::from),
        )
    }

    /// `full`, the sync asked for first, and, only where a filesystem refuses it the way
    /// [`refused`] tells, `plain`: so `F_FULLFSYNC` is kept wherever it is supported.
    pub(super) fn full_or_plain(
        full: impl FnOnce() -> std::io::Result<()>,
        plain: impl FnOnce() -> std::io::Result<()>,
    ) -> std::io::Result<()> {
        match full() {
            Err(e) if refused(&e) => plain(),
            synced => synced,
        }
    }

    /// One step of a new file's commit: give the file `from` in `dir` the name `to` there,
    /// never over a file that has it.
    pub(super) type Step<'s> = &'s dyn Fn(BorrowedFd<'_>, &OsStr, &OsStr) -> Result<(), Errno>;

    /// How a new file's commit writes its content in place, where it must ([`fill`]).
    pub(super) type Fill<'s> = &'s dyn Fn(File, &[u8], Durability) -> std::io::Result<()>;

    /// The steps a new file's commit takes, in order (#160): a rename that never replaces,
    /// then a hard link, which never replaces either; each is passed over when it is not
    /// to be had (see [`commit_new`]), and then the content is written in place with
    /// `fill`.
    pub(super) struct NewSteps<'s> {
        pub(super) rename: Step<'s>,
        pub(super) link: Step<'s>,
        pub(super) fill: Fill<'s>,
    }

    /// The steps a new file's commit takes.
    pub(super) const NO_CLOBBER: NewSteps<'static> = NewSteps {
        rename: &rename_noreplace,
        link: &link_new,
        fill: &fill,
    };

    /// Give `temp`'s file the name `name` in the directory it is in, only where nothing has
    /// that name: by `steps.rename`; where that is not to be had — `EINVAL`, `ENOSYS`,
    /// `ENOTSUP` or `EOPNOTSUPP`: no such rename on this platform, kernel or filesystem — by
    /// `steps.link`, the temporary name then removed as `temp` drops; and where that is
    /// not to be had either — `EPERM`, `ENOSYS`, `ENOTSUP`, `EOPNOTSUPP` or `EMLINK`: a
    /// filesystem without hard links — by writing `content` in place, into a file created
    /// exclusively ([`write_in_place`]). `EEXIST` from any step, a file that appeared since
    /// the target was looked at, refuses the write and leaves that file as it is.
    pub(super) fn commit_new(
        mut temp: Temp<'_>,
        name: &OsStr,
        content: &[u8],
        durability: Durability,
        steps: &NewSteps<'_>,
    ) -> Result<(), Failure> {
        let dir = temp.dir;
        match (steps.rename)(dir, &temp.name, name) {
            Ok(()) => {
                temp.renamed = true;
                Ok(())
            }
            Err(errno) if no_such_rename(errno) => match (steps.link)(dir, &temp.name, name) {
                Ok(()) => Ok(()),
                Err(errno) if no_hard_links(errno) => {
                    write_in_place(dir, name, content, durability, steps.fill)
                }
                Err(errno) => Err(refused_if_there(errno)),
            },
            Err(errno) => Err(refused_if_there(errno)),
        }
    }

    /// Rename `from` to `to` in `dir`, never over a file at `to`:
    /// `renameat2(RENAME_NOREPLACE)` on Linux and Android, `renameatx_np(RENAME_EXCL)` on
    /// Apple platforms.
    #[cfg(any(
        target_os = "linux",
        target_os = "android",
        target_os = "macos",
        target_os = "ios",
        target_os = "tvos",
        target_os = "visionos",
        target_os = "watchos"
    ))]
    fn rename_noreplace(dir: BorrowedFd<'_>, from: &OsStr, to: &OsStr) -> Result<(), Errno> {
        fs::renameat_with(dir, from, dir, to, fs::RenameFlags::NOREPLACE)
    }

    /// No rename that never replaces on this platform: not to be had, so the commit goes on
    /// to a hard link.
    #[cfg(not(any(
        target_os = "linux",
        target_os = "android",
        target_os = "macos",
        target_os = "ios",
        target_os = "tvos",
        target_os = "visionos",
        target_os = "watchos"
    )))]
    fn rename_noreplace(_: BorrowedFd<'_>, _: &OsStr, _: &OsStr) -> Result<(), Errno> {
        Err(Errno::NOSYS)
    }

    /// Link `to` in `dir` to the file `from` is, which fails on a name already taken.
    fn link_new(dir: BorrowedFd<'_>, from: &OsStr, to: &OsStr) -> Result<(), Errno> {
        fs::linkat(dir, from, dir, to, AtFlags::empty())
    }

    /// Write `content` to `name` in `dir` with `fill`, created exclusively and without
    /// following a symlink: a new file's commit on a filesystem without hard links. No file
    /// there is replaced, but the write is not all or nothing: one that fails part-way
    /// removes the file it created again, while the name is still that file
    /// ([`remove_if_still`]), and a crash or a kill while it is written leaves the file
    /// partly written.
    fn write_in_place(
        dir: BorrowedFd<'_>,
        name: &OsStr,
        content: &[u8],
        durability: Durability,
        fill: Fill<'_>,
    ) -> Result<(), Failure> {
        let file = File::from(fs::openat(dir, name, IN_PLACE, NEW_FILE).map_err(refused_if_there)?);
        // Which file the write created, taken before it is written: a look that fails
        // leaves nothing to tell it by, and a failed write then leaves the file.
        let created = fs::fstat(&file).ok();
        fill(file, content, durability).map_err(|e| {
            if let Some(created) = &created {
                remove_if_still(dir, name, created);
            }
            Failure::from(e)
        })
    }

    /// Remove `name` from `dir` while it is still the file `created` describes — the same
    /// device and inode; its size and times are the failed write's own, and are not
    /// compared — best effort: the write has already failed, and a failure here is not the
    /// one it reports. A file put at the name since is left as it is; one put there in the
    /// instant between that look and the removal is removed instead, as by any removal by
    /// name.
    fn remove_if_still(dir: BorrowedFd<'_>, name: &OsStr, created: &fs::Stat) {
        let still = fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW)
            .is_ok_and(|now| now.st_dev == created.st_dev && now.st_ino == created.st_ino);
        if still {
            let _ = fs::unlinkat(dir, name, AtFlags::empty());
        }
    }

    /// Whether `errno`, from a rename that never replaces, says there is no such rename.
    fn no_such_rename(errno: Errno) -> bool {
        [Errno::INVAL, Errno::NOSYS, Errno::NOTSUP, Errno::OPNOTSUPP].contains(&errno)
    }

    /// Whether `errno`, from a hard link, says the filesystem makes none.
    fn no_hard_links(errno: Errno) -> bool {
        [
            Errno::PERM,
            Errno::NOSYS,
            Errno::NOTSUP,
            Errno::OPNOTSUPP,
            Errno::MLINK,
        ]
        .contains(&errno)
    }

    /// `errno` from a step of a new file's commit, as the write's failure: `EEXIST`, a
    /// file at the name, is the refusal.
    fn refused_if_there(errno: Errno) -> Failure {
        if errno == Errno::EXIST {
            Failure::Exists
        } else {
            Failure::from(errno)
        }
    }

    /// A temporary file a write created in `dir`, unlinked when dropped unless it was
    /// renamed over the target first.
    pub(super) struct Temp<'d> {
        dir: BorrowedFd<'d>,
        pub(super) name: OsString,
        renamed: bool,
    }

    impl Drop for Temp<'_> {
        fn drop(&mut self) {
            if !self.renamed {
                // Best effort: the write has already failed, and this error is not the one
                // it reports.
                let _ = fs::unlinkat(self.dir, &self.name, AtFlags::empty());
            }
        }
    }

    /// Create a new file in `dir` with `mode` under the first of `names` that is free,
    /// trying at most [`MAX_TEMP_ATTEMPTS`] of them.
    pub(super) fn create_temp<'d>(
        dir: BorrowedFd<'d>,
        mode: Mode,
        names: impl IntoIterator<Item = OsString>,
    ) -> Result<(Temp<'d>, File), Errno> {
        for name in names.into_iter().take(MAX_TEMP_ATTEMPTS) {
            match fs::openat(dir, &name, TEMP, mode) {
                Ok(fd) => {
                    let temp = Temp {
                        dir,
                        name,
                        renamed: false,
                    };
                    return Ok((temp, File::from(fd)));
                }
                Err(Errno::EXIST) => {}
                Err(e) => return Err(e),
            }
        }
        Err(Errno::EXIST)
    }

    /// Random temporary names, `.mds-tmp-<16 hex digits>.tmp`, each drawn from a fresh
    /// `RandomState` so no two writes, in this process or another, are likely to share one.
    fn temp_names() -> impl Iterator<Item = OsString> {
        use std::hash::{BuildHasher as _, Hasher as _};

        (0..MAX_TEMP_ATTEMPTS).map(|attempt| {
            let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
            hasher.write_usize(attempt);
            OsString::from(format!(
                "{TEMP_PREFIX}{:016x}{TEMP_SUFFIX}",
                hasher.finish()
            ))
        })
    }

    /// Make the rename itself durable by syncing the directory it happened in: `dir`, as
    /// the walk opened it, opened again to read ([`TO_SYNC`]) — a descriptor opened for
    /// search alone cannot be synced — which a directory the user may not list refuses.
    ///
    /// `File::sync_all` is `F_FULLFSYNC` on Apple platforms, which a filesystem may refuse
    /// for a directory (`ENOTSUP`, `EOPNOTSUPP`, `EINVAL`); a plain `fsync` is the fallback
    /// for those. A filesystem that refuses that too cannot sync a directory, which is no
    /// failure. Any other failure — the open's included — is the sync's: the rename has
    /// landed, and the caller says the file is written but not synced.
    fn sync_directory(dir: BorrowedFd<'_>) -> std::io::Result<()> {
        #[cfg(test)]
        super::sync_probe::directory_sync()?;
        let readable = File::from(fs::openat(dir, ".", TO_SYNC, Mode::empty())?);
        settle_directory_sync(
            || readable.sync_all(),
            || fs::fsync(&readable).map_err(std::io::Error::from),
        )
    }

    /// The directory sync's outcome, from `full`, the sync asked for first, and `plain`,
    /// the fallback made only when `full` was refused ([`full_or_plain`]): a refusal of
    /// both is no error, as there is no directory sync to be had.
    pub(super) fn settle_directory_sync(
        full: impl FnOnce() -> std::io::Result<()>,
        plain: impl FnOnce() -> std::io::Result<()>,
    ) -> std::io::Result<()> {
        match full_or_plain(full, plain) {
            Err(e) if refused(&e) => Ok(()),
            synced => synced,
        }
    }

    /// Whether `e` is a filesystem's refusal to sync the way it was asked.
    fn refused(e: &std::io::Error) -> bool {
        Errno::from_io_error(e).is_some_and(refused_sync)
    }

    /// Whether `errno` is a refusal to sync the way it was asked — `ENOTSUP`, `EOPNOTSUPP`,
    /// `EINVAL` — rather than a failure to sync.
    fn refused_sync(errno: Errno) -> bool {
        errno == Errno::NOTSUP || errno == Errno::OPNOTSUPP || errno == Errno::INVAL
    }
}

#[cfg(windows)]
mod windows {
    use std::ffi::{OsStr, OsString};
    use std::io::Write as _;
    use std::os::windows::ffi::{OsStrExt as _, OsStringExt as _};
    use std::path::{Path, PathBuf};
    use std::time::SystemTime;

    use super::{
        Below, Beside, Commit, DirIdentity, Durability, Failure, Inputs, Landed, Parents, Removal,
        TEMP_PREFIX, TEMP_SUFFIX,
    };

    /// `ERROR_PATH_NOT_FOUND`: a directory that is not there, in the operating system's
    /// words.
    const PATH_NOT_FOUND: i32 = 3;

    /// The directory a write's file went in, by path.
    pub(super) type Dir = PathBuf;

    /// Write `content` to `below.name`, in the directory [`walk`] checks, by path (the
    /// residual the module docs describe), as `commit` says, refusing a symlink at the
    /// target; and give that directory back. No directory is synced here.
    pub(super) fn write(
        below: &Below<'_>,
        anchor: Option<DirIdentity>,
        content: &[u8],
        durability: Durability,
        parents: Parents,
        commit: Commit<'_>,
    ) -> Result<Landed, Failure> {
        let dir = walk(below, anchor, parents)?;
        let target = dir.join(below.name);
        match (std::fs::symlink_metadata(&target), commit) {
            (Ok(meta), _) if meta.file_type().is_symlink() => return Err(Failure::LinkAtTarget),
            // A new file is never put where anything is.
            (Ok(_), Commit::New) => return Err(Failure::Exists),
            (Err(e), _) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),
            _ => {}
        }
        replace(&dir, &target, content, durability, commit)?;
        Ok(Landed {
            dir,
            not_synced: None,
        })
    }

    /// Whether anything has `name` in `dir`, looked at by path without following a
    /// symlink: only a name nothing has is [`Beside::Nothing`]; a failed look is
    /// [`Beside::Something`].
    pub(super) fn look(dir: &Dir, name: &OsStr) -> Beside {
        match std::fs::symlink_metadata(dir.join(name)) {
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Beside::Nothing,
            _ => Beside::Something,
        }
    }

    /// A file as a rewrite read it, by path (#160): its size and the times it was last
    /// modified and created.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(super) struct Stamp {
        size: u64,
        modified: Option<SystemTime>,
        created: Option<SystemTime>,
    }

    impl Stamp {
        /// The stamp `meta` gives.
        fn of(meta: &std::fs::Metadata) -> Self {
            Self {
                size: meta.len(),
                modified: meta.modified().ok(),
                created: meta.created().ok(),
            }
        }

        /// Whether `file`, looked at by path without following a symlink, is still the
        /// regular file this stamp was taken of, unchanged.
        fn holds(&self, file: &Path) -> bool {
            std::fs::symlink_metadata(file)
                .is_ok_and(|meta| meta.is_file() && Self::of(&meta) == *self)
        }
    }

    /// A file a rewrite read, held for its replace, by path: the directory it was read in,
    /// the file, and its stamp.
    pub(super) struct Held {
        dir: PathBuf,
        file: PathBuf,
        stamp: Stamp,
    }

    /// Read `below.name` again in the directory [`walk`] checks — below `anchor`, the
    /// directory checked, when there is one — by path, refusing a symlink there, and hold
    /// it if its bytes are `read`.
    pub(super) fn read_stamped(
        below: &Below<'_>,
        anchor: Option<DirIdentity>,
        read: &[u8],
    ) -> Result<Held, Failure> {
        let dir = walk(below, anchor, Parents::Existing)?;
        let target = dir.join(below.name);
        match std::fs::symlink_metadata(&target) {
            Ok(meta) if meta.file_type().is_symlink() => return Err(Failure::LinkAtTarget),
            // A directory, which an open as a file refuses: no longer the file read, as
            // nothing but a regular file is (below) — not a file that cannot be read.
            Ok(meta) if !meta.is_file() => return Err(Failure::Changed),
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err(Failure::Changed),
            Err(e) => return Err(e.into()),
        }
        let mut opened = std::fs::File::open(&target)?;
        let meta = opened.metadata()?;
        if !meta.is_file() {
            return Err(Failure::Changed);
        }
        // One byte more than was read tells a file that grew from one that did not.
        let expected = u64::try_from(read.len()).unwrap_or(u64::MAX);
        if mds::read_at_most(&mut opened, expected.saturating_add(1), expected)? != read {
            return Err(Failure::Changed);
        }
        Ok(Held {
            dir,
            file: target,
            stamp: Stamp::of(&meta),
        })
    }

    /// Replace the file `held` was read from with `content`, unless its stamp has changed
    /// by the time it is replaced. No directory is synced here.
    pub(super) fn replace_held(
        held: Held,
        content: &[u8],
        durability: Durability,
    ) -> Result<Landed, Failure> {
        let commit = Commit::Replace(Some(&held.stamp));
        replace(&held.dir, &held.file, content, durability, commit)?;
        Ok(Landed {
            dir: held.dir,
            not_synced: None,
        })
    }

    /// Replace the file `held` was read from with `content` as [`replace_held`] does in the
    /// [`Durability::Fsync`] tier, and give its directory back.
    pub(super) fn rename_held(held: Held, content: &[u8]) -> Result<Dir, Failure> {
        let commit = Commit::Replace(Some(&held.stamp));
        replace(&held.dir, &held.file, content, Durability::Fsync, commit)?;
        Ok(held.dir)
    }

    /// A directory's sync after a rewrite's rename: none here, as for every write on
    /// Windows.
    pub(super) fn sync_owed(_dir: &Dir) -> std::io::Result<()> {
        Ok(())
    }

    /// Whether `a` and `b` are one directory, by path: no directory is synced here.
    pub(super) fn same_directory(a: &Dir, b: &Dir) -> bool {
        a == b
    }

    /// Remove `below.name`, in the directory [`walk`] checks — creating none — once it is
    /// a regular file `proof` accepts, refusing a symlink or a junction there; the file is
    /// closed again, looked at by path for the [`Stamp`] it was opened with, and removed
    /// by path (the residual the module docs describe).
    pub(super) fn remove(
        below: &Below<'_>,
        anchor: Option<DirIdentity>,
        proof: impl FnOnce(&mut std::fs::File) -> std::io::Result<bool>,
    ) -> Result<Removal, Failure> {
        let dir = match walk(below, anchor, Parents::Existing) {
            Ok(dir) => dir,
            Err(Failure::Io(e)) if nothing_below(&e) => return Ok(Removal::Missing),
            Err(failure) => return Err(failure),
        };
        let target = dir.join(below.name);
        match std::fs::symlink_metadata(&target) {
            Ok(meta) if meta.file_type().is_symlink() => return Err(Failure::LinkAtTarget),
            Ok(meta) if !meta.is_file() => return Err(Failure::NotARegularFile),
            Ok(_) => {}
            // A name the file system cannot hold — too long (`ERROR_FILENAME_EXCED_RANGE`)
            // or not a name it accepts (`ERROR_INVALID_NAME`) — names no file.
            Err(e) if no_such_name(&e) => return Ok(Removal::Missing),
            Err(e) => return Err(Failure::Unreadable(e)),
        }
        let mut file = match std::fs::File::open(&target) {
            Ok(file) => file,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Removal::Missing),
            Err(e) => return Err(Failure::Unreadable(e)),
        };
        // Taken of the file opened before `proof` reads it, so an edit made while or after
        // it is read changes it too.
        let stamp = Stamp::of(&file.metadata().map_err(Failure::Unreadable)?);
        if !proof(&mut file).map_err(Failure::Unreadable)? {
            return Ok(Removal::Kept);
        }
        drop(file);
        // The file proven must still be at the name, unchanged: one written over after it
        // was read, or another put there with another size or other times, is left.
        match std::fs::symlink_metadata(&target) {
            Ok(now) if now.is_file() && Stamp::of(&now) == stamp => {}
            Ok(_) => return Err(Failure::Changed),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Removal::Missing),
            Err(e) => return Err(e.into()),
        }
        match std::fs::remove_file(&target) {
            Ok(()) => Ok(Removal::Removed),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Removal::Missing),
            Err(e) => Err(e.into()),
        }
    }

    /// Whether `e`, from the walk to a file to be removed or read again, says a directory
    /// on its way is not there, or is no directory: then no file is there.
    pub(super) fn nothing_below(e: &std::io::Error) -> bool {
        matches!(
            e.kind(),
            std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
        ) || e.raw_os_error() == Some(PATH_NOT_FOUND)
    }

    /// Whether `e`, from the look at a file to be removed, says no file has its name: none
    /// is there, or the file system cannot hold the name, which std reports as
    /// `InvalidFilename`.
    fn no_such_name(e: &std::io::Error) -> bool {
        matches!(
            e.kind(),
            std::io::ErrorKind::NotFound | std::io::ErrorKind::InvalidFilename
        )
    }

    /// Put `content` at `target` in `dir`, by way of a temporary file beside it, as
    /// `commit` says: renamed over the file there with [`std::fs::rename`] — when it
    /// stamps the file a rewrite read, only if `target` still holds it, and for an output
    /// only if it is no MDS module, each looked at just before ([`ready_to_replace`]) — or
    /// moved into place without `MOVEFILE_REPLACE_EXISTING`, which fails on a file that is
    /// there.
    ///
    /// The rename is std's, not tempfile's `persist` (#160). Both first move the file with
    /// `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`, which fails with `ERROR_ACCESS_DENIED`
    /// while another program — an editor, a viewer, a virus scanner, an indexer — holds
    /// the target open, even one that shares it for delete; std's rename then replaces it
    /// with POSIX semantics, where the file system has them and that program shares it
    /// for delete, as std opens every file. The temporary file is therefore a plain new
    /// file: tempfile's own marks its file temporary — a hint that its bytes need never
    /// reach the disk — and only tempfile's moves clear that mark again.
    fn replace(
        dir: &Path,
        target: &Path,
        content: &[u8],
        durability: Durability,
        commit: Commit<'_>,
    ) -> Result<(), Failure> {
        let mut temp = tempfile::Builder::new()
            .prefix(TEMP_PREFIX)
            .suffix(TEMP_SUFFIX)
            .make_in(dir, |path| {
                std::fs::OpenOptions::new()
                    .write(true)
                    .create_new(true)
                    .open(path)
            })?;
        temp.as_file_mut().write_all(content)?;
        if durability == Durability::Fsync {
            temp.as_file().sync_all()?;
        }
        match commit {
            Commit::Replace(_) | Commit::Output { .. } => {
                // The temporary file is deleted again as `temp` drops, until it is renamed.
                ready_to_replace(target, commit)?;
                std::fs::rename(temp.path(), target)?;
                // Renamed: nothing is left at its temporary name to delete.
                temp.disable_cleanup(true);
            }
            Commit::New => {
                // A file that appears while the run pauses here is met by the move itself.
                super::pause_before_replace();
                // The temporary file is deleted again as the error drops.
                temp.persist_noclobber(target).map_err(|e| {
                    if e.error.kind() == std::io::ErrorKind::AlreadyExists {
                        Failure::Exists
                    } else {
                        Failure::from(e.error)
                    }
                })?;
            }
        }
        Ok(())
    }

    /// Whether the move over `target` may go on, as `commit` says, looked at by path just
    /// before it: a rewrite's file must still hold the stamp it was read with, and an
    /// output's target must be no file the run reads, nor an MDS module unless the output
    /// is one (#425).
    fn ready_to_replace(target: &Path, commit: Commit<'_>) -> Result<(), Failure> {
        match commit {
            Commit::Replace(Some(stamp)) if !stamp.holds(target) => Err(Failure::Changed),
            Commit::Output { inputs, module } => never_over_an_input(target, inputs, module),
            _ => Ok(()),
        }
    }

    /// Refuse the move over `target` when the file there is one of `inputs`, or an MDS
    /// module while the output is none (`module`) (#425), by path. It is looked at without
    /// following a symlink: nothing there, a symlink — which the move replaces, never
    /// writing through it — and anything else that is no regular file are neither. For an
    /// output that is no module, a regular file there is judged by its name and, for a
    /// `.md` file's, read ([`is_a_module`]); any regular file is compared with each of
    /// `inputs` ([`is_an_input`]).
    fn never_over_an_input(target: &Path, inputs: &Inputs, module: bool) -> Result<(), Failure> {
        match std::fs::symlink_metadata(target) {
            Ok(meta) if meta.is_file() => {}
            Ok(_) => return Ok(()),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(e) => return Err(e.into()),
        }
        if !module && is_a_module(target)? {
            return Err(Failure::Module);
        }
        if is_an_input(inputs, target)? {
            return Err(Failure::Input);
        }
        Ok(())
    }

    /// Whether `target` is one of `inputs`, by canonical path: std gives no file index on
    /// Windows, so a hard link to an input — another path — is not one (the residual the
    /// module docs describe). A target gone since the look is none — nothing to replace —
    /// and one whose canonical path cannot be had otherwise is an error, which refuses the
    /// write, as a look that fails does on unix.
    fn is_an_input(inputs: &Inputs, target: &Path) -> Result<bool, Failure> {
        let target = match std::fs::canonicalize(target) {
            Ok(target) => target,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
            Err(e) => return Err(e.into()),
        };
        Ok(inputs
            .paths()
            .any(|file| std::fs::canonicalize(file).is_ok_and(|file| file == target)))
    }

    /// The name of the file `target` opens: its last component less the dots and spaces
    /// it ends in, which Windows drops ([`super::as_windows_opens`]) — so `-o "lib.md."`
    /// and `-o "lib.md "`, which write `lib.md`, are judged as `lib.md` (#425).
    fn opened_name(target: &Path) -> Option<OsString> {
        let name: Vec<u16> = target.file_name()?.encode_wide().collect();
        Some(OsString::from_wide(super::as_windows_opens(&name)))
    }

    /// Whether `target`, a regular file a moment ago, is an MDS module (#425), by the name
    /// of the file it opens ([`opened_name`]): a `.mds` file by its name alone
    /// ([`super::names_source`]), never read; a `.md` file ([`super::names_markdown`])
    /// opened and read by path, that [`super::is_mds_module`] takes for one. Any other name
    /// is none, and so is a `.md` file gone since; a `.md` file that cannot be opened or
    /// read is [`Failure::UnreadMarkdown`].
    fn is_a_module(target: &Path) -> Result<bool, Failure> {
        let Some(name) = opened_name(target) else {
            return Ok(false);
        };
        if super::names_source(&name) {
            return Ok(true);
        }
        if !super::names_markdown(&name) {
            return Ok(false);
        }
        let judge = || -> std::io::Result<bool> {
            let mut file = match std::fs::File::open(target) {
                Ok(file) => file,
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
                Err(e) => return Err(e),
            };
            super::is_mds_module(&mut file)
        };
        judge().map_err(Failure::UnreadMarkdown)
    }

    /// The directory `below.name` is in: the anchor, created first when `parents` says
    /// so — refused when `anchor` names another directory than the one there, or one
    /// gone, which is never made again — then each directory below it, refused when it is
    /// a symlink or a junction; all by path.
    fn walk(
        below: &Below<'_>,
        anchor: Option<DirIdentity>,
        parents: Parents,
    ) -> Result<PathBuf, Failure> {
        if parents == Parents::Create && anchor.is_none() {
            // A name on the anchor's path taken by a link that leads nowhere — the anchor
            // then resolves to nothing — is a directory that is not there, as on unix; a
            // file there keeps the error creating the directory met.
            std::fs::create_dir_all(&below.anchor).map_err(|e| {
                let leads_nowhere = || {
                    std::fs::metadata(&below.anchor)
                        .is_err_and(|m| m.kind() == std::io::ErrorKind::NotFound)
                };
                if e.kind() == std::io::ErrorKind::AlreadyExists && leads_nowhere() {
                    std::io::Error::from_raw_os_error(PATH_NOT_FOUND)
                } else {
                    e
                }
            })?;
        }
        if anchor.is_some_and(|checked| DirIdentity::of(&below.anchor) != Some(checked)) {
            return Err(Failure::AnchorMoved);
        }
        let mut dir = below.anchor.clone();
        for (depth, name) in below.dirs.iter().enumerate() {
            dir.push(name);
            if !directory_below(&dir, parents)? {
                return Err(Failure::LinkBelowAnchor { depth });
            }
        }
        Ok(dir)
    }

    /// Whether `dir`, a directory below the anchor, is one that is not a symlink or a
    /// junction — creating it first when it is missing and `parents` says so. `false`
    /// when it is a link; an error when it is something else or cannot be looked at.
    fn directory_below(dir: &Path, parents: Parents) -> std::io::Result<bool> {
        let meta = match std::fs::symlink_metadata(dir) {
            Err(e) if e.kind() == std::io::ErrorKind::NotFound && parents == Parents::Create => {
                match std::fs::create_dir(dir) {
                    Err(e) if e.kind() != std::io::ErrorKind::AlreadyExists => return Err(e),
                    _ => std::fs::symlink_metadata(dir)?,
                }
            }
            looked => looked?,
        };
        if meta.file_type().is_symlink() {
            return Ok(false);
        }
        if !meta.is_dir() {
            return Err(std::io::ErrorKind::NotADirectory.into());
        }
        Ok(true)
    }
}

// ── Test-only pause before a rewrite's replace or a new file's commit (#160) ─

/// `MDS_TEST_PAUSE_BEFORE_REPLACE`: how a debug build is made to stop between a rewrite's
/// read and its replace, so that a test can change the file, or swap its directory, in
/// that window, and between [`create_new`]'s look at its target and its commit, so that a
/// test can put a file there (`tests/anchored_writes.rs`) — [`write_over_own`] stops at
/// the same two places. A release build has none of it.
#[cfg(debug_assertions)]
mod pause_trigger {
    use std::path::PathBuf;
    use std::time::Duration;

    use super::{atomic_write_file, Durability, Parents};
    use crate::output::WriteTarget;

    /// The variable naming the file that ends the pause. The run writes the same name with
    /// `.paused` appended once it has stopped, for the test to wait for.
    const VARIABLE: &str = "MDS_TEST_PAUSE_BEFORE_REPLACE";

    /// How long the pause waits between two looks for the file that ends it.
    const POLL: Duration = Duration::from_millis(5);

    /// How many looks the pause makes before the replace goes on regardless: ten seconds.
    const MAX_POLLS: u32 = 2_000;

    /// Stop here when `MDS_TEST_PAUSE_BEFORE_REPLACE` names a file: say so by writing
    /// `<file>.paused`, then wait until `<file>` exists, or until [`MAX_POLLS`] looks have
    /// found none.
    pub(crate) fn pause_before_replace() {
        let Some(go) = std::env::var_os(VARIABLE).map(PathBuf::from) else {
            return;
        };
        let mut paused = go.clone().into_os_string();
        paused.push(".paused");
        // A marker that cannot be written leaves the test waiting for it, which the test
        // reports as a run that never paused.
        let _ = atomic_write_file(
            &WriteTarget::as_typed(PathBuf::from(paused)),
            "",
            Durability::RenameOnly,
            Parents::Existing,
        );
        for _ in 0..MAX_POLLS {
            if go.exists() {
                return;
            }
            std::thread::sleep(POLL);
        }
    }
}

#[cfg(debug_assertions)]
pub(crate) use pause_trigger::pause_before_replace;

/// A release build's pause before a rewrite's replace or a new file's commit: none.
#[cfg(not(debug_assertions))]
pub(crate) fn pause_before_replace() {}

/// The unit tests' view of the directory syncs a rewrite makes on unix (#160): how many
/// this thread has started, and an error for each to fail with instead, so that a test
/// can count them and fail them without a filesystem that refuses one.
#[cfg(all(test, unix))]
pub(crate) mod sync_probe {
    use std::cell::Cell;

    thread_local! {
        static STARTED: Cell<usize> = const { Cell::new(0) };
        static FAILING: Cell<Option<i32>> = const { Cell::new(None) };
    }

    /// How many directory syncs this thread has started.
    pub(crate) fn directory_syncs() -> usize {
        STARTED.with(Cell::get)
    }

    /// Make this thread's directory syncs fail with the OS error `errno` until the guard
    /// it gives back drops.
    pub(crate) fn failing_with(errno: i32) -> Failing {
        FAILING.with(|failing| failing.set(Some(errno)));
        Failing
    }

    /// While it lives, this thread's directory syncs fail ([`failing_with`]).
    #[must_use]
    pub(crate) struct Failing;

    impl Drop for Failing {
        fn drop(&mut self) {
            FAILING.with(|failing| failing.set(None));
        }
    }

    /// Count a directory sync about to be made, and fail it as [`failing_with`] asked.
    pub(super) fn directory_sync() -> std::io::Result<()> {
        STARTED.with(|started| started.set(started.get() + 1));
        match FAILING.with(Cell::get) {
            Some(errno) => Err(std::io::Error::from_raw_os_error(errno)),
            None => Ok(()),
        }
    }
}

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

    /// The cause of a write refused for an MDS module, as a user reads it: the refusal, and
    /// the way out in brackets (#425). Written out, so no test follows a change to the
    /// constants it is made from.
    const MODULE_REFUSED: &str = "refusing to replace an MDS module (an output that declares \
         type: mds is a generated module, and is rebuilt from its source)";

    /// [`atomic_write_file`] of a file named as it is written, anchored at its directory.
    fn write_as_typed(
        path: &Path,
        content: &str,
        durability: Durability,
    ) -> std::result::Result<(), mds::MdsError> {
        atomic_write_file(
            &WriteTarget::as_typed(path.to_path_buf()),
            content,
            durability,
            Parents::Existing,
        )
    }

    /// Names of leftover `.mds-tmp-*` entries directly inside `dir`.
    fn temp_residue(dir: &Path) -> Vec<String> {
        std::fs::read_dir(dir)
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .filter(|n| n.starts_with(TEMP_PREFIX))
            .collect()
    }

    /// The names in `dir`, sorted.
    fn entries(dir: &Path) -> Vec<String> {
        let mut names: Vec<String> = std::fs::read_dir(dir)
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        names.sort();
        names
    }

    /// Creates a symlink for a test, tolerating Windows' unprivileged restriction.
    ///
    /// Mirrors `crates/mds-core/src/lib.rs`'s crate-internal helper of the same name and
    /// contract (#147): unix needs no privilege; Windows needs Developer Mode or an
    /// elevated process (GitHub's `windows-latest` runners have Developer Mode enabled, so
    /// a failure there is a genuine regression and must panic), and only the unprivileged
    /// local case — `CI` unset plus raw OS error 1314 (`ERROR_PRIVILEGE_NOT_HELD`) — is a
    /// skip. Duplicated rather than shared because this crate has no unit-test-scope helper
    /// module.
    fn make_symlink(target: &Path, link: &Path) -> bool {
        #[cfg(unix)]
        let result = std::os::unix::fs::symlink(target, link);
        #[cfg(windows)]
        let result = if target.is_dir() {
            std::os::windows::fs::symlink_dir(target, link)
        } else {
            std::os::windows::fs::symlink_file(target, link)
        };

        match result {
            Ok(()) => true,
            Err(err) => {
                #[cfg(windows)]
                {
                    const ERROR_PRIVILEGE_NOT_HELD: i32 = 1314;
                    if err.raw_os_error() == Some(ERROR_PRIVILEGE_NOT_HELD)
                        && std::env::var_os("CI").is_none()
                    {
                        crate::output::ewriteln!(
                            "skipping: symlink creation needs Developer Mode or an elevated process on Windows"
                        );
                        return false;
                    }
                }
                panic!(
                    "failed to create symlink {} -> {}: {err}",
                    target.display(),
                    link.display()
                );
            }
        }
    }

    /// The OS's own text for `errno`, as [`io_cause`] shows it.
    #[cfg(unix)]
    fn os_text(errno: rustix::io::Errno) -> String {
        std::io::Error::from(errno).to_string()
    }

    // ── Splitting a target at its anchor ─────────────────────────────────────────

    /// A target splits into its anchor, the directories below it and its name; a file
    /// typed bare is anchored at `.`. A target whose name is not one — `.`, `..`, a root —
    /// or with `..` below its anchor is refused before anything is opened (#160).
    #[test]
    fn a_target_splits_at_its_anchor_and_below_it_is_names_only() {
        let target = WriteTarget::below(Path::new("out"), Path::new("o"), Path::new("a/b/x.md"));
        assert_eq!(
            Below::of(&target).unwrap(),
            Below {
                anchor: PathBuf::from("out"),
                dirs: vec![OsStr::new("a"), OsStr::new("b")],
                name: OsStr::new("x.md"),
            }
        );
        let bare = WriteTarget::as_typed(PathBuf::from("x.md"));
        assert_eq!(
            Below::of(&bare).unwrap(),
            Below {
                anchor: PathBuf::from("."),
                dirs: vec![],
                name: OsStr::new("x.md"),
            }
        );

        for typed in [".", "out/..", "/"] {
            let target = WriteTarget::as_typed(PathBuf::from(typed));
            let kind = Below::of(&target).map(|_| ()).unwrap_err().kind();
            assert_eq!(
                kind,
                std::io::ErrorKind::IsADirectory,
                "{typed:?} names a directory"
            );
        }
        let climbing =
            WriteTarget::below(Path::new("out"), Path::new("out"), Path::new("a/../x.md"));
        assert_eq!(
            Below::of(&climbing).map(|_| ()).unwrap_err().kind(),
            std::io::ErrorKind::InvalidInput,
            "a `..` below the anchor is refused"
        );
    }

    /// A target that ends in a separator, or in a separator and a `.`, names a directory,
    /// though `Path::components` drops that ending and leaves the name before it: `out/` and
    /// `out/.` are refused as a directory, never written as the file `out`. Controls: the
    /// same names without the ending, and a name that merely ends in a dot, split.
    #[test]
    fn a_target_ending_in_a_separator_names_a_directory() {
        let sep = std::path::MAIN_SEPARATOR_STR;
        for typed in [
            "out/".to_owned(),
            "out/.".to_owned(),
            "out/./".to_owned(),
            "sub/out/".to_owned(),
            format!("out{sep}"),
            format!("out{sep}."),
        ] {
            let target = WriteTarget::as_typed(PathBuf::from(&typed));
            let kind = Below::of(&target).map(|_| ()).unwrap_err().kind();
            assert_eq!(
                kind,
                std::io::ErrorKind::IsADirectory,
                "{typed:?} names a directory"
            );
        }
        for (typed, name) in [("out", "out"), ("sub/out", "out"), ("out.", "out.")] {
            let target = WriteTarget::as_typed(PathBuf::from(typed));
            assert_eq!(
                Below::of(&target).unwrap().name,
                OsStr::new(name),
                "{typed:?}"
            );
        }
    }

    /// A name holding a `:` is NTFS stream syntax on Windows — `lib.mds::$DATA` is the file
    /// `lib.mds` itself, `lib.md:x` a stream of `lib.md` — and is refused there before
    /// anything is opened, as an invalid file name (#425): a write by that name would land
    /// on a file its name does not say. On unix a `:` is an ordinary character, and such
    /// a name splits like any other. Control: a name without one.
    #[test]
    fn a_name_in_stream_syntax_is_refused_on_windows_alone() {
        assert!(names_a_stream(OsStr::new("lib.mds::$DATA")));
        assert!(names_a_stream(OsStr::new("lib.md:x")));
        assert!(!names_a_stream(OsStr::new("lib.md")));

        for name in ["lib.mds::$DATA", "lib.md:x"] {
            let target = WriteTarget::below(Path::new("out"), Path::new("o"), Path::new(name));
            let split = Below::of(&target).map(|below| below.name.to_owned());
            if cfg!(windows) {
                assert_eq!(
                    split.map_err(|e| e.kind()),
                    Err(std::io::ErrorKind::InvalidFilename),
                    "{name}"
                );
            } else {
                assert_eq!(split.unwrap(), OsStr::new(name));
            }
        }
        let plain = WriteTarget::below(Path::new("out"), Path::new("o"), Path::new("lib.md"));
        assert_eq!(Below::of(&plain).unwrap().name, OsStr::new("lib.md"));
    }

    /// On unix a file whose name holds a `:` is written like any other (#425): the
    /// refusal of stream syntax is Windows' alone.
    #[cfg(unix)]
    #[test]
    fn a_name_with_a_colon_is_written_on_unix() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a:b.md");
        write_as_typed(&file, "written", Durability::RenameOnly).unwrap();
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "written");
    }

    /// A refused directory is named below the anchor's shown form, cut after the level the
    /// symlink was found at.
    #[test]
    fn a_refused_directory_is_named_as_shown_down_to_the_link() {
        let target = WriteTarget::below(
            Path::new("/canonical/out"),
            Path::new("out"),
            Path::new("a/b/x.md"),
        );
        assert_eq!(shown_directory(&target, 0), Path::new("out").join("a"));
        assert_eq!(
            shown_directory(&target, 1),
            Path::new("out").join("a").join("b")
        );
    }

    // ── A symlink below the anchor (#160) ────────────────────────────────────────

    /// A symlink planted at a directory below the anchor is refused, named as shown, and
    /// nothing reaches the directory it points at; the link is left as it was. Controls:
    /// the same target writes once the link is a directory again, and a file written
    /// through the link by hand does reach the directory it points at.
    #[cfg(unix)]
    #[test]
    fn a_symlink_planted_below_the_anchor_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let anchor = dir.path().join("anchor");
        let victim = dir.path().join("victim");
        std::fs::create_dir_all(anchor.join("a")).unwrap();
        std::fs::create_dir(&victim).unwrap();
        std::os::unix::fs::symlink(&victim, anchor.join("a").join("b")).unwrap();
        let target = WriteTarget::below(&anchor, Path::new("out"), Path::new("a/b/x.md"));

        for parents in [Parents::Create, Parents::Existing] {
            let err = atomic_write_file(&target, "X", Durability::Fsync, parents)
                .expect_err("a symlink below the anchor is refused")
                .to_string();
            assert_eq!(
                err,
                "cannot write out/a/b/x.md: refusing to follow a symlink at out/a/b"
            );
        }
        assert_eq!(entries(&victim), Vec::<String>::new());
        assert!(std::fs::symlink_metadata(anchor.join("a/b"))
            .unwrap()
            .file_type()
            .is_symlink());

        std::fs::remove_file(anchor.join("a/b")).unwrap();
        atomic_write_file(&target, "X", Durability::Fsync, Parents::Create).unwrap();
        assert_eq!(
            std::fs::read_to_string(anchor.join("a/b/x.md")).unwrap(),
            "X"
        );
        std::fs::remove_dir_all(anchor.join("a/b")).unwrap();
        std::os::unix::fs::symlink(&victim, anchor.join("a").join("b")).unwrap();
        std::fs::write(anchor.join("a/b/by-hand"), "x").unwrap();
        assert_eq!(entries(&victim), vec!["by-hand".to_owned()]);
    }

    /// A failed open of a directory below the anchor is a symlink refusal when the open
    /// said `ELOOP` — a link swapped back for a directory before it could be looked at
    /// again included — or when the name is a symlink, whatever the open said; any other
    /// failure of a directory is the write's own.
    #[cfg(unix)]
    #[test]
    fn a_failed_open_below_the_anchor_is_refused_when_it_met_a_symlink() {
        use std::os::fd::AsFd as _;

        use rustix::io::Errno;

        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join("real")).unwrap();
        std::os::unix::fs::symlink("real", dir.path().join("link")).unwrap();
        let fd = rustix::fs::open(
            dir.path(),
            rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::DIRECTORY,
            rustix::fs::Mode::empty(),
        )
        .unwrap();
        let failure =
            |name: &str, errno| super::unix::below_failure(fd.as_fd(), OsStr::new(name), 3, errno);

        assert!(
            matches!(
                failure("real", Errno::LOOP),
                Failure::LinkBelowAnchor { depth: 3 }
            ),
            "ELOOP is a symlink, though a directory is there now"
        );
        assert!(
            matches!(
                failure("link", Errno::NOTDIR),
                Failure::LinkBelowAnchor { depth: 3 }
            ),
            "a symlink there now is refused, whatever the open said"
        );
        for errno in [Errno::NOTDIR, Errno::ACCESS] {
            assert!(
                matches!(failure("real", errno), Failure::Io(_)),
                "{errno:?} of a directory is the write's own failure"
            );
        }
    }

    /// A directory the user may write to and search but not list — a drop box, mode
    /// `0o333` — takes a write on Linux and Android, as the anchor and as a directory below
    /// it, since the walk opens each for search alone (#160). Elsewhere the walk opens each
    /// to read, which such a directory refuses: `Permission denied`, and nothing written.
    #[cfg(unix)]
    #[test]
    fn a_directory_that_cannot_be_listed_takes_a_write_on_linux_alone() {
        use std::os::unix::fs::PermissionsExt as _;

        let dir = tempfile::tempdir().unwrap();
        let drop_box = dir.path().join("box");
        std::fs::create_dir(&drop_box).unwrap();
        let mode =
            |mode| std::fs::set_permissions(&drop_box, std::fs::Permissions::from_mode(mode));
        mode(0o333).unwrap();
        if std::fs::read_dir(&drop_box).is_ok() {
            mode(0o755).unwrap();
            crate::output::ewriteln!("running as root; mode 0o333 does not stop a listing");
            return;
        }
        let as_anchor = WriteTarget::as_typed(drop_box.join("anchor.md"));
        let below = WriteTarget::below(dir.path(), Path::new("out"), Path::new("box/below.md"));
        let written = [&as_anchor, &below].map(|target| {
            atomic_write_file(target, "X", Durability::RenameOnly, Parents::Existing)
                .map_err(|e| e.to_string())
        });
        // Read by path, which the directory's search permission allows.
        let landed =
            ["anchor.md", "below.md"].map(|name| std::fs::read_to_string(drop_box.join(name)).ok());
        // Restored before anything is asserted, so the scratch directory can be removed.
        mode(0o755).unwrap();

        if cfg!(any(target_os = "linux", target_os = "android")) {
            assert_eq!(written, [Ok(()), Ok(())]);
            assert_eq!(landed, [Some("X".to_owned()), Some("X".to_owned())]);
            assert_eq!(entries(&drop_box), ["anchor.md", "below.md"]);
        } else {
            let denied = "Permission denied (os error 13)";
            let [anchor_err, below_err] = written.map(|w| w.expect_err("a drop box is refused"));
            assert!(
                anchor_err.starts_with("cannot write ") && anchor_err.ends_with(denied),
                "{anchor_err}"
            );
            assert_eq!(
                below_err,
                format!("cannot write out/box/below.md: {denied}")
            );
            assert_eq!(landed, [None, None]);
            assert_eq!(entries(&drop_box), Vec::<String>::new());
        }
    }

    /// The walk's search-only open, refused by a kernel or a filesystem (`EINVAL`), is made
    /// again to read; any other failure is the open's, and an open whose search flag is
    /// none of its own — a platform without one — is never made twice.
    #[cfg(unix)]
    #[test]
    fn a_search_only_open_that_is_refused_is_made_again_to_read() {
        use std::cell::RefCell;

        use rustix::fs::OFlags;
        use rustix::io::Errno;

        // A stand-in for `O_PATH`, which this platform may not have.
        let search = OFlags::NONBLOCK;
        let flags = OFlags::DIRECTORY | search;
        let opens = |refusal: Errno, search: OFlags| {
            let asked = RefCell::new(Vec::new());
            let opened = super::unix::search_or_read(flags, search, |with: OFlags| {
                asked.borrow_mut().push(with);
                if with.contains(OFlags::NONBLOCK) {
                    Err(refusal)
                } else {
                    Ok(())
                }
            });
            (opened, asked.into_inner())
        };

        assert_eq!(
            opens(Errno::INVAL, search),
            (Ok(()), vec![flags, OFlags::DIRECTORY]),
            "refused: opened again to read"
        );
        assert_eq!(
            opens(Errno::ACCESS, search),
            (Err(Errno::ACCESS), vec![flags]),
            "any other failure is the open's"
        );
        assert_eq!(
            opens(Errno::INVAL, OFlags::empty()),
            (Err(Errno::INVAL), vec![flags]),
            "no search flag of its own: nothing to open again without"
        );
    }

    /// A rewrite whose rename landed in a directory that could not then be synced — made
    /// `-wx` between the rewrite's read and its replace, so the sync cannot open it to
    /// read — is [`Rewritten::NotSynced`]: the file holds the rewrite, and the error names
    /// it with the sync's cause (#160). Controls: the rename-only tier syncs no directory
    /// and is done; the same rewrite in a directory left alone is synced, and no temporary
    /// file is left either way.
    #[cfg(unix)]
    #[test]
    fn a_rewrite_whose_directory_cannot_be_synced_is_written_and_said_so() {
        use std::os::unix::fs::PermissionsExt as _;

        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        std::fs::create_dir(&src).unwrap();
        let file = src.join("a.mds");
        let target = WriteTarget::below(dir.path(), Path::new("out"), Path::new("src/a.mds"));
        let mode = |mode| std::fs::set_permissions(&src, std::fs::Permissions::from_mode(mode));
        // The rewrite's outcome — the error of a directory not synced, if any — what the
        // file holds, and whether the directory could be listed while it was `-wx`.
        let rewrite_unlistable = |durability| {
            std::fs::write(&file, "OLD").unwrap();
            let read = read_stamped(&target, "OLD").unwrap();
            mode(0o333).unwrap();
            let rewritten = replace_if_unchanged(read, "NEW", durability).map(|r| match r {
                Rewritten::Done => None,
                Rewritten::NotSynced(e) => Some(e.to_string()),
            });
            // Read by path, which the directory's search permission allows.
            let landed = std::fs::read_to_string(&file).unwrap();
            let listable = std::fs::read_dir(&src).is_ok();
            mode(0o755).unwrap();
            (rewritten.map_err(|e| e.to_string()), landed, listable)
        };

        let (fsync, landed, listable) = rewrite_unlistable(Durability::Fsync);
        if listable {
            crate::output::ewriteln!("running as root; mode 0o333 does not stop a listing");
            return;
        }
        assert_eq!(
            fsync,
            Ok(Some(
                "out/src/a.mds written, but its directory could not be synced: Permission \
                 denied (os error 13)"
                    .to_owned()
            ))
        );
        assert_eq!(landed, "NEW", "the rewrite landed");
        assert_eq!(
            rewrite_unlistable(Durability::RenameOnly),
            (Ok(None), "NEW".to_owned(), false),
            "control: the rename-only tier syncs no directory"
        );

        std::fs::write(&file, "OLD").unwrap();
        let read = read_stamped(&target, "OLD").unwrap();
        assert!(
            matches!(
                replace_if_unchanged(read, "NEW", Durability::Fsync),
                Ok(Rewritten::Done)
            ),
            "control: a directory left alone is synced"
        );
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "NEW");
        assert_eq!(entries(&src), ["a.mds"]);
    }

    /// `file`, below the anchor `root` and shown below `d`, written `OLD` and rewritten
    /// `NEW`, the sync of its directory owed ([`replace_owing_sync`]).
    #[cfg(unix)]
    fn owing(root: &Path, file: &str) -> Renamed {
        std::fs::write(root.join(file), "OLD").unwrap();
        let target = WriteTarget::below(root, Path::new("d"), Path::new(file));
        replace_owing_sync(read_stamped(&target, "OLD").unwrap(), "NEW").unwrap()
    }

    /// What `flushed` gives back, each rewrite as its caller would show it: `synced <file>`,
    /// or the error that takes the place of its status line.
    #[cfg(unix)]
    fn shown(flushed: Option<Flushed<&str>>) -> Vec<String> {
        flushed
            .into_iter()
            .flatten()
            .map(|synced| match synced {
                Synced::Durable(file) => format!("synced {file}"),
                Synced::NotSynced(file, e) => format!("{file}: {e}"),
            })
            .collect()
    }

    /// A directory run's rewrites owe their directory's sync until the run is past the last
    /// of its files there, every file of the run counted: then that directory is synced
    /// once, and its rewrites come back, each once, in the order they were renamed (#160).
    /// Here `sub/x.mds` lies between `src`'s files, as a walk can find it: `sub` is synced
    /// when the run is past `x.mds`, the anchor's directory when it is past `c.mds` — two
    /// syncs for four rewrites, each file holding its rewrite. When the syncs fail, each
    /// rewrite comes back with the error that names it, `d/<file> written, but its
    /// directory could not be synced: <cause>`, and still only once.
    #[cfg(unix)]
    #[test]
    fn owed_syncs_are_made_once_for_each_directory_after_its_last_file() {
        use sync_probe::{directory_syncs, failing_with};

        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir(root.join("sub")).unwrap();
        let files = ["a.mds", "sub/x.mds", "b.mds", "c.mds"];
        // What each place of the run gave back, where it gave anything, and the syncs made.
        let run = || {
            let mut syncs = DirectorySyncs::new(files.iter().map(Path::new));
            let before = directory_syncs();
            let mut at = Vec::new();
            for (place, &file) in files.iter().enumerate() {
                let mut back = shown(syncs.landed(place, owing(root, file), file));
                back.extend(shown(syncs.past(place)));
                if !back.is_empty() {
                    at.push((place, back));
                }
            }
            for file in files {
                assert_eq!(std::fs::read_to_string(root.join(file)).unwrap(), "NEW");
            }
            (at, directory_syncs() - before)
        };

        let synced = |file: &str| format!("synced {file}");
        assert_eq!(
            run(),
            (
                vec![
                    (1, vec![synced("sub/x.mds")]),
                    (3, ["a.mds", "b.mds", "c.mds"].map(synced).to_vec()),
                ],
                2
            )
        );

        let failing = failing_with(5);
        let cause = std::io::Error::from_raw_os_error(5);
        let not_synced = |file: &str| {
            format!("{file}: d/{file} written, but its directory could not be synced: {cause}")
        };
        assert_eq!(
            run(),
            (
                vec![
                    (1, vec![not_synced("sub/x.mds")]),
                    (3, ["a.mds", "b.mds", "c.mds"].map(not_synced).to_vec()),
                ],
                2
            ),
            "a failed sync comes back for each rewrite owed there, once"
        );
        drop(failing);
    }

    /// A rewrite renamed into another directory than the one its directory's owed rewrites
    /// went in — the same path, a directory swapped in between — has those synced at once,
    /// in their own directory, and owes a sync of its own (#160): two syncs, the first when
    /// it lands. Control: the same two rewrites in one directory are one sync, made when the
    /// run is past the second.
    #[cfg(unix)]
    #[test]
    fn a_rewrite_into_a_directory_swapped_in_syncs_the_one_before_it_first() {
        use sync_probe::directory_syncs;

        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir(root.join("s")).unwrap();
        let files = ["s/a.mds", "s/b.mds"];
        // What landing `s/b.mds` gave back, then the run's being past it, and the syncs.
        let run = |swap: bool| {
            let mut syncs = DirectorySyncs::new(files.iter().map(Path::new));
            let before = directory_syncs();
            assert!(shown(syncs.landed(0, owing(root, files[0]), files[0])).is_empty());
            assert!(
                shown(syncs.past(0)).is_empty(),
                "s/a.mds is not s's last file"
            );
            if swap {
                std::fs::rename(root.join("s"), root.join("s-old")).unwrap();
                std::fs::create_dir(root.join("s")).unwrap();
            }
            let landed = shown(syncs.landed(1, owing(root, files[1]), files[1]));
            let past = shown(syncs.past(1));
            (landed, past, directory_syncs() - before)
        };

        assert_eq!(
            run(false),
            (
                Vec::new(),
                vec!["synced s/a.mds".to_string(), "synced s/b.mds".to_string()],
                1
            ),
            "control: one directory"
        );
        assert_eq!(
            run(true),
            (
                vec!["synced s/a.mds".to_string()],
                vec!["synced s/b.mds".to_string()],
                2
            )
        );
        assert_eq!(
            std::fs::read_to_string(root.join("s-old/a.mds")).unwrap(),
            "NEW"
        );
    }

    /// A rewrite at a place the run did not name has no directory's last file to wait for:
    /// it is synced as it lands, and comes back at once (#160).
    #[cfg(unix)]
    #[test]
    fn a_rewrite_at_a_place_the_run_did_not_name_is_synced_at_once() {
        use sync_probe::directory_syncs;

        let dir = tempfile::tempdir().unwrap();
        let mut syncs = DirectorySyncs::new([Path::new("a.mds")]);
        let before = directory_syncs();
        assert_eq!(
            shown(syncs.landed(1, owing(dir.path(), "x.mds"), "x.mds")),
            ["synced x.mds"]
        );
        assert_eq!(directory_syncs() - before, 1);
        assert!(shown(syncs.past(0)).is_empty(), "nothing is owed for a.mds");
    }

    /// The Fsync tier's sync of a file's bytes before the rename: the full sync asked for
    /// first — `F_FULLFSYNC` on Apple platforms — refused by a filesystem (`ENOTSUP`,
    /// `EOPNOTSUPP`, `EINVAL`) falls back to a plain one, and only then. A sync that fails,
    /// the plain one refused too included, is the write's failure: a file's bytes are not
    /// to be had unsynced, unlike a directory's sync.
    #[cfg(unix)]
    #[test]
    fn a_file_sync_the_filesystem_refuses_falls_back_to_a_plain_one() {
        use rustix::io::Errno;

        let fail = |errno: Errno| -> std::io::Result<()> { Err(errno.into()) };
        let sync = |full: std::io::Result<()>, plain: Option<std::io::Result<()>>| {
            let mut fell_back = false;
            let synced = super::unix::full_or_plain(
                || full,
                || {
                    fell_back = true;
                    plain.expect("no fallback after this sync")
                },
            );
            (synced.map_err(|e| Errno::from_io_error(&e)), fell_back)
        };

        assert_eq!(sync(Ok(()), None), (Ok(()), false), "synced");
        for refusal in [Errno::NOTSUP, Errno::OPNOTSUPP, Errno::INVAL] {
            assert_eq!(
                sync(fail(refusal), Some(Ok(()))),
                (Ok(()), true),
                "{refusal:?}, then a plain sync"
            );
            assert_eq!(
                sync(fail(refusal), Some(fail(Errno::INVAL))),
                (Err(Some(Errno::INVAL)), true),
                "{refusal:?}, then a plain sync refused too: the write's error"
            );
            assert_eq!(
                sync(fail(refusal), Some(fail(Errno::IO))),
                (Err(Some(Errno::IO)), true),
                "{refusal:?}, then a plain sync that fails: the write's error"
            );
        }
        assert_eq!(
            sync(fail(Errno::IO), None),
            (Err(Some(Errno::IO)), false),
            "a failed sync is the write's error, with no fallback"
        );
    }

    /// The Fsync tier's directory sync, after the rename has landed: a sync refused for a
    /// directory (`ENOTSUP`, `EOPNOTSUPP`, `EINVAL`) falls back to a plain one, and a
    /// filesystem that refuses that too cannot sync a directory at all — the write stands,
    /// with no error. Any other failure, of either sync, is the sync's, which the write
    /// reports as written but not synced; the fallback is made only after a refusal.
    #[cfg(unix)]
    #[test]
    fn a_directory_sync_the_filesystem_refuses_twice_does_not_fail_the_write() {
        use rustix::io::Errno;

        let fail = |errno: Errno| -> std::io::Result<()> { Err(errno.into()) };
        let settle = |full: std::io::Result<()>, plain: Option<std::io::Result<()>>| {
            let mut fell_back = false;
            let settled = super::unix::settle_directory_sync(
                || full,
                || {
                    fell_back = true;
                    plain.expect("no fallback after this sync")
                },
            );
            (settled.map_err(|e| Errno::from_io_error(&e)), fell_back)
        };

        assert_eq!(settle(Ok(()), None), (Ok(()), false), "synced");
        for refusal in [Errno::NOTSUP, Errno::OPNOTSUPP, Errno::INVAL] {
            assert_eq!(
                settle(fail(refusal), Some(Ok(()))),
                (Ok(()), true),
                "{refusal:?}, then a plain sync"
            );
            assert_eq!(
                settle(fail(refusal), Some(fail(Errno::INVAL))),
                (Ok(()), true),
                "{refusal:?}, then a plain sync refused too: no directory sync to be had"
            );
            assert_eq!(
                settle(fail(refusal), Some(fail(Errno::IO))),
                (Err(Some(Errno::IO)), true),
                "{refusal:?}, then a plain sync that fails: the sync's error"
            );
        }
        assert_eq!(
            settle(fail(Errno::IO), None),
            (Err(Some(Errno::IO)), false),
            "a failed sync is the sync's error, with no fallback"
        );
    }

    /// A symlinked anchor is followed: the anchor is resolved by path, as the user typed it
    /// (#160). Control for the refusal above: the same link, as the anchor itself, writes.
    #[test]
    fn a_symlinked_anchor_is_followed() {
        let dir = tempfile::tempdir().unwrap();
        let real = dir.path().join("real");
        std::fs::create_dir(&real).unwrap();
        let link = dir.path().join("link");
        if !make_symlink(&real, &link) {
            return;
        }
        let target = WriteTarget::below(&link, Path::new("link"), Path::new("sub/x.md"));
        atomic_write_file(&target, "X", Durability::RenameOnly, Parents::Create).unwrap();
        assert_eq!(
            std::fs::read_to_string(real.join("sub").join("x.md")).unwrap(),
            "X"
        );
    }

    /// A write `mds watch` makes below its out-dir names the directory its check found
    /// there, and an anchor the write opens that is another directory — the out-dir
    /// swapped between the check and the write, here a sibling's identity named instead
    /// — is refused with the out-dir refusal, the file named as shown, and nothing is
    /// written or created below it (#160). Control: the identity of the directory opened
    /// writes.
    ///
    /// `#[cfg(unix)]`: two directories made a moment apart are told apart by their inode
    /// there; Windows has their creation times alone, which can be equal.
    #[cfg(unix)]
    #[test]
    fn a_write_whose_anchor_is_not_the_directory_checked_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("out");
        let other = dir.path().join("other");
        for made in [&out, &other] {
            std::fs::create_dir(made).unwrap();
        }
        let identity = |of: &Path| DirIdentity::of(of).expect("a directory");
        let target = WriteTarget::below(&out, Path::new("o"), Path::new("sub/x.md"));

        let swapped = target.below_checked_anchor(&out, 0, identity(&other));
        let err = atomic_write_file(&swapped, "X", Durability::RenameOnly, Parents::Create)
            .expect_err("the anchor opened is not the directory checked")
            .to_string();
        assert_eq!(
            err,
            format!("cannot write {}: {OUT_DIR_MOVED}", safe_path(&target.shown))
        );
        assert_eq!(
            entries(&out),
            Vec::<String>::new(),
            "nothing is written or created below it"
        );

        let checked = target.below_checked_anchor(&out, 0, identity(&out));
        atomic_write_file(&checked, "X", Durability::RenameOnly, Parents::Create).unwrap();
        assert_eq!(
            std::fs::read_to_string(out.join("sub").join("x.md")).unwrap(),
            "X"
        );
    }

    /// An out-dir the check found missing is written below the directory above it, the
    /// one checked, and created there without following a symlink (#160): a write that
    /// opens another directory as that anchor is refused and creates nothing, and a
    /// symlink put where the out-dir is to be made is refused, its target left empty.
    /// Control: the directory checked, opened, gets the out-dir and the file.
    #[cfg(unix)]
    #[test]
    fn a_missing_out_dir_is_made_below_the_directory_checked_above_it() {
        let dir = tempfile::tempdir().unwrap();
        let base = dir.path().join("base");
        let other = dir.path().join("other");
        let victim = dir.path().join("victim");
        for made in [&base, &other, &victim] {
            std::fs::create_dir(made).unwrap();
        }
        let identity = |of: &Path| DirIdentity::of(of).expect("a directory");
        let out = base.join("out");
        let target = WriteTarget::below(&out, Path::new("o"), Path::new("x.md"));
        let write = |anchor: &Path| {
            let checked = target.below_checked_anchor(&out, 1, identity(anchor));
            atomic_write_file(&checked, "X", Durability::RenameOnly, Parents::Create)
        };

        let err = write(&other)
            .expect_err("not the directory checked")
            .to_string();
        assert_eq!(
            err,
            format!("cannot write {}: {OUT_DIR_MOVED}", safe_path(&target.shown))
        );
        assert!(!out.exists(), "nothing is created");

        std::os::unix::fs::symlink(&victim, &out).unwrap();
        let err = write(&base)
            .expect_err("a link where the out-dir goes")
            .to_string();
        assert_eq!(err, format!("cannot write o/x.md: {FOLLOW_REFUSAL} at o"));
        assert_eq!(
            entries(&victim),
            Vec::<String>::new(),
            "nothing lands there"
        );
        std::fs::remove_file(&out).unwrap();

        write(&base).unwrap();
        assert_eq!(std::fs::read_to_string(out.join("x.md")).unwrap(), "X");
    }

    /// An anchor a check found is never made again by path (#160): a write that finds it
    /// gone is refused with the out-dir refusal and creates nothing, so no directory is
    /// made wherever that path leads by then; the next check finds the directory above it.
    /// Control: the same target, named with no directory to expect, is created by path,
    /// as any output's anchor is.
    #[test]
    fn a_checked_anchor_that_is_gone_is_not_made_again() {
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("out");
        std::fs::create_dir(&out).unwrap();
        let identity = DirIdentity::of(&out).expect("a directory");
        std::fs::remove_dir(&out).unwrap();
        let target = WriteTarget::below(&out, Path::new("o"), Path::new("x.md"));

        let checked = target.below_checked_anchor(&out, 0, identity);
        let err = atomic_write_file(&checked, "X", Durability::RenameOnly, Parents::Create)
            .expect_err("the anchor checked is gone")
            .to_string();
        assert_eq!(
            err,
            format!("cannot write {}: {OUT_DIR_MOVED}", safe_path(&target.shown))
        );
        assert!(!out.exists(), "nothing is made by path");

        atomic_write_file(&target, "X", Durability::RenameOnly, Parents::Create).unwrap();
        assert_eq!(std::fs::read_to_string(out.join("x.md")).unwrap(), "X");
    }

    /// A bounded swap loop (#160): while a thread swaps a directory below the anchor
    /// between a directory and a symlink, at most 2,000 writes in at most 10 s land
    /// nothing in the link's target. Controls: the loop met both states — some writes
    /// landed, some were refused — and a file written through the link by hand does reach
    /// its target.
    #[cfg(unix)]
    #[test]
    fn a_swap_loop_below_the_anchor_lands_nothing_in_the_link_s_target() {
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::Arc;
        use std::time::{Duration, Instant};

        /// How long each state is held: about as long as a write takes.
        const HOLD: Duration = Duration::from_micros(200);

        let dir = tempfile::tempdir().unwrap();
        let anchor = dir.path().join("anchor");
        let victim = dir.path().join("victim");
        std::fs::create_dir_all(anchor.join("sub")).unwrap();
        std::fs::create_dir(&victim).unwrap();
        let target = WriteTarget::below(&anchor, Path::new("out"), Path::new("sub/x.md"));

        let stop = Arc::new(AtomicBool::new(false));
        let swapper = {
            let stop = Arc::clone(&stop);
            let (anchor, victim) = (anchor.clone(), victim.clone());
            std::thread::spawn(move || {
                let sub = anchor.join("sub");
                // Bounded: at most 100,000 swaps, and the loop ends with the writes.
                for i in 0..100_000u32 {
                    if stop.load(Ordering::Relaxed) {
                        break;
                    }
                    let _ = std::fs::rename(&sub, anchor.join(format!("away-{i}")));
                    let _ = std::os::unix::fs::symlink(&victim, &sub);
                    std::thread::sleep(HOLD);
                    if std::fs::remove_file(&sub).is_err() {
                        let _ = std::fs::rename(&sub, anchor.join(format!("away-{i}-b")));
                    }
                    let _ = std::fs::create_dir(&sub);
                    std::thread::sleep(HOLD);
                }
            })
        };

        let started = Instant::now();
        let (mut written, mut refused) = (0u32, 0u32);
        // Bounded: 2,000 writes or 10 s, whichever comes first.
        for _ in 0..2_000 {
            if started.elapsed() > Duration::from_secs(10) {
                break;
            }
            match atomic_write_file(&target, "X", Durability::RenameOnly, Parents::Create) {
                Ok(()) => written += 1,
                Err(e) if e.to_string().contains(FOLLOW_REFUSAL) => refused += 1,
                Err(_) => {}
            }
        }
        stop.store(true, Ordering::Relaxed);
        swapper.join().unwrap();

        assert_eq!(
            entries(&victim),
            Vec::<String>::new(),
            "nothing landed in the link's target ({written} written, {refused} refused)"
        );
        assert!(
            written > 0 && refused > 0,
            "the loop met both states: {written} written, {refused} refused"
        );
        let _ = std::fs::remove_file(anchor.join("sub"));
        let _ = std::fs::remove_dir_all(anchor.join("sub"));
        std::os::unix::fs::symlink(&victim, anchor.join("sub")).unwrap();
        std::fs::write(anchor.join("sub/by-hand"), "x").unwrap();
        assert_eq!(entries(&victim), vec!["by-hand".to_owned()]);
    }

    // ── Directories a write creates ─────────────────────────────────────────────

    /// `Parents::Create` creates a missing anchor by path and the directories below it;
    /// `Parents::Existing` creates nothing and fails. Control: the first writes.
    #[test]
    fn only_an_output_creates_its_directories() {
        let dir = tempfile::tempdir().unwrap();
        let anchor = dir.path().join("new").join("anchor");
        let target = WriteTarget::below(&anchor, Path::new("out"), Path::new("a/b/x.md"));

        let err = atomic_write_file(&target, "X", Durability::RenameOnly, Parents::Existing)
            .expect_err("nothing is created for a rewrite")
            .to_string();
        let named = format!("cannot write {}: ", safe_path(&target.shown));
        assert!(err.starts_with(&named), "{err}");
        assert!(!dir.path().join("new").exists(), "nothing was created");

        atomic_write_file(&target, "X", Durability::RenameOnly, Parents::Create).unwrap();
        assert_eq!(
            std::fs::read_to_string(anchor.join("a").join("b").join("x.md")).unwrap(),
            "X"
        );
    }

    /// An anchor that is a symlink leading nowhere is a directory that is not there: the
    /// write says so, rather than the `File exists` creating it fails with, and creates
    /// nothing where the link points. Control: once the link leads to a directory, the
    /// write lands there.
    #[test]
    fn a_dangling_symlink_anchor_is_reported_as_missing() {
        let dir = tempfile::tempdir().unwrap();
        let link = dir.path().join("link");
        let nowhere = dir.path().join("nowhere");
        // A directory link (Windows tells the kinds apart), then left leading nowhere.
        std::fs::create_dir(&nowhere).unwrap();
        if !make_symlink(&nowhere, &link) {
            return;
        }
        std::fs::remove_dir(&nowhere).unwrap();
        let target = WriteTarget::below(&link, Path::new("o"), Path::new("x.md"));

        let err = atomic_write_file(&target, "X", Durability::RenameOnly, Parents::Create)
            .expect_err("a dangling anchor cannot be written below")
            .to_string();
        #[cfg(unix)]
        let missing = os_text(rustix::io::Errno::NOENT);
        // `ERROR_PATH_NOT_FOUND`.
        #[cfg(windows)]
        let missing = std::io::Error::from_raw_os_error(3).to_string();
        assert_eq!(
            err,
            format!("cannot write {}: {missing}", safe_path(&target.shown))
        );
        assert!(
            !nowhere.exists(),
            "nothing was created where the link points"
        );

        std::fs::create_dir(&nowhere).unwrap();
        atomic_write_file(&target, "X", Durability::RenameOnly, Parents::Create).unwrap();
        assert_eq!(std::fs::read_to_string(nowhere.join("x.md")).unwrap(), "X");
    }

    // ── A rewrite over the bytes it read ─────────────────────────────────────────

    /// A rewrite's second read holds the file only as it was read (#160): other bytes,
    /// more bytes, a file gone and a symlink in its place are each refused; a file edited
    /// after the read is not replaced — the edit is left and no temporary file — and one
    /// as it was read is (control).
    ///
    /// Each edit changes the file's size: a filesystem whose clock is coarser than the
    /// time between two writes can give an edit of the same size the same times.
    ///
    /// Runs on every platform, so the Windows stamp — size and times, by path — is held to
    /// the same rule as the unix one; only the symlink arm waits on [`make_symlink`].
    #[test]
    fn a_rewrite_replaces_only_the_file_as_it_was_read() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a.mds");
        let target = WriteTarget::new(file.clone(), PathBuf::from("a.mds"));
        let changed = format!(
            "cannot write {}: changed since it was read; not written",
            safe_path(&target.shown)
        );
        let refused = |read: &str| {
            read_stamped(&target, read)
                .map(|_| ())
                .expect_err("not the file as read")
                .to_string()
        };
        std::fs::write(&file, "one").unwrap();
        assert_eq!(refused("two"), changed, "other bytes");
        assert_eq!(refused("on"), changed, "more bytes than were read");

        let read = read_stamped(&target, "one").unwrap();
        std::fs::write(&file, "edited").unwrap();
        let err = replace_if_unchanged(read, "ONE", Durability::Fsync)
            .expect_err("edited after the read")
            .to_string();
        assert_eq!(err, changed);
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "edited");
        assert_eq!(temp_residue(dir.path()), Vec::<String>::new());

        let read = read_stamped(&target, "edited").unwrap();
        assert!(matches!(
            replace_if_unchanged(read, "EDITED", Durability::Fsync),
            Ok(Rewritten::Done)
        ));
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "EDITED");

        std::fs::remove_file(&file).unwrap();
        assert_eq!(refused("EDITED"), changed, "gone");
        if make_symlink(&dir.path().join("elsewhere"), &file) {
            assert_eq!(
                refused("EDITED"),
                format!(
                    "cannot write {}: {SYMLINK_REFUSAL}",
                    safe_path(&target.shown)
                ),
                "a symlink in its place"
            );
        }
    }

    // ── A new file, never over another ───────────────────────────────────────────

    /// [`create_new`] puts a file where nothing is, and refuses a target that is there
    /// ([`NotCreated::Exists`]), the file left as it is and no temporary file (#160). A
    /// symlink there is refused as a symlink, and nothing is written through it. Control:
    /// [`atomic_write_file`] replaces the same file.
    #[test]
    fn a_new_file_is_never_put_where_a_file_is() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a.mds");
        let target = WriteTarget::new(file.clone(), PathBuf::from("a.mds"));
        let new = |content: &str| {
            create_new(&target, content, Durability::RenameOnly, Parents::Existing).map_err(
                |not_created| match not_created {
                    NotCreated::Exists => "exists".to_owned(),
                    NotCreated::Failed(e) => e.to_string(),
                },
            )
        };

        new("first").unwrap();
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "first");
        assert_eq!(new("second"), Err("exists".to_owned()));
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "first");
        assert_eq!(temp_residue(dir.path()), Vec::<String>::new());

        atomic_write_file(
            &target,
            "replaced",
            Durability::RenameOnly,
            Parents::Existing,
        )
        .unwrap();
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "replaced");

        std::fs::remove_file(&file).unwrap();
        let elsewhere = dir.path().join("elsewhere");
        if make_symlink(&elsewhere, &file) {
            assert_eq!(
                new("third"),
                Err(format!(
                    "cannot write {}: {SYMLINK_REFUSAL}",
                    safe_path(&target.shown)
                ))
            );
            assert!(!elsewhere.exists(), "nothing is written through the link");
        }
    }

    /// [`write_over_own`] of `target`, its directories already there, with what it did
    /// not write as text: `kept` for [`NotCreated::Exists`], else the error's.
    fn over_own(target: &WriteTarget, own: Option<&str>, content: &str) -> Result<(), String> {
        write_over_own(
            target,
            own,
            content,
            Durability::RenameOnly,
            Parents::Existing,
        )
        .map_err(|not_written| match not_written {
            NotCreated::Exists => "kept".to_owned(),
            NotCreated::Failed(e) => e.to_string(),
        })
    }

    /// [`write_over_own`] replaces only the caller's own file, unchanged, and otherwise
    /// writes only where nothing is (#160): nothing there — whether or not the caller wrote
    /// there before — and the file is created; the file holding exactly what the caller
    /// wrote is replaced; a file the caller did not write, one changed since, one with
    /// more bytes, a directory and a symlink — even to a file holding the caller's bytes —
    /// are kept ([`NotCreated::Exists`]), each as it was, nothing written through the
    /// link, and no temporary file left.
    #[test]
    fn a_write_over_its_own_file_replaces_no_other() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a.md");
        let target = WriteTarget::new(file.clone(), PathBuf::from("a.md"));
        let text = || std::fs::read_to_string(&file).unwrap();
        let kept = Err("kept".to_owned());

        assert_eq!(over_own(&target, None, "first"), Ok(()), "nothing there");
        assert_eq!(text(), "first");
        assert_eq!(over_own(&target, None, "second"), kept, "not the caller's");
        assert_eq!(text(), "first");
        assert_eq!(
            over_own(&target, Some("first"), "second"),
            Ok(()),
            "the caller's own, unchanged"
        );
        assert_eq!(text(), "second");
        assert_eq!(
            over_own(&target, Some("first"), "third"),
            kept,
            "changed since the caller wrote it"
        );
        assert_eq!(
            over_own(&target, Some("secon"), "third"),
            kept,
            "more bytes"
        );
        assert_eq!(text(), "second");
        assert_eq!(temp_residue(dir.path()), Vec::<String>::new());

        std::fs::remove_file(&file).unwrap();
        assert_eq!(over_own(&target, Some("second"), "third"), Ok(()), "gone");
        assert_eq!(text(), "third");

        std::fs::remove_file(&file).unwrap();
        std::fs::create_dir(&file).unwrap();
        assert_eq!(
            over_own(&target, Some("third"), "fourth"),
            kept,
            "a directory"
        );
        assert!(file.is_dir(), "the directory is left");
        std::fs::remove_dir(&file).unwrap();

        let elsewhere = dir.path().join("elsewhere");
        std::fs::write(&elsewhere, "third").unwrap();
        if make_symlink(&elsewhere, &file) {
            for own in [Some("third"), None] {
                assert_eq!(over_own(&target, own, "fourth"), kept, "a symlink, {own:?}");
            }
            assert_eq!(
                std::fs::read_to_string(&elsewhere).unwrap(),
                "third",
                "nothing is written through the link"
            );
            assert!(std::fs::symlink_metadata(&file)
                .unwrap()
                .file_type()
                .is_symlink());
        }
        assert_eq!(temp_residue(dir.path()), Vec::<String>::new());
    }

    /// A FIFO at the target of [`write_over_own`] is kept, never opened — the write does
    /// not wait on it — whether or not the caller wrote there (#160).
    #[cfg(unix)]
    #[test]
    fn a_write_over_its_own_file_keeps_a_fifo() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a.md");
        let made = std::process::Command::new("mkfifo")
            .arg(&file)
            .status()
            .expect("mkfifo runs");
        assert!(made.success(), "mkfifo a.md");
        let target = WriteTarget::new(file.clone(), PathBuf::from("a.md"));
        for own in [Some("first"), None] {
            assert_eq!(
                over_own(&target, own, "second"),
                Err("kept".to_owned()),
                "{own:?}"
            );
        }
        assert_eq!(
            entries(dir.path()),
            ["a.md"],
            "the FIFO is left, and no temporary file"
        );
    }

    /// A socket at the target of [`write_over_own`] is kept, whether or not the caller wrote
    /// there (#160): a socket refuses the read's open, and is no file of the caller's, as a
    /// FIFO is none.
    #[cfg(unix)]
    #[test]
    fn a_write_over_its_own_file_keeps_a_socket() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a.md");
        let _socket = std::os::unix::net::UnixListener::bind(&file).unwrap();
        let target = WriteTarget::new(file.clone(), PathBuf::from("a.md"));
        for own in [Some("first"), None] {
            assert_eq!(
                over_own(&target, own, "second"),
                Err("kept".to_owned()),
                "{own:?}"
            );
        }
        assert_eq!(
            entries(dir.path()),
            ["a.md"],
            "the socket is left, and no temporary file"
        );
    }

    /// A file the caller wrote at the target of [`write_over_own`] that cannot be read is
    /// reported with the read's cause (#160), never kept as a file changed since — the
    /// caller cannot tell — and left as it is, with no temporary file. Control: the same
    /// file, readable again, is replaced. Skipped, with a reason, where mode 0o200 does not
    /// stop a read (running as root).
    #[cfg(unix)]
    #[test]
    fn a_write_over_its_own_file_reports_a_file_it_cannot_read() {
        use std::os::unix::fs::PermissionsExt as _;

        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a.md");
        let target = WriteTarget::new(file.clone(), PathBuf::from("a.md"));
        let set_mode = |mode: u32| {
            std::fs::set_permissions(&file, std::fs::Permissions::from_mode(mode)).unwrap();
        };
        std::fs::write(&file, "first").unwrap();
        set_mode(0o200);
        let Err(denied) = std::fs::File::open(&file) else {
            crate::output::ewriteln!("running as root; mode 0o200 does not stop a read");
            return;
        };

        let failed = over_own(&target, Some("first"), "second");
        set_mode(0o644);
        assert_eq!(
            failed,
            Err(format!(
                "cannot write {}: {}",
                safe_path(&target.shown),
                io_cause(&denied)
            ))
        );
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "first", "left");
        assert_eq!(temp_residue(dir.path()), Vec::<String>::new());

        assert_eq!(over_own(&target, Some("first"), "second"), Ok(()));
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "second");
    }

    /// A directory gone since the caller wrote below it is no failure of
    /// [`write_over_own`] (#160): nothing is there, so the file is written as a new one,
    /// the directory made again where the caller makes its directories.
    #[test]
    fn a_write_over_its_own_file_in_a_directory_gone_since_makes_it_again() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("sub").join("a.md");
        let target = WriteTarget::below(dir.path(), Path::new("o"), Path::new("sub/a.md"));
        let written = |own: Option<&str>| {
            write_over_own(
                &target,
                own,
                "second",
                Durability::RenameOnly,
                Parents::Create,
            )
            .map_err(|not_written| match not_written {
                NotCreated::Exists => "kept".to_owned(),
                NotCreated::Failed(e) => e.to_string(),
            })
        };
        assert_eq!(written(None), Ok(()), "control: made where nothing is");
        std::fs::remove_dir_all(dir.path().join("sub")).unwrap();

        assert_eq!(written(Some("second")), Ok(()));
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "second");
    }

    // ── Never over an MDS module (#425) ─────────────────────────────────────────

    /// An output is never written over an MDS module (#425): a `.md` file that declares
    /// `type: mds` — bare, quoted, or with CRLF lines, and named with its extension in
    /// another case, which on a case-insensitive volume is a `.md` file's name — and any
    /// `.mds` file, whatever it holds and in either case, are refused, named as shown, and
    /// left as they are, with no temporary file. Controls: a `.md` file with no
    /// frontmatter, one that declares another `type`, one with `type: mds` below another
    /// key only, another kind of file, and names nothing has are each written.
    #[test]
    fn an_output_is_never_written_over_an_mds_module() {
        let dir = tempfile::tempdir().unwrap();
        let shown = |name: &str| PathBuf::from("out").join(name);
        let write = |name: &str| {
            write_compiled(
                &WriteTarget::new(dir.path().join(name), shown(name)),
                "X",
                &Inputs::default(),
            )
            .map_err(|e| e.to_string())
        };
        let text = |name: &str| std::fs::read_to_string(dir.path().join(name)).unwrap();
        for (name, module) in [
            ("m.md", "---\ntype: mds\n---\nM\n"),
            ("q.md", "---\ntype: \"mds\"\n---\nQ\n"),
            ("crlf.md", "---\r\ntype: 'mds'\r\n---\r\nC\r\n"),
            ("UP.MD", "---\ntype: mds\n---\nU\n"),
            ("mixed.Md", "---\ntype: mds\n---\nX\n"),
            ("source.mds", "---\ntype: mds\n---\nS\n"),
            ("plain.mds", "Hello\n"),
            ("UP.MDS", ""),
        ] {
            std::fs::write(dir.path().join(name), module).unwrap();
            assert_eq!(
                write(name),
                Err(format!(
                    "cannot write {}: {MODULE_REFUSED}",
                    shown(name).display()
                )),
                "{name}"
            );
            assert_eq!(text(name), module, "{name} is left as it is");
        }
        assert_eq!(
            temp_residue(dir.path()),
            Vec::<String>::new(),
            "no temporary file"
        );
        for (name, other) in [
            ("plain.md", Some("plain\n")),
            ("other.md", Some("---\ntype: other\n---\nO\n")),
            ("nested.md", Some("---\nconfig:\n  type: mds\n---\nN\n")),
            ("notes.txt", Some("---\ntype: mds\n---\nT\n")),
            ("new.md", None),
            ("new.mds", None),
        ] {
            if let Some(other) = other {
                std::fs::write(dir.path().join(name), other).unwrap();
            }
            assert_eq!(write(name), Ok(()), "control: {name} is written");
            assert_eq!(text(name), "X", "control: {name}");
        }
    }

    /// An output that is itself an MDS module — its frontmatter declares `type: mds`, as
    /// mds-core judges a `.md` file's — may replace one (#425): a template that generates
    /// a module rewrites it, and a module written by hand at its output is replaced too.
    /// It is still never written over a file the run reads, module or not. Controls: an
    /// output that is no module is refused over the same module, and one that declares
    /// `type: mds` only below another key is no module either.
    #[test]
    fn a_module_is_replaced_only_by_output_that_is_itself_a_module() {
        const GENERATED: &str = "---\ntype: mds\n---\nGenerated\n";
        let dir = tempfile::tempdir().unwrap();
        let path = |name: &str| dir.path().join(name);
        let write = |name: &str, content: &str, inputs: &Inputs| {
            write_compiled(
                &WriteTarget::new(path(name), PathBuf::from(name)),
                content,
                inputs,
            )
            .map_err(|e| e.to_string())
        };
        let text = |name: &str| std::fs::read_to_string(path(name)).unwrap();
        let module = "---\ntype: mds\n---\nM\n";
        std::fs::write(path("m.md"), module).unwrap();

        assert_eq!(
            write("m.md", "plain\n", &Inputs::default()),
            Err(format!("cannot write m.md: {MODULE_REFUSED}")),
            "control: an output that is no module"
        );
        assert_eq!(
            write(
                "m.md",
                "---\nconfig:\n  type: mds\n---\nN\n",
                &Inputs::default()
            ),
            Err(format!("cannot write m.md: {MODULE_REFUSED}")),
            "control: type: mds below another key is no module"
        );
        assert_eq!(text("m.md"), module, "left as it is");

        assert_eq!(write("m.md", GENERATED, &Inputs::default()), Ok(()));
        assert_eq!(text("m.md"), GENERATED, "a module replaces a module");
        std::fs::write(path("lib.mds"), "Hello\n").unwrap();
        assert_eq!(
            write("lib.mds", "plain\n", &Inputs::default()),
            Err(format!("cannot write lib.mds: {MODULE_REFUSED}")),
            "control: an output that is no module, over a .mds file"
        );
        assert_eq!(write("lib.mds", GENERATED, &Inputs::default()), Ok(()));
        assert_eq!(text("lib.mds"), GENERATED, "a module replaces a .mds file");
        let crlf = "---\r\ntype: 'mds'\r\n---\r\nAgain\r\n";
        assert_eq!(write("m.md", crlf, &Inputs::default()), Ok(()));
        assert_eq!(text("m.md"), crlf, "and its own output again");

        assert_eq!(
            write("m.md", GENERATED, &Inputs::new([path("m.md")])),
            Err(format!("cannot write m.md: {INPUT_REFUSAL}")),
            "never over a file the run reads"
        );
        assert_eq!(text("m.md"), crlf, "the input is left as it is");
        assert_eq!(
            temp_residue(dir.path()),
            Vec::<String>::new(),
            "no temporary file"
        );
    }

    /// The module check reads the file in the directory the write opened, never by path
    /// (#425): while a thread points the symlinked anchor `cur` at a directory holding a
    /// module, then at one holding a plain file, and back, at most 2,000 writes in at most
    /// 10 s never replace the module — each lands in the plain file's directory or is
    /// refused. Controls: the loop met both — some writes landed, some were refused.
    #[cfg(unix)]
    #[test]
    fn a_module_is_judged_in_the_directory_the_write_opened() {
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::Arc;
        use std::time::{Duration, Instant};

        /// How long each state is held: about as long as a write takes.
        const HOLD: Duration = Duration::from_micros(200);
        const MODULE: &str = "---\ntype: mds\n---\nM\n";

        let dir = tempfile::tempdir().unwrap();
        let (with_module, plain) = (dir.path().join("with-module"), dir.path().join("plain"));
        std::fs::create_dir(&with_module).unwrap();
        std::fs::create_dir(&plain).unwrap();
        std::fs::write(with_module.join("a.md"), MODULE).unwrap();
        std::fs::write(plain.join("a.md"), "plain\n").unwrap();
        let cur = dir.path().join("cur");
        std::os::unix::fs::symlink(&with_module, &cur).unwrap();
        let target = WriteTarget::below(&cur, Path::new("cur"), Path::new("a.md"));

        let stop = Arc::new(AtomicBool::new(false));
        let swapper = {
            let stop = Arc::clone(&stop);
            let (base, with_module, plain) =
                (dir.path().to_path_buf(), with_module.clone(), plain.clone());
            std::thread::spawn(move || {
                // Bounded: at most 100,000 swaps, and the loop ends with the writes. Each
                // swap renames a new link over `cur`, so `cur` always leads somewhere.
                for i in 0..100_000u32 {
                    if stop.load(Ordering::Relaxed) {
                        break;
                    }
                    let next = if i % 2 == 0 { &plain } else { &with_module };
                    let link = base.join(format!("link-{i}"));
                    let _ = std::os::unix::fs::symlink(next, &link);
                    let _ = std::fs::rename(&link, base.join("cur"));
                    std::thread::sleep(HOLD);
                }
            })
        };

        let started = Instant::now();
        let (mut written, mut refused) = (0u32, 0u32);
        // Bounded: 2,000 writes or 10 s, whichever comes first.
        for _ in 0..2_000 {
            if started.elapsed() > Duration::from_secs(10) {
                break;
            }
            match write_compiled(&target, "X", &Inputs::default()) {
                Ok(()) => written += 1,
                Err(e) if e.to_string().contains(MODULE_REFUSAL) => refused += 1,
                Err(_) => {}
            }
        }
        stop.store(true, Ordering::Relaxed);
        swapper.join().unwrap();

        assert_eq!(
            std::fs::read_to_string(with_module.join("a.md")).unwrap(),
            MODULE,
            "the module is never replaced ({written} written, {refused} refused)"
        );
        assert!(
            written > 0 && refused > 0,
            "the loop met both directories: {written} written, {refused} refused"
        );
    }

    /// An output is never written over a file the run reads (#425): `vars.json`, one of
    /// the inputs, is refused, named as shown, and left as it is, with no temporary file.
    /// Controls: the same write with no inputs writes it, and a file that is no input is
    /// written.
    #[test]
    fn an_output_is_never_written_over_a_file_the_run_reads() {
        let dir = tempfile::tempdir().unwrap();
        let (vars, other) = (dir.path().join("vars.json"), dir.path().join("other.json"));
        std::fs::write(&vars, "{}\n").unwrap();
        std::fs::write(&other, "{}\n").unwrap();
        let inputs = Inputs::new([vars.clone()]);
        let write = |path: &Path, inputs: &Inputs| {
            write_compiled(
                &WriteTarget::new(path.to_path_buf(), PathBuf::from("out/x.json")),
                "X",
                inputs,
            )
            .map_err(|e| e.to_string())
        };

        assert_eq!(
            write(&vars, &inputs),
            Err(format!(
                "cannot write {}: {INPUT_REFUSAL}",
                Path::new("out/x.json").display()
            ))
        );
        assert_eq!(
            std::fs::read_to_string(&vars).unwrap(),
            "{}\n",
            "left as it is"
        );
        assert_eq!(
            temp_residue(dir.path()),
            Vec::<String>::new(),
            "no temporary file"
        );
        assert_eq!(
            write(&other, &inputs),
            Ok(()),
            "control: no input is written"
        );
        assert_eq!(
            write(&vars, &Inputs::default()),
            Ok(()),
            "control: no inputs"
        );
        assert_eq!(std::fs::read_to_string(&vars).unwrap(), "X");
    }

    /// An input found from a path rather than named — the `mds.json` nearest a directory
    /// run's source (#425) — is searched for only by a write that meets a file at its
    /// target, and a file found there is refused as any input is, and left as it is. A new
    /// file is written without the search: nothing is there to replace. Control: a file at
    /// the target that is no input is searched for once, and written over.
    #[test]
    fn an_input_found_from_a_path_is_searched_for_only_when_a_file_is_at_the_target() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        static SEARCHES: AtomicUsize = AtomicUsize::new(0);
        fn beside(from: &Path) -> Option<PathBuf> {
            SEARCHES.fetch_add(1, Ordering::SeqCst);
            Some(from.with_file_name("mds.json"))
        }
        let dir = tempfile::tempdir().unwrap();
        let path = |name: &str| dir.path().join(name);
        let inputs = Inputs::default().and_found_from(&path("page.mds"), beside);
        let write = |name: &str| {
            write_compiled(
                &WriteTarget::new(path(name), PathBuf::from(name)),
                "X",
                &inputs,
            )
            .map_err(|e| e.to_string())
        };
        let searches = || SEARCHES.load(Ordering::SeqCst);

        assert_eq!(write("page.md"), Ok(()));
        assert_eq!(searches(), 0, "a new file is written without the search");
        assert_eq!(
            write("page.md"),
            Ok(()),
            "control: no input is written over"
        );
        assert_eq!(
            searches(),
            1,
            "control: a file at the target is searched for"
        );
        std::fs::write(path("mds.json"), "{}\n").unwrap();
        assert_eq!(
            write("mds.json"),
            Err(format!("cannot write mds.json: {INPUT_REFUSAL}"))
        );
        assert_eq!(searches(), 2);
        assert_eq!(
            std::fs::read_to_string(path("mds.json")).unwrap(),
            "{}\n",
            "left as it is"
        );
    }

    /// A compiled output's write looks at a file beside it, in the directory it went in
    /// (#160): nothing there is [`Beside::Nothing`]; a file, a directory and, on unix, a
    /// dangling symlink there are [`Beside::Something`], each left as it is. A file named
    /// in another directory is not looked at, and is something. The output is written in
    /// every case.
    #[test]
    fn a_compiled_output_s_write_looks_at_the_file_beside_it() {
        let dir = tempfile::tempdir().unwrap();
        let path = |name: &str| dir.path().join(name);
        let target = WriteTarget::new(path("a.md"), PathBuf::from("a.md"));
        let look = |beside: &WriteTarget| {
            write_compiled_and_look(&target, "X", &Inputs::default(), beside)
                .map_err(|e| e.to_string())
        };
        let named = |name: &str| target.sibling(|file| file.with_file_name(name));

        assert_eq!(look(&named("a.json")), Ok(Beside::Nothing), "nothing there");
        std::fs::write(path("a.json"), "[]\n").unwrap();
        assert_eq!(look(&named("a.json")), Ok(Beside::Something), "a file");
        assert_eq!(
            std::fs::read_to_string(path("a.json")).unwrap(),
            "[]\n",
            "left as it is"
        );
        std::fs::create_dir(path("d.json")).unwrap();
        assert_eq!(look(&named("d.json")), Ok(Beside::Something), "a directory");
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(path("gone"), path("l.json")).unwrap();
            assert_eq!(
                look(&named("l.json")),
                Ok(Beside::Something),
                "a dangling symlink"
            );
        }
        std::fs::create_dir(path("sub")).unwrap();
        std::fs::write(path("sub").join("e.json"), "[]\n").unwrap();
        let elsewhere = WriteTarget::new(path("sub").join("e.json"), PathBuf::from("e.json"));
        assert_eq!(
            look(&elsewhere),
            Ok(Beside::Something),
            "another directory is not looked at"
        );
        assert_eq!(std::fs::read_to_string(path("a.md")).unwrap(), "X");
    }

    /// On unix an input is told by its device and inode (#425): a hard link to it is that
    /// file and is refused, and so is the file an input named through a symlink leads to.
    /// Control: a copy of it, another file with the same bytes, is written.
    #[cfg(unix)]
    #[test]
    fn an_input_is_the_file_its_path_leads_to_now() {
        let dir = tempfile::tempdir().unwrap();
        let path = |name: &str| dir.path().join(name);
        std::fs::write(path("vars.json"), "{}\n").unwrap();
        std::fs::hard_link(path("vars.json"), path("linked.json")).unwrap();
        std::os::unix::fs::symlink(path("vars.json"), path("via.json")).unwrap();
        std::fs::write(path("copy.json"), "{}\n").unwrap();
        let write = |name: &str, inputs: &Inputs| {
            write_compiled(
                &WriteTarget::new(path(name), PathBuf::from(name)),
                "X",
                inputs,
            )
            .map_err(|e| e.to_string())
        };

        let refused = |name: &str| Err(format!("cannot write {name}: {INPUT_REFUSAL}"));
        assert_eq!(
            write("linked.json", &Inputs::new([path("vars.json")])),
            refused("linked.json")
        );
        assert_eq!(
            write("vars.json", &Inputs::new([path("via.json")])),
            refused("vars.json")
        );
        assert_eq!(std::fs::read_to_string(path("vars.json")).unwrap(), "{}\n");
        assert_eq!(
            write("copy.json", &Inputs::new([path("vars.json")])),
            Ok(()),
            "control: a copy is another file"
        );
    }

    /// A `.md` file at an output's target that cannot be read is refused (#425): nothing
    /// tells it is no MDS module. `locked.md`, at mode 0o000, is refused, named as shown,
    /// with the read's cause, and left as it is, with no temporary file. Controls: the same
    /// file, readable again, is written; and `locked.json` at mode 0o000 — a name no
    /// module has, so the write never opens it — is written. `locked.mds` at mode 0o000 is
    /// refused as a module, by its name, without a read. Skipped, with a reason, where mode
    /// 0o000 does not stop a read (running as root).
    #[cfg(unix)]
    #[test]
    fn an_output_is_never_written_over_a_markdown_file_it_cannot_read() {
        use std::os::unix::fs::PermissionsExt as _;

        let dir = tempfile::tempdir().unwrap();
        let path = |name: &str| dir.path().join(name);
        let shown = |name: &str| PathBuf::from("out").join(name);
        let write = |name: &str| {
            write_compiled(
                &WriteTarget::new(path(name), shown(name)),
                "X",
                &Inputs::default(),
            )
            .map_err(|e| e.to_string())
        };
        let set_mode = |name: &str, mode: u32| {
            std::fs::set_permissions(path(name), std::fs::Permissions::from_mode(mode)).unwrap();
        };
        std::fs::write(path("locked.md"), "notes\n").unwrap();
        std::fs::write(path("locked.json"), "{}\n").unwrap();
        set_mode("locked.md", 0o000);
        set_mode("locked.json", 0o000);
        let Err(denied) = std::fs::File::open(path("locked.md")) else {
            crate::output::ewriteln!("running as root; mode 0o000 does not stop a read");
            return;
        };

        let refused = write("locked.md");
        set_mode("locked.md", 0o644);
        assert_eq!(
            refused,
            Err(format!(
                "cannot write {}: {MODULE_UNKNOWN}: {}",
                shown("locked.md").display(),
                io_cause(&denied)
            ))
        );
        assert_eq!(
            std::fs::read_to_string(path("locked.md")).unwrap(),
            "notes\n",
            "left as it is"
        );
        assert_eq!(
            temp_residue(dir.path()),
            Vec::<String>::new(),
            "no temporary file"
        );

        assert_eq!(
            write("locked.md"),
            Ok(()),
            "control: readable, it is written"
        );
        assert_eq!(std::fs::read_to_string(path("locked.md")).unwrap(), "X");
        assert_eq!(
            write("locked.json"),
            Ok(()),
            "control: a .json file is never opened"
        );
        set_mode("locked.json", 0o644);
        assert_eq!(std::fs::read_to_string(path("locked.json")).unwrap(), "X");

        // A `.mds` file is a module by its name alone: refused as one, never read.
        std::fs::write(path("locked.mds"), "Hello\n").unwrap();
        set_mode("locked.mds", 0o000);
        let refused = write("locked.mds");
        set_mode("locked.mds", 0o644);
        assert_eq!(
            refused,
            Err(format!(
                "cannot write {}: {MODULE_REFUSED}",
                shown("locked.mds").display()
            )),
            "a .mds file is never read to tell"
        );
        assert_eq!(
            std::fs::read_to_string(path("locked.mds")).unwrap(),
            "Hello\n"
        );
    }

    /// A name is judged as Windows opens it (#425): less the dots and spaces it ends in,
    /// which Windows drops from a path's last component, so `lib.md.` and `lib.md ` are
    /// `lib.md` — in bytes and in UTF-16 units alike. Controls: a name that ends in neither
    /// is kept as it is, a dot or space inside it is kept, and a name of nothing but dots
    /// and spaces is kept whole.
    #[test]
    fn a_name_is_judged_without_the_dots_and_spaces_windows_drops() {
        let trimmed = |name: &str| as_windows_opens(name.as_bytes()).to_vec();
        for (name, opens) in [
            ("lib.md.", "lib.md"),
            ("lib.md ", "lib.md"),
            ("lib.md. .", "lib.md"),
            ("lib.mds...", "lib.mds"),
            ("lib.md", "lib.md"),
            ("a. b.md", "a. b.md"),
            ("...", "..."),
            (". ", ". "),
            ("", ""),
        ] {
            assert_eq!(trimmed(name), opens.as_bytes(), "{name:?}");
        }
        let wide: Vec<u16> = "lib.md .".encode_utf16().collect();
        let expected: Vec<u16> = "lib.md".encode_utf16().collect();
        assert_eq!(as_windows_opens(&wide), expected.as_slice(), "UTF-16");
    }

    /// The module check reads an existing output no further than the end of its
    /// frontmatter, at most one read past it (#425): a `.md` file with frontmatter and a
    /// 1 MiB body — whether it declares `type: mds` or not, with the close met inside a
    /// read, across two reads, or after a frontmatter longer than one read — is judged
    /// as mds-core judges it, and the body is left unread. A fence that never closes is
    /// read no further than the cap and is no module. Control: a file with no fence is
    /// read for the fence alone.
    #[test]
    fn the_module_check_reads_no_further_than_the_frontmatter() {
        use std::io::Seek as _;
        const ONE_READ: usize = 8 * 1024;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out.md");
        let check = |text: &str| -> (bool, usize) {
            std::fs::write(&path, text).unwrap();
            let mut file = std::fs::File::open(&path).unwrap();
            let module = is_mds_module(&mut file).unwrap();
            let read = usize::try_from(file.stream_position().unwrap()).unwrap();
            (module, read)
        };
        let body = "b\n".repeat(512 * 1024);
        let straddle = format!("---\ntype: mds\n{}", "a".repeat(8181));
        for (label, frontmatter, module) in [
            ("no type", "---\ntitle: t\n---\n".to_owned(), false),
            ("a module", "---\ntype: mds\n---\n".to_owned(), true),
            ("CRLF", "---\r\ntype: mds\r\n---\r\n".to_owned(), true),
            ("across two reads", format!("{straddle}\n---\n"), true),
            (
                "longer than one read",
                format!("---\n{}type: mds\n---\n", "k: v\n".repeat(5000)),
                true,
            ),
        ] {
            let (judged, read) = check(&format!("{frontmatter}{body}"));
            assert_eq!(judged, module, "{label}");
            assert!(
                read <= frontmatter.len() + ONE_READ,
                "{label}: read {read} bytes of a {}-byte frontmatter",
                frontmatter.len()
            );
        }

        let cap = usize::try_from(mds::MAX_FILE_SIZE).unwrap();
        let (judged, read) = check(&format!("---\ntype: mds\n{}", "u".repeat(cap + 1024)));
        assert!(!judged, "a fence that never closes is no module");
        assert!(read <= cap, "read {read} bytes, past the cap");

        let (judged, read) = check(&format!("plain\n{body}"));
        assert!(!judged, "control");
        assert!(read <= 5, "control: read {read} bytes");
    }

    /// On Windows an output's target is judged as the file it opens (#425): `m.md.` and
    /// `m.md ` write `m.md`, a module, and are refused, named as typed, and `lib.mds.` is
    /// the source `lib.mds`, refused too; each is left as it is. Control: `plain.md.` writes
    /// `plain.md`, which is no module.
    #[cfg(windows)]
    #[test]
    fn on_windows_a_name_ending_in_dots_or_spaces_is_judged_as_the_file_it_opens() {
        let dir = tempfile::tempdir().unwrap();
        let path = |name: &str| dir.path().join(name);
        let write = |name: &str| {
            write_compiled(
                &WriteTarget::new(path(name), PathBuf::from(name)),
                "X",
                &Inputs::default(),
            )
            .map_err(|e| e.to_string())
        };
        let module = "---\ntype: mds\n---\nM\n";
        std::fs::write(path("m.md"), module).unwrap();
        std::fs::write(path("lib.mds"), "Hello\n").unwrap();
        std::fs::write(path("plain.md"), "notes\n").unwrap();
        for name in ["m.md.", "m.md ", "lib.mds."] {
            assert_eq!(
                write(name),
                Err(format!("cannot write {name}: {MODULE_REFUSED}")),
                "{name:?}"
            );
        }
        assert_eq!(std::fs::read_to_string(path("m.md")).unwrap(), module);
        assert_eq!(std::fs::read_to_string(path("lib.mds")).unwrap(), "Hello\n");
        assert_eq!(write("plain.md."), Ok(()), "control");
        assert_eq!(std::fs::read_to_string(path("plain.md")).unwrap(), "X");
    }

    /// On Windows a file another program holds open is still replaced (#160): an output
    /// ([`write_compiled`]) and then a rewrite ([`replace_if_unchanged`]) each land over a
    /// target held open as std opens a file — shared for read, write and delete, as an
    /// editor, a viewer or a test's reads hold one — and a fresh read by path finds the
    /// new bytes, with no temporary file left. Control: tempfile's `persist`, a
    /// `MoveFileExW` alone, fails over the same held target with `ERROR_ACCESS_DENIED`
    /// (os error 5), the failure `mds watch` met while a reader held its output open. Were
    /// that move to succeed, the hazard is not the one this test names, and the test
    /// fails to say so.
    #[cfg(windows)]
    #[test]
    fn on_windows_a_file_another_program_holds_open_is_still_replaced() {
        use std::io::Write as _;

        const ERROR_ACCESS_DENIED: i32 = 5;
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("out.md");
        std::fs::write(&file, "old\n").unwrap();
        let held = std::fs::File::open(&file).unwrap();

        let mut control = tempfile::NamedTempFile::new_in(dir.path()).unwrap();
        control.write_all(b"control\n").unwrap();
        let refused = control
            .persist(&file)
            .expect_err("control: persist over a file held open must fail");
        assert_eq!(
            refused.error.raw_os_error(),
            Some(ERROR_ACCESS_DENIED),
            "control: {}",
            refused.error
        );
        drop(refused);
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "old\n", "control");

        let target = WriteTarget::new(file.clone(), PathBuf::from("out.md"));
        assert_eq!(
            write_compiled(&target, "output\n", &Inputs::default()).map_err(|e| e.to_string()),
            Ok(()),
            "an output"
        );
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "output\n");

        // The file the output's rename put there, held open in its turn.
        let held_again = std::fs::File::open(&file).unwrap();
        let read = read_stamped(&target, "output\n").unwrap();
        assert!(
            matches!(
                replace_if_unchanged(read, "rewrite\n", Durability::Fsync),
                Ok(Rewritten::Done)
            ),
            "a rewrite"
        );
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "rewrite\n");
        assert_eq!(temp_residue(dir.path()), Vec::<String>::new());
        drop((held, held_again));
    }

    /// Each step of a new file's commit puts the file where nothing is, and never over a
    /// file that is there (#160): the rename that never replaces; a hard link, once each
    /// answer saying that rename is not to be had is given; and the content written in
    /// place into a file created exclusively, once each answer saying hard links are not
    /// to be had either is given too. With the name taken, each step refuses, the file
    /// there keeps its bytes, and no temporary file is left. A step that fails otherwise
    /// fails the write, and no later step is taken.
    #[cfg(unix)]
    #[test]
    fn each_step_of_a_new_file_s_commit_never_replaces_a_file() {
        use std::cell::RefCell;
        use std::ffi::OsString;
        use std::io::Write as _;
        use std::os::fd::{AsFd as _, BorrowedFd};

        use rustix::fs::{Mode, OFlags};
        use rustix::io::Errno;

        use super::unix::{commit_new, create_temp, NewSteps, NO_CLOBBER};

        /// What a commit of `new` to `a.mds` came to: its outcome, the steps it took, the
        /// bytes of `a.mds` — `there` when it was taken first — and the names left.
        #[derive(Debug, PartialEq, Eq)]
        struct Outcome {
            result: Result<(), String>,
            steps: Vec<&'static str>,
            file: Option<String>,
            names: Vec<String>,
        }

        // `rename` and `link`: the answer each step gives in place of its own, if any.
        let commit = |rename: Option<Errno>, link: Option<Errno>, taken: bool| {
            let dir = tempfile::tempdir().unwrap();
            let file = dir.path().join("a.mds");
            if taken {
                std::fs::write(&file, "there").unwrap();
            }
            let fd = rustix::fs::open(
                dir.path(),
                OFlags::RDONLY | OFlags::DIRECTORY,
                Mode::empty(),
            )
            .unwrap();
            let taken_steps = RefCell::new(Vec::new());
            let forced_rename = |d: BorrowedFd<'_>, from: &OsStr, to: &OsStr| {
                taken_steps.borrow_mut().push("rename");
                rename.map_or_else(|| (NO_CLOBBER.rename)(d, from, to), Err)
            };
            let forced_link = |d: BorrowedFd<'_>, from: &OsStr, to: &OsStr| {
                taken_steps.borrow_mut().push("link");
                link.map_or_else(|| (NO_CLOBBER.link)(d, from, to), Err)
            };
            let steps = NewSteps {
                rename: &forced_rename,
                link: &forced_link,
                fill: NO_CLOBBER.fill,
            };
            let temp_name = OsString::from(format!("{TEMP_PREFIX}step{TEMP_SUFFIX}"));
            let (temp, mut written) =
                create_temp(fd.as_fd(), Mode::from_raw_mode(0o644), [temp_name]).unwrap();
            written.write_all(b"new").unwrap();
            drop(written);
            let result = commit_new(
                temp,
                OsStr::new("a.mds"),
                b"new",
                Durability::RenameOnly,
                &steps,
            )
            .map_err(|failure| match failure {
                Failure::Exists => "exists".to_owned(),
                Failure::Io(e) => format!("{:?}", Errno::from_io_error(&e)),
                other => format!("{other:?}"),
            });
            Outcome {
                result,
                steps: taken_steps.into_inner(),
                file: std::fs::read_to_string(&file).ok(),
                names: entries(dir.path()),
            }
        };
        let landed = |steps: &[&'static str]| Outcome {
            result: Ok(()),
            steps: steps.to_vec(),
            file: Some("new".to_owned()),
            names: vec!["a.mds".to_owned()],
        };
        let refused = |steps: &[&'static str]| Outcome {
            result: Err("exists".to_owned()),
            steps: steps.to_vec(),
            file: Some("there".to_owned()),
            names: vec!["a.mds".to_owned()],
        };

        assert_eq!(commit(None, None, false), landed(&["rename"]), "renamed");
        assert_eq!(
            commit(None, None, true),
            refused(&["rename"]),
            "rename refused"
        );
        for no_rename in [Errno::INVAL, Errno::NOSYS, Errno::NOTSUP, Errno::OPNOTSUPP] {
            let both = ["rename", "link"];
            assert_eq!(
                commit(Some(no_rename), None, false),
                landed(&both),
                "{no_rename:?}: linked"
            );
            assert_eq!(
                commit(Some(no_rename), None, true),
                refused(&both),
                "{no_rename:?}: link refused"
            );
        }
        for no_link in [
            Errno::PERM,
            Errno::NOSYS,
            Errno::NOTSUP,
            Errno::OPNOTSUPP,
            Errno::MLINK,
        ] {
            let both = ["rename", "link"];
            assert_eq!(
                commit(Some(Errno::INVAL), Some(no_link), false),
                landed(&both),
                "{no_link:?}: written in place"
            );
            assert_eq!(
                commit(Some(Errno::INVAL), Some(no_link), true),
                refused(&both),
                "{no_link:?}: written in place refused"
            );
        }

        let failed = |steps: &[&'static str]| Outcome {
            result: Err(format!("{:?}", Some(Errno::IO))),
            steps: steps.to_vec(),
            file: None,
            names: Vec::new(),
        };
        assert_eq!(
            commit(Some(Errno::IO), None, false),
            failed(&["rename"]),
            "a failed rename is no reason to link"
        );
        assert_eq!(
            commit(Some(Errno::INVAL), Some(Errno::IO), false),
            failed(&["rename", "link"]),
            "a failed link is no reason to write in place"
        );
    }

    /// A new file's commit that writes its content in place — no rename that never
    /// replaces, no hard links — and fails part-way removes the file it created again
    /// (#160): left partly written, `mds watch` would keep it as a file it did not write
    /// for the rest of the session. The write's own failure is reported, and no temporary
    /// file is left. A file put at the name before that removal is left as it is: only the
    /// file the write created is removed. Control: the same commit, its content written
    /// whole, leaves the file.
    #[cfg(unix)]
    #[test]
    fn a_new_file_written_in_place_that_fails_part_way_is_removed_again() {
        use std::ffi::OsString;
        use std::fs::File;
        use std::io::Write as _;
        use std::os::fd::{AsFd as _, BorrowedFd};

        use rustix::fs::{Mode, OFlags};
        use rustix::io::Errno;

        use super::unix::{commit_new, create_temp, Fill, NewSteps, NO_CLOBBER};

        const CONTENT: &[u8] = b"new content";
        // What a commit of `CONTENT` to `a.mds` in `dir`, written in place by `fill`, came
        // to: its outcome, and each name left with its bytes.
        let in_place = |dir: &Path, fill: Fill<'_>| {
            let fd =
                rustix::fs::open(dir, OFlags::RDONLY | OFlags::DIRECTORY, Mode::empty()).unwrap();
            let no_rename = |_: BorrowedFd<'_>, _: &OsStr, _: &OsStr| Err(Errno::INVAL);
            let no_link = |_: BorrowedFd<'_>, _: &OsStr, _: &OsStr| Err(Errno::PERM);
            let steps = NewSteps {
                rename: &no_rename,
                link: &no_link,
                fill,
            };
            let temp_name = OsString::from(format!("{TEMP_PREFIX}step{TEMP_SUFFIX}"));
            let (temp, mut written) =
                create_temp(fd.as_fd(), Mode::from_raw_mode(0o644), [temp_name]).unwrap();
            written.write_all(CONTENT).unwrap();
            drop(written);
            let result = commit_new(
                temp,
                OsStr::new("a.mds"),
                CONTENT,
                Durability::RenameOnly,
                &steps,
            )
            .map_err(|failure| match failure {
                Failure::Io(e) => format!("{:?}", Errno::from_io_error(&e)),
                other => format!("{other:?}"),
            });
            let left: Vec<(String, String)> = entries(dir)
                .into_iter()
                .map(|name| {
                    let text = std::fs::read_to_string(dir.join(&name)).unwrap();
                    (name, text)
                })
                .collect();
            (result, left)
        };
        let no_space = format!("{:?}", Some(Errno::NOSPC));

        let dir = tempfile::tempdir().unwrap();
        assert_eq!(
            in_place(dir.path(), NO_CLOBBER.fill),
            (Ok(()), vec![("a.mds".to_owned(), "new content".to_owned())]),
            "control: written whole"
        );

        let dir = tempfile::tempdir().unwrap();
        let part_way = |mut file: File, content: &[u8], _: Durability| {
            file.write_all(&content[..3])?;
            Err(Errno::NOSPC.into())
        };
        assert_eq!(
            in_place(dir.path(), &part_way),
            (Err(no_space.clone()), Vec::new()),
            "removed again"
        );

        let dir = tempfile::tempdir().unwrap();
        let theirs = dir.path().join("theirs");
        let replaced_meanwhile = |mut file: File, content: &[u8], _: Durability| {
            file.write_all(&content[..3])?;
            std::fs::write(&theirs, "theirs")?;
            std::fs::rename(&theirs, dir.path().join("a.mds"))?;
            Err(Errno::NOSPC.into())
        };
        assert_eq!(
            in_place(dir.path(), &replaced_meanwhile),
            (
                Err(no_space),
                vec![("a.mds".to_owned(), "theirs".to_owned())]
            ),
            "a file put at the name since is left"
        );
    }

    // ── A removal ────────────────────────────────────────────────────────────────

    /// The file `rel` below the anchor `anchor`, named below `o`.
    fn to_remove(anchor: &Path, rel: &str) -> WriteTarget {
        WriteTarget::below(anchor, Path::new("o"), Path::new(rel))
    }

    /// A file its proof does not accept is kept, and the proof is given the file to be
    /// removed to read; a file its proof cannot read is kept too, as unreadable (#160).
    /// Control: the same file, its proof accepting it, is removed.
    #[test]
    fn a_file_its_proof_does_not_accept_is_kept() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("x.json");
        std::fs::write(&file, "stale").unwrap();
        let target = to_remove(dir.path(), "x.json");

        let mut read = String::new();
        let kept = remove_proven(&target, |opened| {
            std::io::Read::read_to_string(opened, &mut read)?;
            Ok(false)
        });
        assert_eq!(kept, Ok(Removal::Kept));
        assert_eq!(read, "stale", "the proof reads the file to be removed");
        assert_eq!(
            std::fs::read_to_string(&file).unwrap(),
            "stale",
            "it is kept"
        );

        let unreadable = remove_proven(&target, |_| Err(std::io::ErrorKind::InvalidData.into()));
        assert!(
            matches!(unreadable, Err(NotRemoved::Unreadable(_))),
            "{unreadable:?}"
        );
        assert!(file.exists(), "a file its proof cannot read is kept");

        assert_eq!(remove_proven(&target, |_| Ok(true)), Ok(Removal::Removed));
        assert!(!file.exists(), "control: the file proven is removed");
    }

    /// A file that is not there — nor a directory on its way, nor one that is a file — is
    /// nothing to remove, and its proof is never asked (#160). Control: a file that is
    /// there is given to its proof.
    #[test]
    fn a_file_that_is_not_there_is_nothing_to_remove() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("file"), "x").unwrap();
        for rel in ["gone.json", "gone/x.json", "file/x.json"] {
            let removal = remove_proven(&to_remove(dir.path(), rel), |_| {
                panic!("{rel}: there is no file to prove")
            });
            assert_eq!(removal, Ok(Removal::Missing), "{rel}");
        }

        std::fs::write(dir.path().join("here.json"), "x").unwrap();
        let mut asked = false;
        let removal = remove_proven(&to_remove(dir.path(), "here.json"), |_| {
            asked = true;
            Ok(false)
        });
        assert_eq!(removal, Ok(Removal::Kept));
        assert!(asked, "control: the proof is asked of a file that is there");
    }

    /// A file whose name is too long for the file system is not there: no file can have
    /// it, so it is nothing to remove and the proof is never asked (#160) — on Windows, a
    /// name std reports as `InvalidFilename` too. Control: a name of the most bytes a
    /// name may have, of a file that is there, is removed.
    #[test]
    fn a_name_too_long_for_the_file_system_is_nothing_to_remove() {
        let dir = tempfile::tempdir().unwrap();
        let too_long = format!("{}.json", "x".repeat(300));
        let removal = remove_proven(&to_remove(dir.path(), &too_long), |_| {
            panic!("there is no file to prove")
        });
        assert_eq!(removal, Ok(Removal::Missing));

        let longest = format!("{}.json", "y".repeat(250));
        std::fs::write(dir.path().join(&longest), "x").unwrap();
        assert_eq!(
            remove_proven(&to_remove(dir.path(), &longest), |_| Ok(true)),
            Ok(Removal::Removed),
            "control"
        );
    }

    /// Only the file's own name is looked past: a directory on its way whose name is too
    /// long for the file system is an error, as any other failure to reach the file is
    /// (#160).
    #[cfg(unix)]
    #[test]
    fn a_directory_name_too_long_on_the_way_is_an_error() {
        let dir = tempfile::tempdir().unwrap();
        let rel = format!("{}/x.json", "d".repeat(300));
        let removal = remove_proven(&to_remove(dir.path(), &rel), |_| {
            panic!("there is no file to prove")
        });
        assert_eq!(
            removal,
            Err(NotRemoved::Failed(os_text(rustix::io::Errno::NAMETOOLONG)))
        );
    }

    /// A symlink below the anchor is never removed through, and one at the file — live or
    /// dangling — is never removed: each is refused, the directory by the path the user
    /// knows it by, and the file a link leads to is left (#160). Control: the same name
    /// below a real directory is removed.
    ///
    /// Runs on every platform, so the Windows removal's looks — at each directory below
    /// the anchor and at the file, by path — are held to it; the refusals wait on
    /// [`make_symlink`], and the refused directory is named in the platform's separator.
    #[test]
    fn a_removal_through_a_symlink_or_of_one_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let anchor = dir.path().join("out");
        let real = anchor.join("real");
        let victim = dir.path().join("victim");
        std::fs::create_dir_all(&real).unwrap();
        std::fs::create_dir(&victim).unwrap();
        std::fs::write(victim.join("x.json"), "victim").unwrap();
        let linked = make_symlink(&victim, &anchor.join("sub"))
            && make_symlink(&victim.join("x.json"), &real.join("live.json"))
            && make_symlink(&dir.path().join("nowhere"), &real.join("gone.json"));
        // The links left in `real`, which no removal here may take.
        let links: &[&str] = if linked {
            &["gone.json", "live.json"]
        } else {
            &[]
        };

        if linked {
            assert_eq!(
                remove_proven(&to_remove(&anchor, "sub/x.json"), |_| Ok(true)),
                Err(NotRemoved::Failed(format!(
                    "{FOLLOW_REFUSAL} at {}",
                    Path::new("o").join("sub").display()
                )))
            );
            for link in ["real/live.json", "real/gone.json"] {
                let removal = remove_proven(&to_remove(&anchor, link), |_| Ok(true));
                assert_eq!(removal, Err(NotRemoved::Link), "{link}");
                assert_eq!(
                    removal.unwrap_err().cause(),
                    SYMLINK_REMOVAL_REFUSAL,
                    "{link}"
                );
            }
            assert_eq!(
                std::fs::read_to_string(victim.join("x.json")).unwrap(),
                "victim",
                "nothing is removed through a symlink"
            );
            assert_eq!(entries(&real), links, "no symlink is removed");
        }

        std::fs::write(real.join("x.json"), "stale").unwrap();
        assert_eq!(
            remove_proven(&to_remove(&anchor, "real/x.json"), |_| Ok(true)),
            Ok(Removal::Removed)
        );
        assert_eq!(entries(&real), links, "control: the file is removed");
    }

    /// A FIFO or a directory at the name is no file to remove: refused as not a regular
    /// file, left as it is, and never given to a proof (#160). Control: a regular file
    /// beside them is removed.
    #[cfg(unix)]
    #[test]
    fn anything_but_a_regular_file_is_left() {
        let dir = tempfile::tempdir().unwrap();
        let made = std::process::Command::new("mkfifo")
            .arg(dir.path().join("x.json"))
            .status()
            .expect("mkfifo runs");
        assert!(made.success(), "mkfifo x.json");
        std::fs::create_dir(dir.path().join("x.md")).unwrap();
        for name in ["x.json", "x.md"] {
            let removal = remove_proven(&to_remove(dir.path(), name), |_| {
                panic!("{name}: not a file to prove")
            });
            assert_eq!(removal, Err(NotRemoved::NotAFile), "{name}");
        }
        assert_eq!(entries(dir.path()), ["x.json", "x.md"], "both are left");

        std::fs::write(dir.path().join("x.txt"), "stale").unwrap();
        assert_eq!(
            remove_proven(&to_remove(dir.path(), "x.txt"), |_| Ok(true)),
            Ok(Removal::Removed)
        );
        assert_eq!(
            entries(dir.path()),
            ["x.json", "x.md"],
            "control: the file is removed"
        );
    }

    /// A file put at the name after the one there was opened — between its proof and its
    /// removal — is not removed: the removal is refused, and the file put there is left
    /// (#160). Control: with nothing put there, the file proven is removed.
    ///
    /// Runs on every platform, so the Windows removal's second look — by path, at the
    /// file's size and times — is held to it.
    #[test]
    fn a_file_put_in_the_place_of_the_one_proven_is_not_removed() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("x.json");
        let other = dir.path().join("other.json");
        std::fs::write(&file, "proven").unwrap();
        std::fs::write(&other, "put there").unwrap();
        let target = to_remove(dir.path(), "x.json");

        let swapped = remove_proven(&target, |_| {
            // On Windows the file proven is still open here, shared for deletion as std
            // opens every file: the rename relies on std's fallback to a POSIX-semantics
            // rename to replace it. A rename that fails is the fixture's, not the removal's.
            std::fs::rename(&other, &file).expect("put another file at the name");
            Ok(true)
        });
        assert_eq!(
            swapped,
            Err(NotRemoved::Failed(CHANGED_WHILE_CHECKED.to_owned()))
        );
        assert_eq!(
            std::fs::read_to_string(&file).unwrap(),
            "put there",
            "the file put there is left"
        );

        assert_eq!(remove_proven(&target, |_| Ok(true)), Ok(Removal::Removed));
        assert!(!file.exists(), "control: the file proven is removed");
    }

    /// A file edited in place — the same file, written over — after its proof read it is
    /// not removed: the removal is refused, and the edit is left (#160). Control: the same
    /// proof, with no edit, removes the file.
    #[test]
    fn an_edit_made_in_place_after_the_proof_read_it_is_not_removed() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("x.json");
        let target = to_remove(dir.path(), "x.json");
        let read_then = |edit: Option<&'static str>| {
            let path = path.clone();
            move |file: &mut std::fs::File| {
                let mut read = String::new();
                std::io::Read::read_to_string(file, &mut read)?;
                if let Some(edit) = edit {
                    std::fs::write(&path, edit)?;
                }
                Ok(read == "mds bytes")
            }
        };

        std::fs::write(&path, "mds bytes").unwrap();
        let edited = remove_proven(&target, read_then(Some("the user's edit, longer")));
        assert_eq!(
            std::fs::read_to_string(&path).ok().as_deref(),
            Some("the user's edit, longer"),
            "the edit is left"
        );
        assert_eq!(
            edited,
            Err(NotRemoved::Failed(CHANGED_WHILE_CHECKED.to_owned()))
        );

        std::fs::write(&path, "mds bytes").unwrap();
        assert_eq!(
            remove_proven(&target, read_then(None)),
            Ok(Removal::Removed)
        );
        assert!(!path.exists(), "control: the file proven is removed");
    }

    /// A removal whose anchor is not the directory its caller checked is refused before
    /// anything below it is looked at, as a write there is (#160). Control: the directory
    /// checked, opened, has the file removed.
    ///
    /// `#[cfg(unix)]`: two directories made a moment apart are told apart by their inode
    /// there; Windows has their creation times alone, which can be equal.
    #[cfg(unix)]
    #[test]
    fn a_removal_whose_anchor_is_not_the_directory_checked_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("out");
        let other = dir.path().join("other");
        std::fs::create_dir_all(out.join("sub")).unwrap();
        std::fs::create_dir(&other).unwrap();
        let file = out.join("sub/x.json");
        std::fs::write(&file, "stale").unwrap();
        let identity = |of: &Path| DirIdentity::of(of).expect("a directory");
        let target = to_remove(&out, "sub/x.json");

        let swapped = target.below_checked_anchor(&out, 0, identity(&other));
        assert_eq!(
            remove_proven(&swapped, |_| Ok(true)),
            Err(NotRemoved::out_dir_moved())
        );
        assert!(file.exists(), "nothing is removed below it");

        let checked = target.below_checked_anchor(&out, 0, identity(&out));
        assert_eq!(remove_proven(&checked, |_| Ok(true)), Ok(Removal::Removed));
        assert!(!file.exists(), "control: the file is removed");
    }

    // ── The temporary file ───────────────────────────────────────────────────────

    /// A temporary name is tried at most [`MAX_TEMP_ATTEMPTS`] times: a write whose every
    /// name is taken fails after that many, and the file under the taken name is left as
    /// it was. Control: a free name is taken at once.
    #[cfg(unix)]
    #[test]
    fn temporary_names_are_tried_a_bounded_number_of_times() {
        use std::os::fd::AsFd as _;

        use super::unix::{create_temp, MAX_TEMP_ATTEMPTS};

        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(".taken"), "T").unwrap();
        let fd = rustix::fs::open(
            dir.path(),
            rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::DIRECTORY,
            rustix::fs::Mode::empty(),
        )
        .unwrap();
        let tried = std::cell::Cell::new(0usize);
        let taken = std::iter::repeat_with(|| {
            tried.set(tried.get() + 1);
            std::ffi::OsString::from(".taken")
        });
        let result = create_temp(fd.as_fd(), rustix::fs::Mode::RUSR, taken);
        assert_eq!(result.map(|_| ()).unwrap_err(), rustix::io::Errno::EXIST);
        assert_eq!(tried.get(), MAX_TEMP_ATTEMPTS);
        assert_eq!(
            std::fs::read_to_string(dir.path().join(".taken")).unwrap(),
            "T"
        );

        let free = [std::ffi::OsString::from(".free")];
        let (temp, _file) = create_temp(fd.as_fd(), rustix::fs::Mode::RUSR, free).unwrap();
        assert_eq!(temp.name, ".free");
        drop(temp);
        assert!(
            !dir.path().join(".free").exists(),
            "dropped, the file is unlinked"
        );
    }

    // ── Moved from output.rs: the replace-by-rename contract ─────────────────────

    /// An error writing a file names it by `shown`, never by `path`, and its cause is the
    /// operating system's, naming no path (#390). Control: the whole message is the one
    /// expected, so the target is named.
    ///
    /// `#[cfg(unix)]`: a read-only directory is what makes the temporary file fail, and
    /// Windows' read-only attribute does not stop a file being created in one (#147).
    #[cfg(unix)]
    #[test]
    fn an_error_writing_names_the_file_as_shown_and_no_path_of_its_own() {
        use std::os::unix::fs::PermissionsExt as _;

        let dir = tempfile::tempdir().unwrap();
        let sub = dir.path().join("sub");
        std::fs::create_dir(&sub).unwrap();
        let target = WriteTarget::new(sub.join("locked.mds"), Path::new("out").join("locked.mds"));
        std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o555)).unwrap();
        let probe = std::fs::write(sub.join("probe"), "");
        let result = atomic_write_file(&target, "NEW", Durability::Fsync, Parents::Existing);
        std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o755)).unwrap();
        if probe.is_ok() {
            crate::output::ewriteln!(
                "running as root; a read-only directory does not stop the write"
            );
            return;
        }

        let err = result
            .expect_err("a read-only directory must fail the write")
            .to_string();
        assert_eq!(
            err,
            format!(
                "cannot write out/locked.mds: {}",
                os_text(rustix::io::Errno::ACCESS)
            )
        );
        let tmp = dir.path().display().to_string();
        assert!(!err.contains(&tmp), "no path of the write's own: {err}");
        assert!(!err.contains(TEMP_PREFIX), "no temporary file: {err}");
    }

    /// T-U1: `mds build` writes artifacts that do not exist yet (#227). The primitive must
    /// create the target instead of failing the existence probe.
    #[test]
    fn atomic_write_file_creates_missing_target() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("fresh.md");
        assert!(!target.exists(), "precondition: target must be absent");

        write_as_typed(&target, "CREATED", Durability::Fsync)
            .expect("writing an absent target must succeed");

        assert_eq!(std::fs::read_to_string(&target).unwrap(), "CREATED");
        let residue = temp_residue(dir.path());
        assert!(
            residue.is_empty(),
            "no .mds-tmp- residue may survive a successful write; got {residue:?}"
        );
    }

    /// T-U9: `Durability::RenameOnly` changes ONLY whether the write is synced. Everything
    /// the callers rely on — the content, the mode of a freshly created artifact, the
    /// symlink refusal, and leaving no temp residue — must be identical to `Fsync` (#227).
    /// The syncs themselves are not observable from a passing process; what this pins is
    /// that skipping them did not quietly relax anything else, and that the file and
    /// directory syncs of `Fsync` succeed on this filesystem.
    #[test]
    fn atomic_write_file_rename_only_matches_fsync_contract() {
        let dir = tempfile::tempdir().unwrap();

        // Fresh target: created, with the same content and mode as the Fsync sibling.
        let quick = dir.path().join("quick.md");
        let synced = dir.path().join("synced.md");
        write_as_typed(&quick, "DERIVED", Durability::RenameOnly).unwrap();
        write_as_typed(&synced, "DERIVED", Durability::Fsync).unwrap();
        assert_eq!(std::fs::read_to_string(&quick).unwrap(), "DERIVED");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            assert_eq!(
                std::fs::metadata(&quick).unwrap().permissions().mode() & 0o777,
                std::fs::metadata(&synced).unwrap().permissions().mode() & 0o777,
                "RenameOnly must not change the mode a fresh artifact is created with"
            );
        }

        // Existing target: replaced, previous content gone.
        write_as_typed(&quick, "REBUILT", Durability::RenameOnly).unwrap();
        assert_eq!(std::fs::read_to_string(&quick).unwrap(), "REBUILT");
        write_as_typed(&synced, "RESYNCED", Durability::Fsync).unwrap();
        assert_eq!(std::fs::read_to_string(&synced).unwrap(), "RESYNCED");

        // Symlink target: still refused (the sync is not what enforces this).
        {
            let real = dir.path().join("real.md");
            std::fs::write(&real, "REAL").unwrap();
            let link = dir.path().join("link.md");
            if !make_symlink(&real, &link) {
                return;
            }
            let err = write_as_typed(&link, "NEW", Durability::RenameOnly)
                .expect_err("RenameOnly must still refuse a symlink target");
            assert!(
                err.to_string().contains("symlink"),
                "the refusal must say why; got: {err}"
            );
            assert_eq!(std::fs::read_to_string(&real).unwrap(), "REAL");
        }

        let residue = temp_residue(dir.path());
        assert!(
            residue.is_empty(),
            "RenameOnly must leave no .mds-tmp- residue; got {residue:?}"
        );
    }

    /// T-U2: a freshly created artifact must carry the same mode `std::fs::write` would
    /// have produced (`0666 & !umask`), not an owner-only 0600. The sibling control makes
    /// the assertion umask-independent.
    ///
    /// `#[cfg(unix)]`: unix permission mode bits (`PermissionsExt::mode`) have no Windows
    /// equivalent — the permission model differs (#147).
    #[cfg(unix)]
    #[test]
    fn atomic_write_file_new_file_mode_matches_std_fs_write() {
        use std::os::unix::fs::PermissionsExt as _;

        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("out.md");
        let ctl = dir.path().join("ctl.md");

        write_as_typed(&out, "X", Durability::Fsync).unwrap();
        std::fs::write(&ctl, "X").unwrap();

        let mode_out = std::fs::metadata(&out).unwrap().permissions().mode() & 0o777;
        let mode_ctl = std::fs::metadata(&ctl).unwrap().permissions().mode() & 0o777;
        assert_eq!(
            mode_out, mode_ctl,
            "new-file mode must match std::fs::write; got 0{mode_out:o} vs control 0{mode_ctl:o}"
        );
    }

    /// T-U3: an existing file keeps its mode across the replace-by-rename cycle — owner-only
    /// `0600`, which the umask could never produce for a new file, and `0640`.
    ///
    /// `#[cfg(unix)]`: unix permission mode bits have no Windows equivalent (#147).
    #[cfg(unix)]
    #[test]
    fn atomic_write_file_existing_mode_preserved() {
        use std::os::unix::fs::PermissionsExt as _;

        let dir = tempfile::tempdir().unwrap();
        for kept in [0o600, 0o640] {
            let target = dir.path().join(format!("src-{kept:o}.mds"));
            std::fs::write(&target, "OLD").unwrap();
            std::fs::set_permissions(&target, std::fs::Permissions::from_mode(kept)).unwrap();

            write_as_typed(&target, "NEW", Durability::Fsync).unwrap();

            let mode = std::fs::metadata(&target).unwrap().permissions().mode() & 0o7777;
            assert_eq!(mode, kept, "existing mode must be preserved; got 0{mode:o}");
            assert_eq!(std::fs::read_to_string(&target).unwrap(), "NEW");
        }
    }

    /// A replaced file lends its replacement its permission bits alone, never its setuid,
    /// setgid or sticky bit (#160): a `0o4755`, a `0o2755` and a `0o1755` file the user
    /// owns are each replaced by a `0o755` one. Each bit is read back after it is set, so
    /// the file replaced held it. (Writing to a file clears its setuid and setgid bits for
    /// a writer without the privilege to keep them, so for most users only the sticky bit
    /// would otherwise reach the replacement.)
    #[cfg(unix)]
    #[test]
    fn a_replaced_file_lends_only_its_permission_bits() {
        use std::os::unix::fs::PermissionsExt as _;

        let dir = tempfile::tempdir().unwrap();
        for special in [0o4755, 0o2755, 0o1755] {
            let target = dir.path().join(format!("tool-{special:o}.md"));
            let mode = || std::fs::metadata(&target).unwrap().permissions().mode() & 0o7777;
            std::fs::write(&target, "OLD").unwrap();
            std::fs::set_permissions(&target, std::fs::Permissions::from_mode(special)).unwrap();
            assert_eq!(mode(), special, "the file replaced holds the bit");

            write_as_typed(&target, "NEW", Durability::RenameOnly).unwrap();

            assert_eq!(std::fs::read_to_string(&target).unwrap(), "NEW");
            assert_eq!(mode(), 0o755, "0{special:o} replaced: got 0{:o}", mode());
        }
    }

    /// A replaced file lends its permission bits only to a file its own owner writes
    /// (#160): from a file another user owns — which only that user chose the mode of —
    /// none, and the replacement keeps the mode a new file is created with. Control: the
    /// same modes, one owner, lend their permission bits and nothing else.
    #[cfg(unix)]
    #[test]
    fn only_a_file_its_writer_owns_lends_its_mode() {
        use rustix::fs::RawMode;

        use super::unix::kept_mode;

        /// `st_mode`'s file type for a regular file, as `stat` gives it above the mode.
        const REGULAR: RawMode = 0o100_000;
        let kept = |st_mode: RawMode, same_owner: bool| {
            kept_mode(st_mode, same_owner).map(|mode| mode.bits())
        };
        assert_eq!(kept(REGULAR | 0o640, true), Some(0o640));
        assert_eq!(kept(REGULAR | 0o7755, true), Some(0o755));
        assert_eq!(kept(REGULAR | 0o666, false), None);
        assert_eq!(kept(REGULAR | 0o4755, false), None);
        assert_eq!(kept(REGULAR | 0o600, false), None);
    }

    /// A file another user owns is replaced by one with the mode a new file is created
    /// with, never that file's (#160): `0o777` lent to the replacement would leave its
    /// bytes open to everyone whatever the writer's umask. Only a writer allowed to give a
    /// file away can set one up, so this runs as root and is skipped, with a reason,
    /// otherwise; [`only_a_file_its_writer_owns_lends_its_mode`] pins the rule everywhere.
    /// Control: a file `std::fs::write` creates beside it has the same mode — never an
    /// execute bit, so never the mode lent.
    #[cfg(unix)]
    #[test]
    fn a_file_another_user_owns_lends_its_replacement_no_mode() {
        use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};

        let dir = tempfile::tempdir().unwrap();
        if std::fs::metadata(dir.path()).unwrap().uid() != 0 {
            crate::output::ewriteln!("not running as root; cannot give a file to another user");
            return;
        }
        let target = dir.path().join("shared.md");
        let fresh = dir.path().join("fresh.md");
        std::fs::write(&target, "OLD").unwrap();
        std::os::unix::fs::chown(&target, Some(65_534), None).unwrap();
        std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o777)).unwrap();
        let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode() & 0o7777;
        assert_eq!(std::fs::metadata(&target).unwrap().uid(), 65_534);
        assert_eq!(mode(&target), 0o777);

        write_as_typed(&target, "NEW", Durability::RenameOnly).unwrap();
        std::fs::write(&fresh, "NEW").unwrap();

        assert_eq!(std::fs::read_to_string(&target).unwrap(), "NEW");
        assert_eq!(mode(&target), mode(&fresh), "got 0{:o}", mode(&target));
        assert_eq!(temp_residue(dir.path()), Vec::<String>::new());
    }

    /// T-U4: a symlink at the target is refused, never written through. The control writes
    /// the symlink's own target directly and must succeed, so the refusal is not passing on
    /// an unrelated failure.
    #[test]
    fn atomic_write_file_refuses_live_symlink_target() {
        let dir = tempfile::tempdir().unwrap();
        let real = dir.path().join("real.md");
        let link = dir.path().join("link.md");
        std::fs::write(&real, "REAL").unwrap();
        if !make_symlink(&real, &link) {
            return;
        }

        let err = write_as_typed(&link, "NEW", Durability::Fsync)
            .expect_err("writing through a symlink must be refused");
        assert!(
            matches!(err, mds::MdsError::Io { .. }),
            "a refused write is mds::io, exit 2 (#157); got {err:?}"
        );
        let err = err.to_string();
        assert!(
            err.ends_with(&format!(": {SYMLINK_REFUSAL}")),
            "expected a symlink refusal; got {err}"
        );
        assert_eq!(
            std::fs::read_to_string(&real).unwrap(),
            "REAL",
            "the symlink's target must not be written through"
        );
        assert!(
            std::fs::symlink_metadata(&link)
                .unwrap()
                .file_type()
                .is_symlink(),
            "the symlink itself must survive the refusal"
        );

        // CONTROL: the same directory and content, addressed at the real file.
        write_as_typed(&real, "NEW", Durability::Fsync)
            .expect("writing the real file must succeed");
        assert_eq!(std::fs::read_to_string(&real).unwrap(), "NEW");
    }

    /// T-U5: a dangling symlink is still a symlink — refuse it rather than materialising
    /// the missing file it points at.
    #[test]
    fn atomic_write_file_refuses_dangling_symlink_target() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("missing.md");
        let link = dir.path().join("link.md");
        if !make_symlink(&missing, &link) {
            return;
        }

        let err = write_as_typed(&link, "NEW", Durability::Fsync)
            .expect_err("writing through a dangling symlink must be refused")
            .to_string();
        assert!(
            err.ends_with(&format!(": {SYMLINK_REFUSAL}")),
            "expected a symlink refusal; got {err}"
        );
        assert!(
            !missing.exists(),
            "the dangling link's target must not be created"
        );
        assert!(
            std::fs::symlink_metadata(&link)
                .unwrap()
                .file_type()
                .is_symlink(),
            "the symlink itself must survive the refusal"
        );
    }

    /// T-U6: a failed write leaves the original inode, bytes and mtime untouched and no
    /// temp file. The control proves the same call succeeds once the directory is writable
    /// again, and that success DOES replace the inode.
    ///
    /// `#[cfg(unix)]`: provokes the failure via chmod and asserts on
    /// `MetadataExt::ino()`, neither of which exists on Windows (#147).
    #[cfg(unix)]
    #[test]
    fn atomic_write_file_failure_preserves_original_and_leaves_no_temp() {
        use std::os::unix::fs::MetadataExt as _;
        use std::os::unix::fs::PermissionsExt as _;

        let dir = tempfile::tempdir().unwrap();
        let sub = dir.path().join("sub");
        std::fs::create_dir(&sub).unwrap();
        let target = sub.join("locked.mds");
        std::fs::write(&target, "OLD").unwrap();

        let before = std::fs::metadata(&target).unwrap();
        let (ino, mtime) = (before.ino(), before.modified().unwrap());

        std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o555)).unwrap();
        let result = write_as_typed(&target, "NEW", Durability::Fsync);
        // Restore before asserting so a failed assertion cannot leave an undeletable
        // tempdir behind.
        std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o755)).unwrap();

        let err = result
            .expect_err("a read-only parent directory must fail the write")
            .to_string();
        assert!(
            err.contains("locked.mds"),
            "error must name the target; got {err}"
        );
        assert_eq!(std::fs::read_to_string(&target).unwrap(), "OLD");
        let after = std::fs::metadata(&target).unwrap();
        assert_eq!(
            after.ino(),
            ino,
            "a failed write must not replace the inode"
        );
        assert_eq!(
            after.modified().unwrap(),
            mtime,
            "a failed write must not touch the mtime"
        );
        let residue = temp_residue(&sub);
        assert!(
            residue.is_empty(),
            "failed write left temp residue: {residue:?}"
        );

        // CONTROL: writable again — the same call succeeds and swaps the inode.
        write_as_typed(&target, "NEW", Durability::Fsync)
            .expect("write must succeed once the dir is writable");
        assert_eq!(std::fs::read_to_string(&target).unwrap(), "NEW");
        assert_ne!(
            std::fs::metadata(&target).unwrap().ino(),
            ino,
            "replace-by-rename must produce a new inode"
        );
    }

    /// T-U7: a directory at the target fails the write at its last step — the rename, after
    /// the temporary file was created and written — and leaves no temp file behind: the
    /// injected failure the unlink guard is for. Named as shown (#390): the error names
    /// neither the path written nor the temporary file.
    #[test]
    fn atomic_write_file_directory_target_refused_without_residue() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("adir");
        std::fs::create_dir(&target).unwrap();

        let shown = Path::new("out").join("adir");
        let err = atomic_write_file(
            &WriteTarget::new(target.clone(), shown.clone()),
            "X",
            Durability::Fsync,
            Parents::Existing,
        )
        .expect_err("a directory target must not be written")
        .to_string();
        let named = format!("cannot write {}: ", safe_path(&shown));
        assert!(
            err.starts_with(&named),
            "error must name the target as shown; got {err}"
        );
        let tmp = dir.path().display().to_string();
        assert!(!err.contains(&tmp), "no path of the write's own: {err}");
        assert!(!err.contains(TEMP_PREFIX), "no temporary file: {err}");
        assert!(target.is_dir(), "the directory must survive the refusal");
        let residue = temp_residue(dir.path());
        assert!(
            residue.is_empty(),
            "refused write left temp residue: {residue:?}"
        );
    }

    /// T-U8: a directory the write cannot open is a hard error — never a write with a
    /// guessed mode (#225) — naming the target and the operating system's cause.
    ///
    /// `#[cfg(unix)]`: provokes the failure with a `0o000`-mode parent directory; Windows'
    /// permission model does not block traversal the same way (#147).
    #[cfg(unix)]
    #[test]
    fn atomic_write_file_unreadable_parent_is_hard_error() {
        use std::os::unix::fs::PermissionsExt as _;

        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("nosearch");
        std::fs::create_dir(&p).unwrap();
        // Planted before the chmod so the root probe below has something to stat.
        let probe = p.join("probe");
        std::fs::write(&probe, "").unwrap();
        std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o000)).unwrap();

        if std::fs::metadata(&probe).is_ok() {
            // Root bypasses the mode bits; EACCES cannot be provoked here.
            std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
            crate::output::ewriteln!("running as root; cannot exercise EACCES");
            return;
        }

        let target = WriteTarget::new(p.join("x.md"), PathBuf::from("x.md"));
        let result = atomic_write_file(&target, "X", Durability::Fsync, Parents::Existing);
        // Restore before asserting so tempdir cleanup always succeeds.
        std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();

        let err = result
            .expect_err("an unopenable directory must be a hard error")
            .to_string();
        assert_eq!(
            err,
            format!("cannot write x.md: {}", os_text(rustix::io::Errno::ACCESS))
        );
        assert!(!p.join("x.md").exists());
    }
}