mds-cli 0.7.0

MDS (Markdown Script) compiler — command-line interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
//! Watch subcommand — file watcher with auto-recompile on save (issue #57).
//!
//! # Design overview
//!
//! Two modes share a single watch loop:
//!
//! - **Single-file mode**: watches the entry file and all its transitive imports.
//!   On each rebuild the dependency set is recomputed from fresh compilation output
//!   (the freshness rule under "Key invariants": never trust a stale dep set).
//!
//! - **Directory mode**: recursive watch on the root dir; tracks a reverse-dependency
//!   graph so editing a shared partial recompiles all transitive importers.
//!   `_`-prefixed files are partials: tracked in the graph but never emitted to their
//!   own `.md` output (DD2). Cross-root dependencies are watched NonRecursively (DD3).
//!   Output mirrors the source subtree under `--out-dir` / `mds.json output_dir` (Fix 2).
//!
//! # Change detection
//!
//! Both modes run two detectors, and neither alone is sufficient:
//!
//! 1. **OS watches** (inotify / FSEvents) — the primary path. Armed before the first
//!    read of anything they cover, so an edit during startup is queued, not dropped.
//! 2. **The idle-tick content backstop** — a `(mtime, size)` diff over every tracked
//!    source *and dependency*, run once per `--poll-interval` by `liveness_probe_*`.
//!    It exists for changes no OS event can announce: a cross-root dependency's
//!    directory is unknowable until the compile that reads it returns, and a watch
//!    descriptor destroyed by `rmdir` never announces its own replacement (#321).
//!
//! The tick is scheduled against an absolute deadline (`TickSchedule`, driven by
//! `TickClock`), so a stream of filesystem events cannot postpone the backstop
//! indefinitely (#319).
//!
//! # Coalescing
//!
//! `--debounce` is a **quiet period**: the first relevant event opens a window and
//! every further content event restarts it, so a save burst longer than the window is
//! still one rebuild. The window is itself bounded — by an absolute cap of
//! `max(10 x window, 1s)` measured from the first event, and by 10 000 drained
//! messages — because the loop does not consult the idle tick while a window is open,
//! so an unbounded window would starve the content backstop as well as the rebuild
//! (#379).
//!
//! # Empty files
//!
//! An editor that saves by truncating and then writing leaves the file empty for a
//! moment, at any `--debounce`. A rebuild that finds a watched file — the entry, a
//! dependency, the `--vars` file, any source of a watched directory — empty where the
//! baseline saw bytes is held back (`EmptyHold`): nothing is compiled, written or printed
//! until a rebuild finds it written, or until a deadline one second after the first
//! rebuild that found it emptied, when the files are compiled as they are. The deadline
//! never moves, and the loop's driver waits for it like the tick, so neither a stream of
//! events nor `--poll-interval 0` can move it; a debounce window already collecting events
//! when it comes finishes first, so the held rebuild can run later by at most that window's
//! cap (#380).
//!
//! # Key invariants
//!
//! - All content output → stdout ONLY when output resolves to stdout.
//! - All status / warnings / errors → stderr (pipe-safe).
//! - `--quiet` suppresses status + warnings but NOT compile errors.
//! - Exit 0 on clean Ctrl+C, or 101 if a compile panicked during the session, which
//!   keeps watching until it is stopped; a panic anywhere else ends the session with
//!   101 (#389). Otherwise non-zero only on startup failure.
//! - Streams (#157): with `-o -`, stdout's reader going away ends the session with
//!   `Stopped watching (stdout closed).` and verdict 0, since nothing can receive its
//!   output any more; a closed stderr only loses the status lines. Once live
//!   ([`live::run_session`]), a rebuild's output failure is reported where it can be and never
//!   changes the exit code; a session that ends at startup exits as a batch run does.
//!   Every status line goes through the CLI's stderr writer, which never panics.
//! - Compile errors during watching never terminate the watcher.
//! - All loops have fixed upper bounds (reconcile rule / reliability.md): the idle tick
//!   against an absolute deadline, the debounce window against an absolute cap
//!   (window <= cap) and a message bound (<= 10 000 per window), and a rebuild held
//!   while a watched file is empty against an absolute deadline (#380).
//! - All `.mds` reads go through `compile_native_to_content`.
//! - **Freshness rule** (design decision of 2026-06; kept in git history as legacy
//!   decision 016 in `88ddbcc~1:.devflow/decisions/decisions.md`): the dependency set
//!   and the `--vars` file are re-derived from fresh compile output / from disk on
//!   every rebuild — never served from a cached snapshot.
//! - **Reconcile rule** (legacy decision 021, same file): the idle tick only re-arms
//!   watches cheaply; a full directory rescan happens only on watch loss/recovery, so
//!   idle cost is O(1) in tree size.

use std::cell::OnceCell;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::ops::ControlFlow;
use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};
use std::sync::{mpsc, Arc};
use std::time::{Duration, Instant};

use miette::Result;
use notify::{Event, RecommendedWatcher, RecursiveMode, Watcher};

use mds::MdsError;

use crate::build::{
    admit_output, auto_detect_mds_file, build_runtime_vars_logged, compile_inputs,
    compile_native_to_content, resolve_dir_as_created, resolve_output_path_for_kind, source_inputs,
    write_output, CompileOutput, EntryPaths, OutputKind, ProjectConfig, RuntimeVarArgs,
    RuntimeVars,
};
use crate::output::{
    collect_mds_files, eprint_error, eprint_warning, is_partial, is_within_default_excluded_dir,
    notify_cause, output_path_for, resolve_output_base, safe_inline, safe_path, stdout_failure,
    write_stdout, OutputBase, Panicked, RootPaths, StdoutOutcome, WriteTarget,
};
use crate::write::{
    remove_proven, write_over_own, DirIdentity, Durability, Inputs, NotCreated, NotRemoved,
    Parents, Removal,
};

// ── Public args struct ────────────────────────────────────────────────────────

pub(crate) struct WatchArgs {
    pub(crate) input: Option<PathBuf>,
    /// `-o/--output` as given; `reject_forbidden_output_flags` turns it into text.
    pub(crate) output: Option<std::ffi::OsString>,
    pub(crate) out_dir: Option<PathBuf>,
    pub(crate) vars: Option<PathBuf>,
    pub(crate) set_vars: Vec<(String, String)>,
    pub(crate) set_string_vars: Vec<(String, String)>,
    pub(crate) clear: bool,
    pub(crate) debounce: u64,
    pub(crate) quiet: bool,
    pub(crate) poll_interval: u64,
}

// ── Internal message types ────────────────────────────────────────────────────

enum Msg {
    Fs(notify::Result<Event>),
    Interrupt,
}

// ── OutputBase re-exported from output.rs (moved for shared use) ─────────────
//
// `OutputBase`, `resolve_output_base`, `output_path_for`, `collect_mds_files`,
// and `is_partial` are now defined in `output.rs` and imported above.
// The doc comments there describe the contracts; no duplication needed here.

// ── Pure helpers (unit-tested below) ─────────────────────────────────────────

/// Compute the set of parent directories that need to be watched (non-recursively)
/// to cover `entry`, all `deps` (graph keys, [`graph_keys`]), and an optional
/// `vars_file`.
///
/// Watching parent directories rather than file inodes is necessary because editors
/// perform atomic save via rename: a file-inode watch is silently orphaned after the
/// swap, but a directory watch survives.
pub(crate) fn dirs_to_watch(
    entry: &Path,
    deps: &[PathBuf],
    vars_file: Option<&Path>,
) -> BTreeSet<PathBuf> {
    let mut dirs = BTreeSet::new();

    let push_parent = |path: &Path, set: &mut BTreeSet<PathBuf>| {
        // Route through mds::effective_parent so that bare filenames — where
        // Path::parent() returns Some("") rather than None — are handled by the
        // single canonical implementation rather than an inline re-implementation.
        // Avoids PF-006: one owner, one place to maintain or regress.
        set.insert(mds::effective_parent(path).to_path_buf());
    };

    push_parent(entry, &mut dirs);

    for dep in deps {
        push_parent(dep, &mut dirs);
    }

    if let Some(vf) = vars_file {
        push_parent(vf, &mut dirs);
    }

    dirs
}

/// Build the set of paths that are "of interest" for a single-file watch:
/// the entry itself, all dependency paths (graph keys), and the vars file if given.
pub(crate) fn files_of_interest(
    entry: &Path,
    deps: &[PathBuf],
    vars_file: Option<&Path>,
) -> HashSet<PathBuf> {
    let mut set = HashSet::new();
    set.insert(entry.to_path_buf());
    for dep in deps {
        set.insert(dep.clone());
    }
    if let Some(vf) = vars_file {
        set.insert(vf.to_path_buf());
    }
    set
}

/// Return `true` for filesystem event kinds that represent **content changes**.
///
/// `EventKind::Access(_)` covers inotify `IN_ACCESS`, `IN_OPEN`, and
/// `IN_CLOSE_NOWRITE` — events emitted when a file is merely *read*, not
/// written.  On Linux the compile step reads `.mds` source files, which causes
/// inotify to emit Access events for those same files.  Without this filter the
/// watcher ingests those events, re-compiles, reads again, emits more Access
/// events, and enters a busy-loop (thousands of recompiles per second).
///
/// macOS FSEvents does not report reads, so this bug was invisible locally and
/// only manifested in CI on `ubuntu-latest`.
///
/// Kept conservative: `Modify`, `Create`, `Remove`, `Any`, `Other` all return
/// `true`.  `Access(Close(AccessMode::Write))` is technically a write-close but
/// those paths also produce a `Modify` event on Linux, so excluding all Access
/// variants is safe and simpler.
pub(crate) fn is_content_event(kind: &notify::EventKind) -> bool {
    !matches!(kind, notify::EventKind::Access(_))
}

/// Return `true` when an fs event is relevant to the current watch set.
///
/// Matches by canonical path. Falls back to (file-name + parent) comparison
/// for just-renamed files whose canonical path may differ transiently.
/// Also tries canonicalizing the event path to handle /tmp → /private/tmp
/// symlink differences on macOS.
///
/// After a case-only rename on a case-insensitive volume (#481), an event names the
/// file by its new spelling, and the watch set holds the spelling it had at startup.
/// Each watched path in the event's canonical directory is then resolved again, and
/// the result is compared with the event's canonical path: canonical with canonical,
/// never as text or with case folded. This is a trigger only: the watch set keeps the
/// startup spelling.
pub(crate) fn event_is_relevant(event: &Event, watched: &HashSet<PathBuf>) -> bool {
    for path in &event.paths {
        if watched.contains(path) {
            return true;
        }
        // Try resolving symlinks in the event path (macOS /tmp → /private/tmp).
        if let Ok(canonical) = path.canonicalize() {
            if watched.contains(&canonical) {
                return true;
            }
            let dir = canonical.parent();
            if watched
                .iter()
                .filter(|w| w.parent() == dir)
                .any(|w| w.canonicalize().is_ok_and(|now| now == canonical))
            {
                return true;
            }
        }
        // Fallback: check by (parent, file_name) in case the path is a relative
        // or non-canonical form of a watched file.
        let name = path.file_name();
        let parent = path.parent();
        if let (Some(n), Some(p)) = (name, parent) {
            if watched
                .iter()
                .any(|w| w.file_name() == Some(n) && w.parent() == Some(p))
            {
                return true;
            }
            // Also try canonical parent.
            if let Ok(cp) = p.canonicalize() {
                if watched
                    .iter()
                    .any(|w| w.file_name() == Some(n) && w.parent() == Some(cp.as_path()))
                {
                    return true;
                }
            }
        }
    }
    false
}

// collect_mds_files and is_partial are now in output.rs (imported above).

/// Canonicalize a graph key: exists → `p.canonicalize()`; missing → canonicalize parent + rejoin.
///
/// Used to normalize event paths before graph lookups so macOS `/tmp`→`/private/tmp`
/// and other symlink-resolved differences are handled consistently.
pub(crate) fn graph_key(p: &Path) -> PathBuf {
    if let Ok(c) = p.canonicalize() {
        return c;
    }
    // File doesn't exist (just deleted): canonicalize effective parent + rejoin filename.
    // mds::effective_parent maps Some("") (bare filename, e.g. "hello.mds") to
    // Path::new(".") so that "".canonicalize() never runs — avoids PF-006 in the
    // graph-key lookup-miss path: without this guard a bare-named file that is
    // deleted cannot be matched against the absolute-path keys stored in forward_deps.
    let parent = mds::effective_parent(p);
    if let Ok(cp) = parent.canonicalize() {
        if let Some(name) = p.file_name() {
            return cp.join(name);
        }
    }
    p.to_path_buf()
}

/// The graph keys ([`graph_key`]) of the dependencies a compile reported, in the
/// canonical form notify reports event paths in — which on Windows keeps the `\\?\`
/// prefix the compiler's own list drops (#409).
///
/// Each stays a path (#390): the text of a path is lossy for a name that is not UTF-8,
/// so two dependencies whose names differ only there would share one key.
pub(crate) fn graph_keys<P: AsRef<Path>>(paths: &[P]) -> Vec<PathBuf> {
    paths.iter().map(|p| graph_key(p.as_ref())).collect()
}

/// Compute the transitive set of sources affected by `seeds`.
///
/// Builds an inverted importer map from the start-of-batch `forward_deps` snapshot
/// then walks DFS with a visited set (cycle-safe, terminates).
/// Returns `seeds ∪ all transitive importers`.
///
/// Pure function — only reads `forward_deps`, does not mutate it.
pub(crate) fn affected_sources(
    forward_deps: &HashMap<PathBuf, Vec<PathBuf>>,
    seeds: &BTreeSet<PathBuf>,
) -> Vec<PathBuf> {
    // Build inverted map: dep → Vec<importer>
    let mut importers: HashMap<&PathBuf, Vec<&PathBuf>> = HashMap::new();
    for (src, deps) in forward_deps {
        for dep in deps {
            importers.entry(dep).or_default().push(src);
        }
    }

    let mut visited: HashSet<&PathBuf> = HashSet::new();
    let mut result: Vec<PathBuf> = Vec::new();
    let mut stack: Vec<&PathBuf> = Vec::new();

    // Seed the stack with the initial changed files.
    for seed in seeds {
        if visited.insert(seed) {
            result.push(seed.clone());
            stack.push(seed);
        }
    }

    // DFS: find all importers transitively.
    while let Some(node) = stack.pop() {
        if let Some(imps) = importers.get(node) {
            for imp in imps {
                if visited.insert(imp) {
                    result.push((*imp).clone());
                    stack.push(imp);
                }
            }
        }
    }

    result
}

/// A single path's content fingerprint: `(mtime, size)`.
///
/// Each field is `None` when the file does not exist or its metadata is unreadable —
/// absence is a valid state to track, and is what lets a deletion register as a change.
pub(crate) type FileStamp = (Option<std::time::SystemTime>, Option<u64>);

/// A `(mtime, size)` baseline keyed by path, as produced by [`snapshot_state`].
pub(crate) type StampMap = HashMap<PathBuf, FileStamp>;

/// Snapshot `(mtime, size)` for a set of paths (liveness probe state).
///
/// Returns `None` for the mtime or size field when the file doesn't exist or
/// the metadata call fails — absence is a valid state to track.
pub(crate) fn snapshot_state(paths: &HashSet<PathBuf>) -> StampMap {
    let mut map = HashMap::new();
    for p in paths {
        match std::fs::metadata(p) {
            Ok(m) => {
                let mtime = m.modified().ok();
                let size = Some(m.len());
                map.insert(p.clone(), (mtime, size));
            }
            Err(_) => {
                map.insert(p.clone(), (None, None));
            }
        }
    }
    map
}

/// Record `path`'s current `(mtime, size)` in `snapshot`, keeping any entry already
/// there.
///
/// The keep-existing rule is the point: baselines are merged oldest-wins, because only
/// a baseline taken before a read can prove the read saw the current content.
pub(crate) fn baseline_path(path: &Path, snapshot: &mut StampMap) {
    snapshot
        .entry(path.to_path_buf())
        .or_insert_with(|| match std::fs::metadata(path) {
            Ok(m) => (m.modified().ok(), Some(m.len())),
            Err(_) => (None, None),
        });
}

/// Return `true` if the current `(mtime, size)` of `path` differs from its entry in
/// `prev`.
///
/// A path with no entry in `prev` counts as differing: the baseline has never seen it,
/// so the watcher cannot claim its content is accounted for.
pub(crate) fn path_state_differs(path: &Path, prev: &StampMap) -> bool {
    let current = match std::fs::metadata(path) {
        Ok(m) => (m.modified().ok(), Some(m.len())),
        Err(_) => (None, None),
    };
    !matches!(prev.get(path), Some(old) if *old == current)
}

/// Return `true` if the current `(mtime, size)` of any path in `paths` differs
/// from its entry in `prev`.
pub(crate) fn state_differs(paths: &HashSet<PathBuf>, prev: &StampMap) -> bool {
    paths.iter().any(|p| path_state_differs(p, prev))
}

/// Decide whether a missing/recovered external dep dir should trigger a full
/// reconcile, and compute the new "missing" set for the next tick.
///
/// Edge-triggered (reconcile rule / AC-P1): a missing external dir forces a reconcile
/// only when it *reappears* (was in `prev_missing`, now exists). A dir that stays
/// missing across ticks does NOT trigger a walk — otherwise a permanently-deleted
/// cross-root dep dir would cause an O(tree) rescan on every idle tick.
///
/// `statuses` is one `(dir, exists, rearm_ok)` per current external dep dir, where
/// `rearm_ok` is the result of attempting to re-arm an existing dir (ignored when
/// `exists` is false).
///
/// Returns `(recovery_needed, now_missing)`.
pub(crate) fn external_recovery_decision(
    prev_missing: &BTreeSet<PathBuf>,
    statuses: &[(PathBuf, bool, bool)],
) -> (bool, BTreeSet<PathBuf>) {
    let mut now_missing = BTreeSet::new();
    let mut recovery = false;
    for (dir, exists, rearm_ok) in statuses {
        if *exists {
            if !*rearm_ok {
                // Re-arming an existing dir failed: genuine watch loss.
                recovery = true;
            } else if prev_missing.contains(dir) {
                // Was missing last tick, now exists and re-armed: recovery edge.
                recovery = true;
            }
        } else {
            now_missing.insert(dir.clone());
        }
    }
    (recovery, now_missing)
}

/// Canonicalize an optional vars path so it matches the canonical paths in notify
/// events (e.g. resolves `/tmp` → `/private/tmp` on macOS).
///
/// Rejects a symlinked vars file at startup (build parity — PF-004).
/// Falls back to the raw path when the file does not yet exist (the user may create
/// it later; the vars file is reloaded on every rebuild — freshness rule — so a duplicate
/// key introduced after startup is caught on the next rebuild, #326).
///
/// A path carrying a forbidden path character (#265) is refused first, before the
/// `exists` probe — so before its directory is ever watched — with the message
/// `check_symlink` gives an existing one (`mds::io`).
///
/// Only the symlink refusal (`ImportError`) is reworded for the `--vars` flag, as every
/// command words it ([`crate::build::vars_file_error`], #157); every other `check_symlink`
/// error — a forbidden character in the resolved path, or a file removed since the
/// `exists` probe — keeps its own message and code.
pub(crate) fn canonicalize_vars_path(vars: Option<PathBuf>) -> Result<Option<PathBuf>, MdsError> {
    if let Some(p) = &vars {
        crate::output::reject_forbidden_output_path("path", p.as_os_str())?;
    }
    match vars {
        Some(p) if p.exists() => mds::NativeFs::check_symlink(&p)
            .map(Some)
            .map_err(|e| crate::build::vars_file_error(&p, e)),
        other => Ok(other),
    }
}

/// A rebuild is over: drop the clear `--clear` asked for, unless the rebuild ended held
/// (#380).
///
/// The event that starts a rebuild asks for the clear ([`crate::output::ask_clear`]) and the
/// first thing the CLI prints then makes it, before its first byte: a compile warning, a
/// failure report, a `Recompiled` line, the compiled output on stdout. So the clear never
/// wipes what the rebuild prints, and no rebuild that prints nothing makes one.
///
/// A rebuild that printed nothing and is not held leaves no clear for a line printed after
/// it — a watch warning, a later tick — so its request ends with it, here. A rebuild held
/// while a file is empty printed nothing either, but it is no rebuild that ran: the one that
/// ends the hold prints, and makes the clear its event asked for. `hold` tells which: it
/// has a deadline exactly while a rebuild is held ([`EmptyHold::deadline`]).
fn end_rebuild_clear(hold: &EmptyHold) {
    if hold.deadline().is_none() {
        crate::output::cancel_clear();
    }
}

/// Update the watcher to reflect a new set of directories.
///
/// Unwatch directories no longer needed, watch newly required ones; a directory that
/// cannot be watched is named through [`shown_watched_dir`] with `root` and `vars`.
/// Returns the updated set of currently-watched directories.
pub(crate) fn resync_watches(
    watcher: &mut RecommendedWatcher,
    current_dirs: &BTreeSet<PathBuf>,
    new_dirs: &BTreeSet<PathBuf>,
    root: RootPaths<'_>,
    vars: Option<RootPaths<'_>>,
) -> BTreeSet<PathBuf> {
    let mut result = current_dirs.clone();
    // Unwatch removed directories.
    for dir in current_dirs.difference(new_dirs) {
        // Errors here are non-fatal (dir may have been deleted).
        let _ = watcher.unwatch(dir);
        result.remove(dir);
    }
    // Watch new directories.
    for dir in new_dirs.difference(current_dirs) {
        if let Err(e) = watcher.watch(dir, RecursiveMode::NonRecursive) {
            eprint_warning(&format!(
                "warning: failed to watch {}: {}",
                safe_path(&shown_watched_dir(dir, root, vars)),
                safe_inline(notify_cause(&e))
            ));
        } else {
            result.insert(dir.clone());
        }
    }
    result
}

// ── Small shared helpers ──────────────────────────────────────────────────────

/// Why a watch session stops, which its last status line names.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StopReason {
    /// Ctrl+C — or the event channel closing, which ends the loop the same way.
    Interrupted,
    /// `-o -` and stdout's reader is gone: nothing can receive the output any more
    /// (#157).
    StdoutClosed,
}

/// Emit the session's last status line to stderr (unless quiet): `Stopped watching.`, or
/// `Stopped watching (stdout closed).` when `-o -` lost its reader.
///
/// Called at every point where a watch session ends without an error: Ctrl+C in the watch
/// loop both modes share, and a gone stdout reader in file mode, at startup or on a
/// rebuild. The verdict is 0 — the exit code of a live session ([`live::run_session`]); a
/// session that stops at startup exits as a batch run with that verdict does (#157).
fn stop_watching(quiet: bool, why: StopReason) {
    if quiet {
        return;
    }
    match why {
        StopReason::Interrupted => crate::output::ewriteln!("Stopped watching."),
        StopReason::StdoutClosed => crate::output::ewriteln!("Stopped watching (stdout closed)."),
    }
}

/// Test-only delay injected right after the startup output is published.
///
/// This is the **positive control** for the arm-before-publish ordering: it widens
/// the interval between "output written" and "watch fully live" to a size no edit
/// can miss. Under a defective ordering that interval is a window in which a file
/// is covered by neither detector, and the injected delay drives the lost-edit rate
/// to ~100%. Under the correct ordering the OS watch is already armed and the mtime
/// baseline already captured before the output is written, so the same delay changes
/// nothing — which is exactly what makes it evidence that the *mechanism* is gone
/// rather than merely rarer.
///
/// Compiled out entirely unless the `startup-race-probe` feature is enabled; that
/// feature must never ship enabled.
#[cfg(feature = "startup-race-probe")]
fn startup_race_probe() {
    std::thread::sleep(Duration::from_millis(200));
}

#[cfg(not(feature = "startup-race-probe"))]
fn startup_race_probe() {}

// ── Test-only readiness marker (#390) ─────────────────────────────────────────

/// `MDS_TEST_READY`: how a debug build tells the test suite that it is watching, by
/// creating the file the variable names (`tests/common/mod.rs` waits for it). A release
/// build has none of it: it never reads the variable and never writes the file.
#[cfg(debug_assertions)]
mod ready_trigger {
    use std::path::{Path, PathBuf};

    /// Environment variable that enables the test-only readiness handshake.
    ///
    /// Its value is the **absolute path of a file** to create once the watch is armed.
    /// Test-only: `mds` never sets it itself and it adds no CLI surface.
    const READY_MARKER_ENV: &str = "MDS_TEST_READY";

    /// Contents written to the readiness file named by [`READY_MARKER_ENV`].
    const READY_MARKER: &str = "MDS_WATCH_READY";

    /// Signal readiness by creating the file named by `MDS_TEST_READY`.
    ///
    /// Called by both watch modes at the single instant where **every** file of
    /// interest is covered by at least one detector: its parent directory is armed
    /// with the OS watcher *and* its `(mtime, size)` baseline has been captured.
    /// An edit made after this file appears is guaranteed to be observed.
    ///
    /// This exists because no pre-existing output line is a sound readiness signal:
    /// `"Watching {path}"` is printed *before* the startup compile, and
    /// `"Recompiled …"` only ever appears after a successful *rebuild*. Tests that
    /// keyed off either raced the tail of startup.
    ///
    /// # Why a file and not stderr
    ///
    /// The handshake must not perturb the streams the suite asserts on. A marker line
    /// on stderr would have to bypass `--quiet` (the suite runs with `-q`), which puts
    /// bytes into the exact stream two tests inspect for *emptiness* — that stderr
    /// carries a compile error through `-q`, and that the initial-compile-error path
    /// emits something at all. Both assertions silently become unfalsifiable the moment
    /// anything else is written there unconditionally. A side channel has no such
    /// coupling: stdout and stderr stay byte-for-byte what a real user would see.
    ///
    /// Write-then-rename so a test polling for the path can never observe a partially
    /// written marker. The temporary file is created new ([`create_ready_marker`]), so a
    /// symlink planted at `<marker>.tmp` never redirects the write (#390). Failures are
    /// ignored: this is a test affordance, and a watcher that cannot create the file must
    /// still watch.
    pub(super) fn emit_ready_marker() {
        let Some(raw) = std::env::var_os(READY_MARKER_ENV) else {
            return;
        };
        let path = PathBuf::from(raw);
        // Absolute paths only. A relative value would resolve against the watcher's cwd
        // — which under `cargo test` is the crate root — and litter the source tree.
        if !path.is_absolute() {
            return;
        }
        let mut tmp = path.clone().into_os_string();
        tmp.push(".tmp");
        let tmp = PathBuf::from(tmp);
        if create_ready_marker(&tmp).is_ok() {
            let _ = std::fs::rename(&tmp, &path);
        }
    }

    /// Create `tmp` new, holding [`READY_MARKER`]: never through an entry already at it,
    /// which a write that opens the path would follow if it were a symlink (#390). An
    /// entry there — a leftover, or a planted link — is removed (the entry itself, never
    /// what a link points to) and the file created once more; another entry in between
    /// ends the attempt.
    ///
    /// A raw write, not `atomic_write_file`'s, by design (#227): the rename that follows
    /// it is the atomic step. Allow-listed in tests/write_funnel.rs, in this module alone.
    fn create_ready_marker(tmp: &Path) -> std::io::Result<()> {
        use std::io::Write as _;
        let create = || {
            std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(tmp)
        };
        let mut file = match create() {
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                std::fs::remove_file(tmp)?;
                create()?
            }
            created => created?,
        };
        file.write_all(READY_MARKER.as_bytes())
    }
}

#[cfg(debug_assertions)]
use ready_trigger::emit_ready_marker;

/// A release build's readiness marker: none.
#[cfg(not(debug_assertions))]
fn emit_ready_marker() {}

// ── Empty-file hold (#380) ────────────────────────────────────────────────────

/// How long, at most, a rebuild is held while a watched file is empty (#380), counted
/// from the rebuild that first found it emptied and never extended.
///
/// An editor that saves by truncating the file and then writing it leaves it empty in
/// between, and a rebuild in that moment would publish an empty output nobody wrote. A
/// file still empty this long after is taken to be empty on purpose, and is compiled as it
/// is. One second is far past any editor's truncate-to-write gap and short enough that a
/// file really emptied is published promptly. It is its own constant, not the debounce
/// cap's floor: the two answer different questions and may change apart.
const EMPTY_HOLD_DEADLINE: Duration = Duration::from_secs(1);

/// Whether a watched file went from non-empty to empty: the baseline saw bytes in it
/// (`before`), and it has none `now` (#380). A file the baseline never saw, saw missing or
/// saw empty — one empty from the start, or one compiled since it was emptied — has not,
/// and neither has a file that is gone.
fn went_empty(before: Option<&FileStamp>, now: &FileStamp) -> bool {
    matches!((before.and_then(|stamp| stamp.1), now.1), (Some(had), Some(0)) if had > 0)
}

/// `path`'s `(mtime, size)` now; `(None, None)` when it cannot be read.
fn stamp_now(path: &Path) -> FileStamp {
    match std::fs::metadata(path) {
        Ok(m) => (m.modified().ok(), Some(m.len())),
        Err(_) => (None, None),
    }
}

/// Whether any of `paths` went from non-empty to empty since `baseline` was taken
/// ([`went_empty`]): one `stat` per path, stopping at the first that did.
#[cfg(test)]
fn any_went_empty<'a>(paths: impl IntoIterator<Item = &'a PathBuf>, baseline: &StampMap) -> bool {
    paths
        .into_iter()
        .any(|path| went_empty(baseline.get(path), &stamp_now(path)))
}

/// Which of `paths` went from non-empty to empty since `baseline` was taken
/// ([`went_empty`]): one `stat` per path.
fn emptied_paths<'a>(
    paths: impl IntoIterator<Item = &'a PathBuf>,
    baseline: &StampMap,
) -> BTreeSet<PathBuf> {
    paths
        .into_iter()
        .filter(|path| went_empty(baseline.get(*path), &stamp_now(path)))
        .cloned()
        .collect()
}

/// The stamps a rebuild's look takes (#380): one `stat` per file of `paths`, a file named
/// more than once — a dependency several sources import — stamped once.
fn look_at<'a>(paths: impl IntoIterator<Item = &'a PathBuf>) -> StampMap {
    let mut look = StampMap::new();
    for path in paths {
        if !look.contains_key(path) {
            look.insert(path.clone(), stamp_now(path));
        }
    }
    look
}

/// The files `look` — the stamps a rebuild's look took — finds emptied since `baseline`
/// was taken ([`went_empty`]): the look's stamps are compared, nothing is `stat`ed again.
fn emptied_in<'a>(look: &'a StampMap, baseline: &'a StampMap) -> impl Iterator<Item = &'a PathBuf> {
    look.iter()
        .filter(move |(path, now)| went_empty(baseline.get(*path), now))
        .map(|(path, _)| path)
}

/// The baseline over `domain` from `taken`, the stamps taken before the rebuild read
/// anything — its look's, laid over the baseline before it (#380). Each file keeps the
/// stamp taken; only one none was taken for — a file the rebuild's compile discovered — is
/// stamped now, and a file outside `domain` is dropped. A file changed since its stamp was
/// taken — truncated after a compile read it whole, or while a rebuild was not reading it —
/// therefore still differs from the baseline, and the next look sees it: a baseline never
/// takes a file as it is after the read it describes.
fn baseline_over<'a>(
    mut taken: StampMap,
    domain: impl IntoIterator<Item = &'a PathBuf>,
) -> StampMap {
    let mut baseline = StampMap::with_capacity(taken.len());
    for path in domain {
        if baseline.contains_key(path) {
            continue;
        }
        let (path, stamp) = taken
            .remove_entry(path)
            .unwrap_or_else(|| (path.clone(), stamp_now(path)));
        baseline.insert(path, stamp);
    }
    baseline
}

/// The instant a rebuild decides its hold at: `now`, or `due` — the deadline of the hold
/// that runs it — if `now` is earlier, so that deadline ends the hold whatever the clock
/// does between the wake and the rebuild (#380).
fn not_before(now: Instant, due: Option<Instant>) -> Instant {
    due.map_or(now, |due| now.max(due))
}

/// A rebuild held while a watched file is empty, and the **absolute** deadline at which it
/// runs anyway (#380).
///
/// The deadline is set by the rebuild that first finds a watched file emptied, and never
/// moves: a later event, another truncation of the same file and an idle tick each find
/// the hold running and leave it as it is. A deadline that moved with them would let a
/// stream of events postpone the rebuild forever — the starvation #319 removed from the
/// idle tick. The hold ends at the first rebuild that finds no watched file emptied, the
/// content having been written, or at the deadline, when the files are compiled as they
/// are. Either rebuild takes the baseline again, so a file that stays empty is not
/// emptied any more, and a later truncation starts a hold of its own.
///
/// A file the rebuild's compile read can also be found emptied after the rebuild looked —
/// a truncation that began between the look and the read ([`Self::on_late_empty`]). That
/// rebuild is held as one the look found is, unless the deadline ended the hold in it: a
/// rebuild the deadline runs compiles the files as they are, and nothing found after its
/// look holds it again.
///
/// The hold never reads the clock: every instant is an argument. The rebuild that looks
/// at the files passes the instant it looked — never earlier than the deadline it is run
/// for ([`not_before`]); the watch loop's driver, [`TickClock`], waits for
/// [`Self::deadline`] and wakes the session there — under `--poll-interval 0` too, where
/// no tick would.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum EmptyHold {
    /// No rebuild is held.
    #[default]
    Off,
    /// Rebuilds are held until this instant.
    Until(Instant),
    /// The deadline ended the hold in the rebuild now running, which compiles the files as
    /// they are; no rebuild is held. The next rebuild's look decides afresh.
    Expired,
}

/// What a rebuild does, as [`EmptyHold::on_rebuild`] decides it.
#[must_use]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HoldVerdict {
    /// Compile: no watched file is emptied, or the hold's deadline has come.
    Compile,
    /// Hold the rebuild back: a watched file is emptied and the deadline is still ahead.
    Hold,
}

impl EmptyHold {
    /// A rebuild at `now` found a watched file emptied (`emptied`), or found none.
    fn on_rebuild(&mut self, emptied: bool, now: Instant) -> HoldVerdict {
        match (*self, emptied) {
            (_, false) => {
                *self = Self::Off;
                HoldVerdict::Compile
            }
            (Self::Off | Self::Expired, true) => {
                *self = Self::Until(now + EMPTY_HOLD_DEADLINE);
                HoldVerdict::Hold
            }
            (Self::Until(until), true) if now < until => HoldVerdict::Hold,
            (Self::Until(_), true) => {
                *self = Self::Expired;
                HoldVerdict::Compile
            }
        }
    }

    /// A rebuild that compiled found, at `now`, a file its compile read emptied since the
    /// rebuild looked. It is held as [`Self::on_rebuild`] holds one the look found — the
    /// deadline set by the first such finding and never moved — unless the deadline ended
    /// the hold in this rebuild, which compiles the files as they are.
    fn on_late_empty(&mut self, now: Instant) -> HoldVerdict {
        match *self {
            Self::Expired => HoldVerdict::Compile,
            Self::Off | Self::Until(_) => self.on_rebuild(true, now),
        }
    }

    /// When the held rebuild runs anyway, if a rebuild is held.
    fn deadline(&self) -> Option<Instant> {
        match *self {
            Self::Off | Self::Expired => None,
            Self::Until(until) => Some(until),
        }
    }
}

/// The files of `reads` — the byte counts a rebuild's `--vars` load and compile read
/// ([`mds::ReadLog`]) — that a read found empty and `baseline` saw with bytes
/// ([`went_empty`]): a truncation that began between the rebuild's look and the read.
///
/// The count the read gave decides, never a later `stat`. A save that truncates and then
/// writes can end between the read and that `stat`: the `stat` finds the bytes written and
/// misses the empty read, and the empty output is published (#380). A file read whole and
/// truncated after is not found here; the rebuild publishes what it read, and the next
/// look finds the file emptied.
fn read_empty(reads: &mds::ReadLog, baseline: &StampMap) -> BTreeSet<PathBuf> {
    reads
        .sizes()
        .into_iter()
        .filter(|&(_, bytes)| bytes == 0)
        .filter_map(|(key, _)| baseline_key(&graph_key(Path::new(&key)), baseline))
        .filter(|path| went_empty(baseline.get(path), &(None, Some(0))))
        .collect()
}

/// The key `baseline` holds for `path`, a file a read named ([`read_empty`]): `path`
/// itself, or, after a rename that changed only the case of a name on a file system that
/// ignores case, the key spelled as the baseline took it that names the same file. A read
/// names a file as it is spelled on disk now; the baseline keeps the spelling it was
/// taken with. `None` when the baseline has no key for the file. Only a key that differs
/// from `path` in ASCII case alone is resolved again.
fn baseline_key(path: &Path, baseline: &StampMap) -> Option<PathBuf> {
    if baseline.contains_key(path) {
        return Some(path.to_path_buf());
    }
    let spelled = path.as_os_str().as_encoded_bytes();
    baseline
        .keys()
        .filter(|key| {
            key.as_os_str()
                .as_encoded_bytes()
                .eq_ignore_ascii_case(spelled)
        })
        .find(|key| graph_key(key) == path)
        .cloned()
}

/// The late look (#380): `emptied` holds the files a rebuild found emptied after its look
/// — read empty by its `--vars` load or its compile ([`read_empty`]), or, for a batch whose
/// `--vars` load failed, `stat`ed empty. When there are any, the rebuild is held as the
/// look would have held it ([`EmptyHold::on_late_empty`], at the instant read here, once)
/// and the files are returned. `None` lets the rebuild run: no file went empty, or the
/// deadline ended the hold in this rebuild, which compiles the files as they are.
///
/// A rebuild held reports nothing and records nothing, and the baseline is left as it is —
/// as it was before a rebuild its look held, the look's stamps for one held by a file found
/// emptied after the look — so the next event or tick finds the emptied file again, and the
/// rebuild is held again or run ([`Settle::Defer`]).
#[must_use]
fn held_after_look(hold: &mut EmptyHold, emptied: BTreeSet<PathBuf>) -> Option<BTreeSet<PathBuf>> {
    if emptied.is_empty() {
        return None;
    }
    (hold.on_late_empty(Instant::now()) == HoldVerdict::Hold).then_some(emptied)
}

// ── Idle tick ─────────────────────────────────────────────────────────────────

/// The idle tick's schedule, holding an **absolute** deadline (#319).
///
/// The liveness probe is the watcher's only backstop for a change that no filesystem
/// event ever announced, so how the tick is scheduled decides whether that backstop
/// is reachable at all.
///
/// Handing `recv_timeout` a fresh `--poll-interval` budget on every message made it
/// starvable: any event stream arriving faster than the interval restarted the
/// countdown before it could expire, so the tick never fired. That is not a rare
/// condition — a compile reads its own sources and inotify reports every read, an
/// editor writes scratch files beside the one being edited, a dev server or sync
/// client touches the tree continuously, and the watch suite's own 50ms output poll
/// is 20× faster than the 1000ms default interval. Under any of them a change the
/// probe was meant to recover was lost permanently rather than delayed.
///
/// Keeping the deadline as an `Instant` pins the tick to wall-clock time instead:
/// an incoming message shortens the remaining wait rather than restarting it, so the
/// tick comes due on schedule no matter how loaded the channel is. A tick that is
/// already due is reported before any message is taken ([`TickPoll::Due`]), so a
/// channel that is never empty cannot postpone it either.
///
/// Re-arming to `now + interval` at the moment a tick is *observed* bounds it from
/// the other side. The probe — and any recompile it triggers — runs between two
/// polls, so a probe that overruns its own interval simply arms the next deadline
/// from when it finished. It can never accumulate overdue ticks and fire them
/// back-to-back: at most one tick per interval, under every load.
///
/// The schedule never reads the clock: every instant is an argument. [`TickClock`]
/// is the driver that reads it and waits on the channel.
#[derive(Debug, Clone, Copy)]
enum TickSchedule {
    /// `--poll-interval 0`: the probe is off, and no tick ever comes due.
    Off,
    /// One tick per `interval`; the next comes due at `next`.
    Every { interval: Duration, next: Instant },
}

/// What a [`TickSchedule`] says at a given instant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TickPoll {
    /// No tick will ever come due: wait for a message for as long as it takes.
    Never,
    /// The tick is due: run it before taking another message. The schedule has
    /// already re-armed one interval from the instant it was asked at.
    Due,
    /// Not due yet: wait at most this long for a message.
    Wait(Duration),
}

impl TickSchedule {
    /// The schedule of a session that starts at `now`: its first tick comes due one
    /// interval later.
    fn start(interval: Option<Duration>, now: Instant) -> Self {
        match interval {
            None => Self::Off,
            Some(interval) => Self::Every {
                interval,
                next: now + interval,
            },
        }
    }

    /// Whether the tick is due at `now`. A due tick re-arms the schedule
    /// ([`Self::rearm`]).
    fn poll(&mut self, now: Instant) -> TickPoll {
        let Self::Every { next, .. } = *self else {
            return TickPoll::Never;
        };
        if now >= next {
            self.rearm(now);
            TickPoll::Due
        } else {
            TickPoll::Wait(next - now)
        }
    }

    /// A tick was observed at `now`: the next comes due one interval after it — never
    /// one interval after the deadline it may have missed.
    fn rearm(&mut self, now: Instant) {
        if let Self::Every { interval, next } = self {
            *next = now + *interval;
        }
    }
}

/// What the watch loop's two deadlines — a held rebuild's ([`EmptyHold`]) and the idle
/// tick's ([`TickSchedule`]) — say at a given instant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WakePoll {
    /// The held rebuild's deadline has come: run it before taking another message, and
    /// before a tick due at the same instant.
    HoldDue,
    /// The tick is due: run it before taking another message. The schedule has already
    /// re-armed.
    TickDue,
    /// Nothing is due: wait at most `wait` for a message. The wait runs out at the held
    /// rebuild's deadline when `hold`, else at the tick's.
    Wait { wait: Duration, hold: bool },
    /// No deadline at all — no rebuild held, and `--poll-interval 0`: wait for a message
    /// for as long as it takes.
    Never,
}

/// The watch loop's next wake at `now`: the held rebuild's deadline `hold`, if a rebuild
/// is held, and the idle tick's `schedule`, whichever comes first (#380).
///
/// The hold is served first when both are due. Its deadline is the one a user waits on —
/// an emptied file published within a second — and the rebuild it runs takes the baseline
/// again, so a tick due at the same instant then finds nothing to do but re-arm watches.
/// A tick left due is served on the very next poll, so neither postpones the other by
/// more than one wake, and a channel that is never empty postpones neither.
fn poll_wake(schedule: &mut TickSchedule, hold: Option<Instant>, now: Instant) -> WakePoll {
    if hold.is_some_and(|until| now >= until) {
        return WakePoll::HoldDue;
    }
    let until_hold = hold.map(|until| until - now);
    match (schedule.poll(now), until_hold) {
        (TickPoll::Due, _) => WakePoll::TickDue,
        (TickPoll::Never, None) => WakePoll::Never,
        (TickPoll::Never, Some(wait)) => WakePoll::Wait { wait, hold: true },
        (TickPoll::Wait(tick), Some(wait)) if wait <= tick => WakePoll::Wait { wait, hold: true },
        (TickPoll::Wait(wait), _) => WakePoll::Wait { wait, hold: false },
    }
}

/// What wakes the watch loop ([`TickClock::recv_next`]).
enum Wake {
    /// A message arrived: a filesystem event, or Ctrl+C.
    Message(Msg),
    /// The idle tick came due ([`TickSchedule`]).
    Tick,
    /// The held rebuild's deadline came ([`EmptyHold`], #380).
    HoldDue,
}

/// Drives a [`TickSchedule`] and a held rebuild's deadline on the real clock and the watch
/// channel ([`poll_wake`]): where the watch loop waits for its next wake. It is not the
/// only reader of `Instant::now()`: the debounce window's driver ([`drain_debounce`])
/// reads it too, and so does a rebuild, for the instant it looks at the files to time a
/// hold (#380).
struct TickClock {
    schedule: TickSchedule,
}

impl TickClock {
    fn new(interval: Option<Duration>) -> Self {
        Self {
            schedule: TickSchedule::start(interval, Instant::now()),
        }
    }

    /// Wait for the next wake: a message from the watch channel, the idle tick, or `hold`
    /// — the deadline of a rebuild held while a watched file is empty (#380). A held
    /// rebuild's deadline is waited for whatever the poll interval: under
    /// `--poll-interval 0`, with no tick to wake the loop, nothing else would.
    ///
    /// `Err` means the channel disconnected; the caller stops.
    fn recv_next(
        &mut self,
        rx: &mpsc::Receiver<Msg>,
        hold: Option<Instant>,
    ) -> std::result::Result<Wake, mpsc::RecvError> {
        match poll_wake(&mut self.schedule, hold, Instant::now()) {
            WakePoll::HoldDue => Ok(Wake::HoldDue),
            WakePoll::TickDue => Ok(Wake::Tick),
            WakePoll::Never => rx.recv().map(Wake::Message),
            WakePoll::Wait { wait, hold } => match rx.recv_timeout(wait) {
                Ok(msg) => Ok(Wake::Message(msg)),
                Err(mpsc::RecvTimeoutError::Timeout) if hold => Ok(Wake::HoldDue),
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    self.schedule.rearm(Instant::now());
                    Ok(Wake::Tick)
                }
                Err(mpsc::RecvTimeoutError::Disconnected) => Err(mpsc::RecvError),
            },
        }
    }
}

// ── Debounce loop ─────────────────────────────────────────────────────────────

/// Largest accepted `--debounce` window; larger values are clamped to it.
///
/// `Instant::now() + Duration::from_millis(u64::MAX)` does not overflow on the
/// i64-second monotonic clocks of macOS and Linux: the deadline lands roughly 585
/// million years out, so an unclamped `--debounce 18446744073709551615` watches
/// forever and silently never rebuilds (observed). 60s is orders of magnitude past
/// any editor save burst.
const MAX_DEBOUNCE_MS: u64 = 60_000;

/// Absolute cap on one debounce window, as a multiple of the window.
const DEBOUNCE_CAP_FACTOR: u32 = 10;

/// Floor under the absolute cap.
///
/// Matches the default `--poll-interval`: while a window is open the loop never
/// reaches `TickClock::recv_next`, so this floor is also the bound on how late the
/// idle-tick backstop can run under a continuous event stream.
const DEBOUNCE_CAP_FLOOR: Duration = Duration::from_millis(1_000);

/// Upper bound on the messages one window will drain.
///
/// The cap bounds the window's DURATION; this bounds its work and its memory. A
/// sender faster than the drain would otherwise grow `paths` without limit inside a
/// single window. Messages left in the channel are not lost: the caller's next
/// event opens a new window and drains them.
const MAX_DEBOUNCE_MESSAGES: usize = 10_000;

/// Why a debounce window ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DebounceEnd {
    /// `--debounce 0`: coalescing is off; no window was ever opened.
    Disabled,
    /// The window closed on its own ([`DebounceWindow::classify`]).
    Closed(WindowEnd),
    /// Ctrl+C. The caller must stop, not rebuild.
    Interrupted,
    /// The watcher's sender was dropped.
    Disconnected,
}

/// Why an open [`DebounceWindow`] closed on its own.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WindowEnd {
    /// A full window passed with no further content event: the intended exit.
    Quiet,
    /// The absolute cap elapsed while events were still arriving.
    Cap,
    /// `MAX_DEBOUNCE_MESSAGES` messages were drained in this window.
    MessageLimit,
}

/// Result of one debounce window.
struct DebounceOutcome {
    /// Every path seen in a content event during the window.
    paths: BTreeSet<PathBuf>,
    /// Whether an event of the window said events were lost ([`notify::Event::need_rescan`]).
    rescan: bool,
    /// Why the window ended.
    end: DebounceEnd,
}

impl DebounceOutcome {
    fn interrupted(&self) -> bool {
        self.end == DebounceEnd::Interrupted
    }
}

/// Convert a raw `--debounce` value (milliseconds) into a quiet-period window.
///
/// - `0` -> `None`: coalescing disabled, every event rebuilds immediately.
/// - nonzero -> `Some(min(value, MAX_DEBOUNCE_MS))`.
///
/// Extracted so the clamp contract is verifiable without the watch loop, exactly as
/// [`clamp_poll_interval`] is.
fn clamp_debounce(debounce_ms: u64) -> Option<Duration> {
    if debounce_ms == 0 {
        None
    } else {
        Some(Duration::from_millis(debounce_ms.min(MAX_DEBOUNCE_MS)))
    }
}

/// Absolute bound on one debounce window: `max(10 x window, 1s)`.
///
/// `window * DEBOUNCE_CAP_FACTOR` cannot overflow `Duration`: [`clamp_debounce`] caps
/// the window at 60s, so the product is at most 600s.
fn debounce_cap(window: Duration) -> Duration {
    (window * DEBOUNCE_CAP_FACTOR).max(DEBOUNCE_CAP_FLOOR)
}

/// One open debounce window: a quiet period with an absolute cap and a message limit
/// (see [`drain_debounce`] for why each rule exists).
///
/// It never reads the clock: every instant is an argument. [`drain_debounce`] is the
/// driver that reads it and waits on the channel.
struct DebounceWindow {
    /// The quiet period every content event restarts.
    window: Duration,
    /// `start + debounce_cap(window)`: no event extends the window past it.
    cap_end: Instant,
    /// When the window closes unless a content event extends it; never past `cap_end`.
    deadline: Instant,
    /// Messages drained so far, of every kind.
    messages: usize,
    /// Every path seen in a content event.
    paths: BTreeSet<PathBuf>,
    /// Whether an event said events were lost.
    rescan: bool,
}

impl DebounceWindow {
    /// A window opened at `start`: it closes one window later unless a content event
    /// extends it, and never after `start + debounce_cap(window)`.
    fn open(window: Duration, start: Instant) -> Self {
        Self {
            window,
            cap_end: start + debounce_cap(window),
            deadline: start + window,
            messages: 0,
            paths: BTreeSet::new(),
            rescan: false,
        }
    }

    /// A filesystem event drained at `now`. It counts toward the message limit; a
    /// content event also contributes its paths and whether it says events were lost, and
    /// extends the window ([`Self::on_content`]). An `Access` event does neither (inotify
    /// IN_ACCESS/IN_OPEN/IN_CLOSE_NOWRITE — reads must not trigger recompiles; see
    /// [`is_content_event`]).
    fn on_event(&mut self, event: notify::Event, now: Instant) {
        self.messages += 1;
        if !is_content_event(&event.kind) {
            return;
        }
        self.rescan |= event.need_rescan();
        self.paths.extend(event.paths);
        self.on_content(now);
    }

    /// A watch error was drained: it counts toward the message limit and extends
    /// nothing.
    fn on_watch_error(&mut self) {
        self.messages += 1;
    }

    /// A content event at `now`: the window now closes one window after it, but never
    /// after the cap end.
    fn on_content(&mut self, now: Instant) {
        self.deadline = (now + self.window).min(self.cap_end);
    }

    /// When the window closes unless a content event extends it.
    fn deadline(&self) -> Instant {
        self.deadline
    }

    /// Whether the window has closed by `now`, and why. `None`: it is still open, so
    /// wait for a message until [`Self::deadline`].
    fn classify(&self, now: Instant) -> Option<WindowEnd> {
        // The bound, enforced in release too: a window may be extended by further
        // events, never past `start + cap`. Pure arithmetic: a descheduled runner
        // cannot trip it, only a defect can. Asserting on MEASURED elapsed time
        // instead would panic a shipped watcher whenever `recv_timeout` overshoots.
        assert!(
            self.deadline <= self.cap_end,
            "debounce deadline escaped its cap: a file written to continuously would \
             postpone its own rebuild (and the idle-tick backstop behind it) for as \
             long as the writing lasts"
        );
        if self.messages >= MAX_DEBOUNCE_MESSAGES {
            Some(WindowEnd::MessageLimit)
        } else if now < self.deadline {
            None
        } else if self.deadline == self.cap_end {
            Some(WindowEnd::Cap)
        } else {
            Some(WindowEnd::Quiet)
        }
    }
}

/// Coalesce a burst of filesystem events into one rebuild.
///
/// # Quiet period, not a fixed window
///
/// The first relevant event opens a window of `debounce_ms`; every further **content**
/// event restarts it. A window that expired at a fixed offset from the FIRST event
/// split any burst longer than `debounce_ms` across two or three windows and rebuilt
/// once per window, each compile seeing a different intermediate state of the file:
/// visible as three `Recompiled` lines from one ten-write burst on a loaded CI runner.
/// The size of the burst a user can produce is not a property `debounce_ms` can
/// predict; the size of the GAP between saves is.
///
/// # Why the cap is mandatory
///
/// An extendable window with no bound is unbounded: a file written to continuously
/// postpones its own rebuild for as long as the writing lasts. Worse, the idle-tick
/// liveness probe is not consulted while a window is open ([`TickClock::recv_next`] is
/// only reached between batches), so an endless stream would starve the content
/// backstop through a door the absolute tick deadline does not cover. The cap
/// (`max(10 x window, 1s)`) bounds both: the rebuild, and the probe behind it.
///
/// # What does NOT extend
///
/// `Access` events (inotify reads; see [`is_content_event`]) and watch errors. The
/// compile reads its own sources, so an extending `Access` event would let the watcher
/// hold its own window open.
///
/// Relevance is deliberately NOT filtered here. An editor's atomic save writes a temp
/// file and renames it; that temp path is in no watch set, and ending the window on it
/// would split the very burst this exists to coalesce. Relevance decides whether to
/// rebuild ([`event_is_relevant`] in file mode, the `.mds`/root filter in dir mode);
/// this decides when.
fn drain_debounce(rx: &mpsc::Receiver<Msg>, debounce_ms: u64) -> DebounceOutcome {
    let Some(window) = clamp_debounce(debounce_ms) else {
        // `--debounce 0`: no coalescing. The channel is left untouched, so the next
        // event is delivered to the loop as its own batch.
        return DebounceOutcome {
            paths: BTreeSet::new(),
            rescan: false,
            end: DebounceEnd::Disabled,
        };
    };

    // The window decides; this loop only reads the clock and waits on the channel.
    // Bounded by the window: it closes at its cap end or its message limit.
    let mut open = DebounceWindow::open(window, Instant::now());
    let end = loop {
        let now = Instant::now();
        if let Some(closed) = open.classify(now) {
            break DebounceEnd::Closed(closed);
        }
        match rx.recv_timeout(open.deadline() - now) {
            Ok(Msg::Fs(Ok(event))) => open.on_event(event, Instant::now()),
            Ok(Msg::Fs(Err(e))) => {
                open.on_watch_error();
                eprint_warning(&format!(
                    "warning: watch error during debounce: {}",
                    safe_inline(notify_cause(&e))
                ));
            }
            Ok(Msg::Interrupt) => break DebounceEnd::Interrupted,
            // The deadline is the single decision point: re-loop and let the window
            // classify the exit.
            Err(mpsc::RecvTimeoutError::Timeout) => {}
            Err(mpsc::RecvTimeoutError::Disconnected) => break DebounceEnd::Disconnected,
        }
    };

    DebounceOutcome {
        paths: open.paths,
        rescan: open.rescan,
        end,
    }
}

// ── Poll-interval clamp (reconcile rule) ─────────────────────────────────────────────

/// Convert a raw `--poll-interval` value (milliseconds) into a tick duration.
///
/// - `0` → `None` (blocking `recv`, no liveness probe)
/// - nonzero → `Some(max(value, 50ms))` — floor prevents a busy-spin liveness probe
///
/// Extracted so the clamp contract can be verified by unit tests independently of
/// the full watch loop.
fn clamp_poll_interval(poll_interval: u64) -> Option<Duration> {
    if poll_interval == 0 {
        None
    } else {
        Some(Duration::from_millis(poll_interval.max(50)))
    }
}

// ── Working directory ─────────────────────────────────────────────────────────

/// The working directory `mds watch` started in, by its canonical path.
///
/// Every path typed relative — the entry, a directory argument such as `.`, `--vars`, a
/// file-mode `-o` — is resolved against the process's working directory on every
/// rebuild. Once that directory is deleted, the process is left in it, and none of them
/// resolves again, even after a directory is recreated at the same path, as a
/// `git checkout` that removes and restores it does (#417).
/// [`restore_if_recreated`](Self::restore_if_recreated) moves the process back into it.
struct WorkingDir {
    /// `None` when the working directory did not resolve at startup: nothing is restored.
    canonical: Option<PathBuf>,
}

impl WorkingDir {
    /// Record the working directory at startup, before any rebuild reads a path typed
    /// relative to it.
    fn record() -> Self {
        WorkingDir {
            canonical: std::env::current_dir()
                .and_then(|dir| dir.canonicalize())
                .ok(),
        }
    }

    /// Called first by every rebuild, before it reads anything. When the working
    /// directory has been deleted and a directory exists again at its recorded canonical
    /// path, reached through no symlink (canonical compared with canonical, #408), it
    /// becomes the working directory again. A working directory that still exists is
    /// never changed. Otherwise nothing changes, and a path typed relative that does not
    /// resolve is reported as typed by the read that needs it, as any missing file is.
    ///
    /// A directory swapped in between the check and the move is the check-then-open
    /// window every path-based read has; the compile checks that the path it compiles
    /// still leads to the file being watched either way
    /// ([`WatchedPath::ensure_unmoved`]).
    fn restore_if_recreated(&self) {
        let Some(recorded) = &self.canonical else {
            return;
        };
        if std::env::current_dir().is_ok() {
            return;
        }
        if recorded.canonicalize().is_ok_and(|now| now == *recorded) {
            // A failure leaves the process where it was; see above.
            let _ = std::env::set_current_dir(recorded);
        }
    }
}

// ── The out-dir during a session (#160) ───────────────────────────────────────

/// What a write finds where the out-dir was ([`OutDirAnchor::check`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OutDirNow {
    /// The directory the session last saw there.
    Unchanged,
    /// No directory, or a different one at the same path — deleted, or another put in its
    /// place: the write creates or uses it, and no output the session wrote is in it.
    New,
    /// The path the user named now leads to a different directory: the write is refused.
    Elsewhere,
}

/// The out-dir a `mds watch` session writes below, as it was when the session started
/// (#160): `--out-dir`, or `mds.json`'s `build.output_dir` below the directory `mds.json`
/// is in.
///
/// Every write below it first resolves the path the user named again — `--out-dir` as
/// typed, or the directory `mds.json` was reached by — as the write would create it, and
/// compares the result with the one resolved when the session started, canonical with
/// canonical (#408). A different directory — a symlink on the path retargeted, the out-dir
/// replaced by a link, or the working directory a relative one is typed against moved —
/// refuses the write: the session writes only where it started, and following the path
/// elsewhere is for a restart to decide. The same
/// path is written below whatever directory is there: a deleted out-dir is created again
/// by the write, a directory put in its place is used, and either becomes the one the
/// next write compares; none of the outputs the session wrote is in it, so the content
/// dedup is cleared and none is skipped as written already. Nothing is held open between
/// writes.
///
/// The check is by path, and so is the write's open of its anchor, so a link swapped onto
/// the path between the two would lead the open elsewhere: the check also finds the
/// directory the write is anchored at — `resolved`, or the nearest directory above it
/// that is there when it is missing — and the write is made only if the anchor it opens
/// is that directory ([`below_checked_out_dir`]).
struct OutDirAnchor {
    /// The path the user named: `--out-dir` as typed, or the directory `mds.json` was
    /// reached by.
    typed: PathBuf,
    /// Where `typed` led when the session started, as a write would create it: the
    /// directory a write below the out-dir is anchored at.
    resolved: PathBuf,
    /// The directory outputs are written below: `resolved`, or `build.output_dir` below it.
    out_dir: PathBuf,
    /// The directory the session last saw at `out_dir`; `None` while there was none.
    identity: Option<DirIdentity>,
    /// Where the last check found the directory the next write is anchored at; `None`
    /// before the first check and after one that refused the write.
    checked: Option<CheckedAnchor>,
}

/// The directory a write below the out-dir is anchored at, as [`OutDirAnchor::check`]
/// found it: `resolved` itself, or — when it is missing, and the write is to create it —
/// the nearest directory above it that is there, `missing` levels up.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct CheckedAnchor {
    missing: usize,
    identity: DirIdentity,
}

impl CheckedAnchor {
    /// `dir`, or the nearest directory above it that is there; `None` when none is.
    fn find(dir: &Path) -> Option<Self> {
        dir.ancestors().enumerate().find_map(|(missing, at)| {
            DirIdentity::of(at).map(|identity| Self { missing, identity })
        })
    }
}

impl OutDirAnchor {
    /// The out-dir a session writes below, recorded once its startup writes are made:
    /// `--out-dir`, else `build.output_dir`. `None` for neither — an output beside its
    /// source is below the watched entry's or root's directory, which every compile
    /// checks ([`WatchedPath::ensure_unmoved`]) — and for a working directory that does
    /// not resolve.
    fn record(out_dir: Option<&Path>, config: Option<&ProjectConfig>) -> Option<Self> {
        let (typed, below) = match (out_dir, config) {
            (Some(typed), _) => (typed.to_path_buf(), None),
            (None, Some(project)) => (
                project.shown_dir.clone(),
                Some(project.config.build.output_dir.as_deref()?),
            ),
            (None, None) => return None,
        };
        let resolved = resolve_dir_as_created(&typed)?;
        let out_dir = below.map_or_else(|| resolved.clone(), |below| resolved.join(below));
        let identity = DirIdentity::of(&out_dir);
        Some(Self {
            typed,
            resolved,
            out_dir,
            identity,
            checked: None,
        })
    }

    /// What the out-dir is now ([`OutDirNow`]). A directory that is not the one last seen
    /// becomes the one the next check compares.
    ///
    /// The directory the write is anchored at is found first and the path the user named
    /// resolved after: a link swapped in before then changes where that path leads, and
    /// one swapped in after it leads the write's open to another directory than the one
    /// found here, which the write refuses.
    fn check(&mut self) -> OutDirNow {
        self.checked = CheckedAnchor::find(&self.resolved);
        if self.checked.is_none()
            || resolve_dir_as_created(&self.typed).as_ref() != Some(&self.resolved)
        {
            self.checked = None;
            return OutDirNow::Elsewhere;
        }
        let now = DirIdentity::of(&self.out_dir);
        if now.is_some() && now == self.identity {
            OutDirNow::Unchanged
        } else {
            self.identity = now;
            OutDirNow::New
        }
    }

    /// A write below the out-dir succeeded: the directory it created, if it found none,
    /// is the one the next check compares.
    fn written(&mut self) {
        if self.identity.is_none() {
            self.identity = DirIdentity::of(&self.out_dir);
        }
    }
}

/// The out-dir as it is now (#160), for a session with none treated as
/// [`OutDirNow::Unchanged`]: one the typed path leads elsewhere from refuses the write
/// below; a new one holds nothing the session wrote, so `last_written` is cleared.
fn check_out_dir<K, V>(
    anchor: Option<&mut OutDirAnchor>,
    last_written: &mut HashMap<K, V>,
) -> OutDirNow {
    let now = anchor.map_or(OutDirNow::Unchanged, OutDirAnchor::check);
    if now == OutDirNow::New {
        last_written.clear();
    }
    now
}

/// `target`, a write below the out-dir after a check that admitted it, made below the
/// directory that check found and only if the anchor the write opens is that directory
/// (#160): a link swapped onto the path in between is refused, not followed. A session
/// with no out-dir writes `target` as it is.
fn below_checked_out_dir(anchor: Option<&OutDirAnchor>, target: &WriteTarget) -> WriteTarget {
    match anchor.and_then(|anchor| Some((anchor, anchor.checked?))) {
        Some((anchor, CheckedAnchor { missing, identity })) => {
            target.below_checked_anchor(&anchor.resolved, missing, identity)
        }
        None => target.clone(),
    }
}

/// Why a session retires one of its outputs (#160), which decides how a removal is told.
#[derive(Clone, Copy)]
enum Retirement {
    /// Its source was deleted: a removal prints `Removed <output> (source deleted)`.
    SourceDeleted,
    /// Its source now compiles to the other kind, whose output was just written: a
    /// removal is silent, as cleaning up after a change of kind always was.
    KindChanged,
}

/// What a directory-mode session wrote at one of its output paths, and for which source
/// (#160): what a later write of the same may skip, the bytes a removal or a replace asks
/// the file to still hold, and whose output the file is — beside their sources `a.b.mds`
/// and `a.mds` both name theirs `a.md` or `a.json`.
#[derive(Debug, Clone, PartialEq, Eq)]
struct WrittenOutput {
    /// The source the output was written for.
    source: PathBuf,
    /// The bytes written.
    content: String,
}

/// What a session's record says of the file at one of its output paths, for the source a
/// removal or a write after a change of kind is made for (#160).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Record<'a> {
    /// No record: the session never wrote there, not since the out-dir was made, or the
    /// file it wrote is gone.
    Unwritten,
    /// The session last wrote there for another source.
    OtherSource,
    /// The session last wrote these bytes there for this source.
    Own(&'a str),
}

impl<'a> Record<'a> {
    /// The record of a file-mode session, whose one source is the entry: what it last
    /// wrote there, if anything.
    fn of_entry(written: Option<&'a String>) -> Self {
        written.map_or(Self::Unwritten, |content| Self::Own(content))
    }
}

/// Retire `out`, an output its source no longer has (#160). `record` is what this
/// session's record says of the file there for that source, and `now` what the out-dir
/// check made before this found.
///
/// The file is removed only if this session wrote it for that source and it still holds
/// exactly those bytes, and only as every deletion below the out-dir is made: below the
/// directory that check found ([`below_checked_out_dir`]) — one the typed path leads
/// elsewhere from refuses the removal — through no symlink and only as a regular file
/// ([`remove_proven`]). A file this session did not write, one it wrote for another
/// source, and one changed since it was written are kept, with one notice saying which
/// (none under `--quiet`). A name nothing has is not mentioned; a symlink there, live or
/// dangling, is something there, and the session's own is refused with a warning.
///
/// Returns whether the file is gone — removed, or not there — so that the record of it
/// can go too; a file kept, one whose removal failed, and one that could not be looked at
/// keep their records.
#[must_use]
fn retire_output(
    out: &WriteTarget,
    anchor: Option<&OutDirAnchor>,
    now: OutDirNow,
    record: Record<'_>,
    why: Retirement,
    quiet: bool,
) -> bool {
    // Looked at without following a symlink: a link at the output, live or dangling, is
    // something there, and refused below as one. Only a name that is not there is gone; a
    // look that fails otherwise — a directory on its way that may not be searched, say —
    // leaves the file perhaps there, so its removal is tried as any other's, and a failure
    // reported, the record kept.
    if let Err(e) = std::fs::symlink_metadata(&out.path) {
        if matches!(
            e.kind(),
            std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
        ) {
            return true;
        }
    }
    let written = match record {
        Record::Own(written) => written,
        Record::Unwritten => {
            if !quiet {
                crate::output::ewriteln!(
                    "Kept {}: not written by this session",
                    safe_path(&out.shown)
                );
            }
            return false;
        }
        Record::OtherSource => {
            if !quiet {
                crate::output::ewriteln!(
                    "Kept {}: not written by this source",
                    safe_path(&out.shown)
                );
            }
            return false;
        }
    };
    let removal = match now {
        OutDirNow::Elsewhere => Err(NotRemoved::out_dir_moved()),
        OutDirNow::Unchanged | OutDirNow::New => {
            remove_proven(&below_checked_out_dir(anchor, out), |file| {
                holds_exactly(file, written)
            })
        }
    };
    match removal {
        Ok(Removal::Removed) => {
            if let (Retirement::SourceDeleted, false) = (why, quiet) {
                crate::output::ewriteln!("Removed {} (source deleted)", safe_path(&out.shown));
            }
            true
        }
        Ok(Removal::Kept) => {
            if !quiet {
                crate::output::ewriteln!(
                    "Kept {}: changed since it was written",
                    safe_path(&out.shown)
                );
            }
            false
        }
        Ok(Removal::Missing) => true,
        Err(not_removed) => {
            match why {
                Retirement::SourceDeleted => eprint_warning(&format!(
                    "warning: could not remove {}: {}",
                    safe_path(&out.shown),
                    safe_inline(not_removed.cause())
                )),
                Retirement::KindChanged => eprint_warning(&format!(
                    "warning: could not remove stale output {}: {}",
                    safe_path(&out.shown),
                    safe_inline(not_removed.cause())
                )),
            }
            false
        }
    }
}

/// Write `content` to `out`, the output of a source's new kind after a change of kind
/// (#160) — `record`, what this session's record says of the file there for that source
/// — only where nothing is, or over the file this session wrote there for that source
/// while it still holds exactly those bytes ([`write_over_own`]), as an output is
/// written: below the directory the caller's out-dir check found, with the directories it
/// goes in created. Anything else there — a file this session did not write, one it wrote
/// for another source, one changed since, a symlink, a directory — is kept, with one
/// notice saying which (none under `--quiet`, and none when `told`: the rebuild of the
/// same source just before kept the same content), and nothing is written: `Ok(false)`,
/// so a later save tries again. The output of the old kind is the caller's to retire, and
/// only once the new one is written.
fn write_after_change_of_kind(
    out: &WriteTarget,
    record: Record<'_>,
    content: &str,
    told: bool,
    quiet: bool,
) -> std::result::Result<bool, MdsError> {
    let own = match record {
        Record::Own(written) => Some(written),
        Record::Unwritten | Record::OtherSource => None,
    };
    match write_over_own(out, own, content, Durability::RenameOnly, Parents::Create) {
        Ok(()) => Ok(true),
        Err(NotCreated::Exists) => {
            if !told && !quiet {
                match record {
                    Record::Own(_) => crate::output::ewriteln!(
                        "Kept {}: changed since it was written; not overwritten",
                        safe_path(&out.shown)
                    ),
                    Record::OtherSource => crate::output::ewriteln!(
                        "Kept {}: not written by this source; not overwritten",
                        safe_path(&out.shown)
                    ),
                    Record::Unwritten => crate::output::ewriteln!(
                        "Kept {}: not written by this session; not overwritten",
                        safe_path(&out.shown)
                    ),
                }
            }
            Ok(false)
        }
        Err(NotCreated::Failed(e)) => Err(e),
    }
}

/// Whether `file` holds exactly `written`: read no further than one byte past it.
fn holds_exactly(file: &mut std::fs::File, written: &str) -> std::io::Result<bool> {
    let len = written.len() as u64;
    Ok(mds::read_at_most(file, len.saturating_add(1), len)? == written.as_bytes())
}

// ── Watched paths ─────────────────────────────────────────────────────────────

/// What a [`WatchedPath`] is: it decides how the typed form is resolved and how a
/// refusal names it.
#[derive(Clone, Copy)]
enum Watched {
    /// File mode's entry.
    Entry,
    /// Directory mode's root.
    Root,
    /// A source below directory mode's root, by its walked path.
    Source,
}

impl Watched {
    /// The refusal once `typed`, a path of this kind, leads somewhere other than the
    /// watched file or directory: `mds::io`, naming the path as typed, escaped — never by
    /// its canonical absolute path (#417, #413).
    fn moved(self, typed: &Path) -> MdsError {
        let (watched, different) = match self {
            Watched::Entry => ("entry", "file"),
            Watched::Root => ("directory", "directory"),
            Watched::Source => ("file", "file"),
        };
        MdsError::Io {
            message: format!(
                "watched {watched} now resolves to a different {different}: \"{}\"; \
                 restart mds watch to follow it",
                mds::escape_path_for_message(&typed.to_string_lossy())
            ),
        }
    }
}

/// A path `mds watch` holds in two forms (#417, #413): file mode's entry, directory
/// mode's root, or a source below that root — one type, checked by one rule.
///
/// `typed` is the path as the user reaches it: as typed, or for a source the root as
/// typed joined with the source's path below it, the form `mds build <dir>` walks. Every
/// compile goes through it, so an error names the file that way, never by its canonical
/// absolute path (#417, #265), `mds.json` is looked up from it at startup (#413), and
/// every status line names the path, and an output resolved beside or below it, that
/// way (#390).
/// `canonical` is the form notify reports event paths under: every identity check —
/// watched directories, files of interest, graph keys, output paths, baselines — uses
/// it. The two are never compared as text (#408):
/// [`ensure_unmoved`](Self::ensure_unmoved) resolves `typed` again and compares the
/// result with `canonical`, canonical with canonical.
struct WatchedPath {
    typed: PathBuf,
    canonical: PathBuf,
    what: Watched,
}

impl WatchedPath {
    /// The entry in the form [`admit_output`] takes, typed first, so the two forms
    /// cannot be handed over swapped.
    fn paths(&self) -> EntryPaths<'_> {
        EntryPaths {
            typed: &self.typed,
            canonical: &self.canonical,
        }
    }

    /// Refuse a path whose lookup fails, with that lookup's error and the typed path.
    /// Refuse a root that resolves to another directory with [`Watched::moved`].
    /// For an entry or source, compare its resolved parent with the watched canonical parent.
    /// A file name with different case in the same canonical directory is not a move.
    /// Each compile also pins that canonical parent during entry resolution.
    fn ensure_unmoved(&self) -> Result<(), MdsError> {
        let moved = match self.what {
            Watched::Root => {
                let now = self.typed.canonicalize().map_err(|e| {
                    let shown =
                        mds::escape_path_for_message(&self.typed.to_string_lossy()).into_owned();
                    if e.kind() == std::io::ErrorKind::NotFound {
                        MdsError::FileNotFound {
                            path: shown,
                            span: None,
                            src: None,
                        }
                    } else {
                        MdsError::Io {
                            message: format!(
                                "cannot resolve path {shown}: {}",
                                safe_inline(crate::output::io_cause(&e))
                            ),
                        }
                    }
                })?;
                now != self.canonical
            }
            Watched::Entry | Watched::Source => {
                mds::NativeFs::check_symlink(&self.typed)?.parent() != self.canonical.parent()
            }
        };
        if moved {
            Err(self.what.moved(&self.typed))
        } else {
            Ok(())
        }
    }

    /// Compile the entry, or a source, by its typed path once
    /// [`ensure_unmoved`](Self::ensure_unmoved) has confirmed that it still leads to the
    /// file being watched. `mds watch` writes no source maps, so the compile takes the
    /// default options. A panic in the compile is caught: the session goes on (#389).
    fn compile(
        &self,
        runtime_vars: Option<HashMap<String, mds::Value>>,
        quiet: bool,
        reads: &Arc<mds::ReadLog>,
    ) -> std::result::Result<CompileOutput, CompileFailure> {
        self.ensure_unmoved().map_err(miette::Error::from)?;
        compile_caught(&self.typed, &self.canonical, runtime_vars, quiet, reads)
    }

    /// The root in the two forms an output below it is resolved and named by: walked
    /// canonical, named as typed (#390).
    fn root_paths(&self) -> RootPaths<'_> {
        RootPaths {
            typed: &self.typed,
            walked: &self.canonical,
        }
    }

    /// The directory of the entry in the same two forms: the canonical directory notify
    /// watches, named by the entry's directory as typed (#390).
    fn dir_paths(&self) -> RootPaths<'_> {
        RootPaths {
            typed: mds::effective_parent(&self.typed),
            walked: mds::effective_parent(&self.canonical),
        }
    }

    /// The path `src` (a walked or graph-key path under the root's `canonical`) is
    /// compiled by: the form its output is named below the root by, too.
    ///
    /// A source outside the root — an out-of-root dependency (DD3) — has no walked
    /// form and is compiled by its canonical path.
    fn walked(&self, src: &Path) -> PathBuf {
        self.root_paths().shown_below(src)
    }

    /// Compile `src` below the root — every directory-mode compile goes through here.
    ///
    /// A source under the root is compiled as a [`Watched::Source`] by its
    /// [walked](Self::walked) path, keyed by `src`, after the root itself: a moved root
    /// is refused naming the root, and a directory moved below it naming the source. The
    /// startup walk skips symlinked directories, but a rebuild compiles the sources it
    /// already knows, and the idle tick's content check follows a link — so a directory
    /// below the root replaced by a symlink after startup is caught at the source. `src`
    /// is canonical: a key the walk of the canonical root produced, or a graph key. An
    /// out-of-root dependency is compiled by its canonical path, with no walked form to
    /// check.
    fn compile_source(
        &self,
        src: &Path,
        runtime_vars: Option<HashMap<String, mds::Value>>,
        quiet: bool,
        reads: &Arc<mds::ReadLog>,
    ) -> std::result::Result<CompileOutput, CompileFailure> {
        if !src.starts_with(&self.canonical) {
            return compile_caught(src, src, runtime_vars, quiet, reads);
        }
        self.ensure_unmoved().map_err(miette::Error::from)?;
        WatchedPath {
            typed: self.walked(src),
            canonical: src.to_path_buf(),
            what: Watched::Source,
        }
        .compile(runtime_vars, quiet, reads)
    }
}

/// Why a watch compile gave no output. Either way the file counts as failed, and the
/// session keeps watching.
#[derive(Debug)]
enum CompileFailure {
    /// The compile's error, or the refusal of a path that no longer leads to the watched
    /// file — still to be reported.
    Error(miette::Report),
    /// The compile panicked. The panic hook has reported it, and the session exits 101
    /// when it stops (#389).
    Panicked,
}

impl CompileFailure {
    /// The error to report: none for a panic, which the panic hook reported.
    fn into_report(self) -> Option<miette::Report> {
        match self {
            Self::Error(e) => Some(e),
            Self::Panicked => None,
        }
    }
}

impl From<miette::Report> for CompileFailure {
    fn from(e: miette::Report) -> Self {
        Self::Error(e)
    }
}

/// Compile the file at `path` with the default options: `mds watch` writes no source
/// maps. Every file the compile reads is recorded in `reads` with its byte count
/// ([`mds::ReadLog`]), for the late look ([`held_after_look`]). The one place a watch
/// compile runs, so the one place a panic in it is caught and the session goes on (#389).
fn compile_caught(
    path: &Path,
    canonical: &Path,
    runtime_vars: Option<HashMap<String, mds::Value>>,
    quiet: bool,
    reads: &Arc<mds::ReadLog>,
) -> std::result::Result<CompileOutput, CompileFailure> {
    let fs = mds::NativeFs::new()
        .with_entry_pin(mds::EntryPin::parent_dir(mds::effective_parent(canonical)))
        .with_read_log(Arc::clone(reads));
    pause_before_compile();
    let compiled = crate::output::catch_compile(
        path,
        AssertUnwindSafe(|| {
            compile_native_to_content(
                fs,
                path,
                runtime_vars,
                quiet,
                mds::CompileOptions::default(),
            )
        }),
    );
    compiled
        .map_err(|Panicked| CompileFailure::Panicked)?
        .map_err(CompileFailure::from)
}

// ── Entry point ───────────────────────────────────────────────────────────────

pub(crate) fn run_watch(args: WatchArgs) -> Result<()> {
    let WatchArgs {
        input,
        output,
        out_dir,
        vars,
        set_vars,
        set_string_vars,
        clear,
        debounce,
        quiet,
        poll_interval,
    } = args;

    // #265, #390: refuse a hostile output location before anything is read or compiled.
    let output =
        crate::build::reject_forbidden_output_flags(output.as_deref(), out_dir.as_deref())?;

    // ── Input mode dispatch ───────────────────────────────────────────────────

    // Reject stdin.
    if input.as_deref() == Some(Path::new("-")) {
        return Err(miette::miette!(
            "watch does not support stdin ('-'); use 'mds build -' instead"
        ));
    }

    // Resolve the input path (may trigger auto-detect).
    let resolved_input = match input {
        None => auto_detect_mds_file("watch")?,
        Some(p) => p,
    };

    let is_dir = resolved_input.is_dir();

    // Directory mode constraint checks.
    if is_dir && output.is_some() {
        return Err(miette::miette!(
            "watch directory mode does not support -o/--output; \
             use --out-dir to specify an output directory"
        ));
    }

    // Clamp poll_interval: 0 = disable; nonzero ≥ 50ms floor (reconcile rule).
    let tick_opt: Option<Duration> = clamp_poll_interval(poll_interval);

    let session_args = SessionArgs {
        out_dir,
        vars,
        set_vars,
        set_string_vars,
        clear,
        debounce_ms: debounce,
        quiet,
        tick: tick_opt,
    };

    if is_dir {
        // #413: the one directory-argument check every directory-mode subcommand makes
        // (a symlink, the filesystem root, a forbidden character — all `mds::io`). It
        // takes `.`, `..` and `sub/..`, which `check_symlink` cannot, and returns the
        // canonical form notify reports event paths under.
        let canonical = crate::input::resolve_directory_argument(&resolved_input)
            .map_err(miette::Error::from)?;
        run_watch_dir(
            WatchedPath {
                typed: resolved_input,
                canonical,
                what: Watched::Root,
            },
            session_args,
        )
    } else {
        // Reject a symlinked entry (build parity — PF-004); plain canonicalize would
        // silently follow it. check_symlink returns the canonical path for
        // non-symlinks, preserving FSEvents path-matching.
        let canonical =
            mds::NativeFs::check_symlink(&resolved_input).map_err(miette::Error::from)?;
        run_watch_file(
            WatchedPath {
                typed: resolved_input,
                canonical,
                what: Watched::Entry,
            },
            output,
            session_args,
        )
    }
}

/// What a watch session runs with besides what it watches, as `mds watch`'s options give
/// it (#256).
struct SessionArgs {
    /// `--out-dir`.
    out_dir: Option<PathBuf>,
    /// `--vars`, as typed.
    vars: Option<PathBuf>,
    /// `--set`'s values.
    set_vars: Vec<(String, String)>,
    /// `--set-string`'s values.
    set_string_vars: Vec<(String, String)>,
    /// `--clear`.
    clear: bool,
    /// `--debounce`, in milliseconds.
    debounce_ms: u64,
    /// `--quiet`.
    quiet: bool,
    /// The idle tick's interval; `None` when `--poll-interval 0` turned it off.
    tick: Option<Duration>,
}

// ── Live session ──────────────────────────────────────────────────────────────

/// The live half of a watch session (#256): going live, the watch loop, and the session's
/// last status line. A mode's startup hands [`live::run_session`] the channel its watcher
/// sends on and a [`live::Session`] — what a tick and a message do — once every watch it
/// can arm is armed and every baseline taken. Going live is reached only through
/// [`live::run_session`], which runs the loop straight after it.
mod live {
    use std::ops::ControlFlow;
    use std::sync::mpsc;
    use std::time::{Duration, Instant};

    use super::{emit_ready_marker, stop_watching, Msg, StopReason, TickClock, Wake};

    /// What a live watch session does when the loop wakes it: each says whether the
    /// session goes on or stops, and why.
    pub(super) trait Session {
        /// Whether the session runs under `--quiet`, which leaves out its last status line.
        fn is_quiet(&self) -> bool;

        /// When the rebuild the session holds while a watched file is empty runs anyway, if
        /// it holds one (#380): the loop wakes it there ([`Self::on_hold_due`]).
        fn hold_deadline(&self) -> Option<Instant>;

        /// The idle tick came due ([`TickClock`]): the liveness probe (reconcile rule).
        fn on_tick(&mut self) -> ControlFlow<StopReason>;

        /// The held rebuild's deadline came (#380): rebuild, compiling the files as they
        /// are. The rebuild ends the hold — the loop wakes for a deadline that has come at
        /// once, so one left standing would never let it wait.
        fn on_hold_due(&mut self) -> ControlFlow<StopReason>;

        /// A message arrived — a filesystem event, or Ctrl+C. `rx` is the channel it came
        /// on, which a debounce window drains.
        fn on_message(&mut self, msg: Msg, rx: &mpsc::Receiver<Msg>) -> ControlFlow<StopReason>;
    }

    /// Go live ([`go_live`]), watch until `session` stops, then print its last status line
    /// ([`stop_watching`]). `tx` is the sender the watcher was armed with, kept until the
    /// loop has ended.
    pub(super) fn run_session(
        tx: mpsc::Sender<Msg>,
        rx: mpsc::Receiver<Msg>,
        tick: Option<Duration>,
        mut session: impl Session,
    ) {
        go_live(&tx);
        let why = watch_loop(&rx, tick, &mut session);
        stop_watching(session.is_quiet(), why);
    }

    /// The session is live: Ctrl+C is wired, every watched directory is armed and every
    /// baseline captured.
    ///
    /// From here on a rebuild's output failure is reported as it happens and never changes
    /// how the session exits: the exit funnel applies its watch-session rule (#157). Only
    /// then is the readiness marker written, so a test that sees the marker sees a live
    /// session.
    fn go_live(tx: &mpsc::Sender<Msg>) {
        // ── Ctrl+C: install LAST, immediately before the loop that can service it ──
        //
        // Installing a handler converts SIGINT from "terminate now" into "enqueue
        // `Msg::Interrupt`", and that message is only ever read by the watch loop. So
        // every instruction between `set_handler` and the loop is a stretch of startup
        // during which Ctrl+C does nothing at all — the process keeps compiling and keeps
        // writing output, then exits 0 as if the user had never pressed it. Repeat
        // presses do not help; only SIGKILL does. The cost scales with the size of the
        // startup compile, so the handler is installed once startup is done, with nothing
        // but the loop after it. Nothing before it needs the handler: arming the watcher
        // only needs the sender, which is cloned here just as well.
        let tx_ctrlc = tx.clone();
        let _ = ctrlc::set_handler(move || {
            crate::output::panic_in_handler("ctrlc");
            let _ = tx_ctrlc.send(Msg::Interrupt);
        });

        // Every dir is armed and every baseline captured — the watch is now live.
        crate::output::note_watch_session_live();
        emit_ready_marker();
    }

    /// The watch loop: one event batch, one idle tick, or one held rebuild's deadline at a
    /// time. It is bounded: it ends on Ctrl+C, on the channel closing, or when a wake ends
    /// the session (stdout's reader gone), and returns why.
    fn watch_loop(
        rx: &mpsc::Receiver<Msg>,
        tick: Option<Duration>,
        session: &mut impl Session,
    ) -> StopReason {
        let mut clock = TickClock::new(tick);
        loop {
            let next = match clock.recv_next(rx, session.hold_deadline()) {
                Err(mpsc::RecvError) => break StopReason::Interrupted,
                Ok(Wake::Tick) => session.on_tick(),
                Ok(Wake::HoldDue) => session.on_hold_due(),
                Ok(Wake::Message(msg)) => session.on_message(msg, rx),
            };
            if let ControlFlow::Break(why) = next {
                break why;
            }
        }
    }
}

// ── Single-file watch ─────────────────────────────────────────────────────────

/// What [`compile_and_write`] returns on success, `(output_path, deps, content)`:
/// - `output_path`: the resolved output, written and shown (None for stdout).
/// - `deps`: transitive dependency paths, as graph keys ([`graph_keys`]).
/// - `content`: the compiled string (issue 3 — reused by the watch baseline block
///   so startup does not compile twice).
type WrittenEntry = (Option<WriteTarget>, Vec<PathBuf>, String);

/// Outcome of [`compile_and_write`]'s compile-and-write attempt, for an output route every
/// rebuild can use.
enum CompileWriteOutcome {
    /// Compiled, routed and written.
    Written(WrittenEntry),
    /// The compile failed, so the output's kind is unknown — and with it the route an
    /// output of that kind takes. `mds watch` keeps watching. `Some` is the failure to
    /// report; `None` a compile that panicked, which the panic hook reported (#389).
    CompileFailed(Option<miette::Report>),
    /// Compiled and routed, but not written. The dependencies the compile reported stay
    /// the session's (#257): every rebuild is triggered by them. `mds watch` keeps
    /// watching. `failure`: `Some` to report, naming the route of the compiled kind;
    /// `None` a repeat of a stdout failure reported already ([`OutputWrite::Failed`]).
    WriteFailed {
        /// Transitive dependency paths, as graph keys ([`graph_keys`]).
        deps: Vec<PathBuf>,
        failure: Option<miette::Report>,
    },
    /// `-o -` and stdout's reader is gone: `mds watch` stops (#157).
    StdoutClosed,
}

/// What one write of a watch session's output did (#157).
#[derive(Debug)]
#[must_use]
enum OutputWrite {
    /// Written in full.
    Written,
    /// Not written. `Some` is the failure to report: an output file that could not be
    /// written, or a new stdout failure (`mds::io`, naming stdout) — the session's first,
    /// or the first since a stdout write last landed. `None` is a repeat of that stdout
    /// failure, which is not reported again. Either way the content-dedup map must not
    /// record the content, so the next rebuild writes again even when its output has not
    /// changed.
    Failed(Option<miette::Report>),
    /// `-o -` and stdout's reader is gone: the session ends.
    StdoutClosed,
}

impl OutputWrite {
    /// The session's reading of one `-o -` write.
    ///
    /// Not [`StdoutOutcome::into_batch_result`]: a batch run takes a closed pipe and a
    /// repeated failure for success and finishes, but a session must stop on the first
    /// and must not record the second as written.
    fn from_stdout(outcome: StdoutOutcome) -> Self {
        match outcome {
            StdoutOutcome::Written => Self::Written,
            StdoutOutcome::Closed => Self::StdoutClosed,
            StdoutOutcome::Failed(e) => Self::Failed(Some(miette::Report::new(stdout_failure(&e)))),
            StdoutOutcome::FailedAgain => Self::Failed(None),
        }
    }
}

/// The path a session's output is written to; `None` for stdout.
fn written_path(output: &Option<WriteTarget>) -> Option<&Path> {
    output.as_ref().map(|target| target.path.as_path())
}

/// The session's output as a status line names it: the file by its shown form (#390), or
/// `<stdout>`.
fn shown_output(output: &Option<WriteTarget>) -> &Path {
    output
        .as_ref()
        .map_or(Path::new("<stdout>"), |target| target.shown.as_path())
}

/// Whether writing `after` empties an output: what the session last wrote there for the
/// same source (`before`) had bytes, and `after` has none (#380). An output the session
/// never wrote there, or wrote empty, is not emptied by an empty write.
fn empties_output(before: Option<&str>, after: &str) -> bool {
    after.is_empty() && before.is_some_and(|before| !before.is_empty())
}

/// Announce a rebuild's output, `shown` as its `Recompiled` line names it, when the write
/// `emptied` it ([`empties_output`], #380) — as a held rebuild whose source stayed empty
/// past its deadline does. Nothing under `--quiet`, as for every watch status line.
fn announce_emptied_output(shown: &Path, emptied: bool, quiet: bool) {
    if emptied && !quiet {
        crate::output::ewriteln!("Wrote an empty output: {}", safe_path(shown));
    }
}

/// Write `content` where the session writes: the output file, through [`write_output`]
/// (`announce` prints its `Compiled to` line) and never over one of `inputs`, the files
/// its compile read (#425), or stdout for `-o -` (`output_path` is `None`).
fn write_session_output(
    output_path: Option<&WriteTarget>,
    content: &str,
    inputs: &Inputs,
    quiet: bool,
    announce: bool,
) -> OutputWrite {
    match output_path {
        Some(target) => match write_output(Some(target), content, inputs, quiet, announce) {
            Ok(()) => OutputWrite::Written,
            Err(e) => OutputWrite::Failed(Some(e)),
        },
        None => OutputWrite::from_stdout(write_stdout(content.as_bytes())),
    }
}

/// A rebuilt output whose route is not the one the session last wrote to: the compiled
/// kind changed (#160). It is written over only a file the session wrote.
#[derive(Debug, Clone, Copy)]
struct ChangeOfKind<'a> {
    /// What the session's record says of the file at the new route, for the source.
    record: Record<'a>,
    /// The rebuild before this one kept the same content from being written: the notice
    /// for the same keep is not shown again.
    told: bool,
}

/// What the write of a rebuilt output came to, when it did not fail ([`write_rebuilt`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Rewritten {
    /// Written in full.
    Written,
    /// Not written: after a change of kind, the file there is not the session's own, or was
    /// changed since the session wrote it, and is kept as it is (#160). Nothing is written
    /// or retired, so a later save tries again.
    Kept,
}

/// Write `content`, a rebuilt output, to the file `target` (#160): the one write file mode
/// and directory mode both make. `anchor` is the out-dir the session writes below and
/// `now` what the check of it just before this found.
///
/// - An out-dir the typed path now leads elsewhere from refuses the write
///   ([`crate::write::out_dir_moved`]).
/// - After a change of kind (`change_of_kind` is `Some`), the file at `target` is written
///   over only if it is the session's own ([`write_after_change_of_kind`]); else
///   [`Rewritten::Kept`].
/// - Any other write is [`write_output`], never over one of the files `inputs` names, the
///   files the compile read (#425). `inputs` is made only when this write needs it.
///
/// The late look (#380) is not taken here: each mode takes it where its own state allows,
/// before this write. The record of what was written, the retirement of the other kind's
/// output and what the rebuild shows are each mode's own.
fn write_rebuilt(
    target: &WriteTarget,
    anchor: Option<&OutDirAnchor>,
    now: OutDirNow,
    change_of_kind: Option<ChangeOfKind<'_>>,
    content: &str,
    inputs: impl FnOnce() -> Inputs,
    quiet: bool,
) -> std::result::Result<Rewritten, miette::Report> {
    if now == OutDirNow::Elsewhere {
        return Err(miette::Report::new(crate::write::out_dir_moved(target)));
    }
    let below = below_checked_out_dir(anchor, target);
    match change_of_kind {
        Some(ChangeOfKind { record, told }) => {
            write_after_change_of_kind(&below, record, content, told, quiet)
                .map(|written| {
                    if written {
                        Rewritten::Written
                    } else {
                        Rewritten::Kept
                    }
                })
                .map_err(miette::Report::new)
        }
        None => write_output(Some(&below), content, &inputs(), quiet, false)
            .map(|()| Rewritten::Written),
    }
}

/// Announce a rebuilt output that was written: its `Recompiled` line, naming `shown`, the
/// number of dependencies the compile reported and the time since `since`, when the
/// compile began; then the notice for an output the write `emptied` ([`empties_output`],
/// #380). Nothing under `--quiet`, as for every watch status line.
fn announce_recompiled(shown: &Path, dep_count: usize, since: Instant, emptied: bool, quiet: bool) {
    if !quiet {
        let elapsed = since.elapsed().as_millis();
        crate::output::ewriteln!(
            "Recompiled {} ({} deps) in {}ms",
            safe_path(shown),
            dep_count,
            elapsed
        );
    }
    announce_emptied_output(shown, emptied, quiet);
}

/// Compile `entry` ([`WatchedPath::compile`]), derive the output path from the compiled
/// kind and the entry's two forms — written beside `entry.canonical`, named beside
/// `entry.typed` (#390) — and write: file mode's startup compile.
///
/// Returns a [`CompileWriteOutcome`]. `CompileFailed` and `WriteFailed` are failures
/// `mds watch` reports and keeps watching through — a failed write still carries the
/// dependencies its compile reported (#257); `StdoutClosed` ends the
/// session before it goes live, with exit 0 (#157). The `Err` this function
/// itself returns is an output route no rebuild can use, which ends `mds watch` at
/// startup (exit 2), since every rebuild writes where startup resolved: a route that
/// fails to resolve — `mds.json` `build.output_dir` with a `..` component, refused with
/// the error `mds build` gives for it — or an output that is the entry file itself
/// ([`admit_output`], #425).
///
/// The output path is derived AFTER compiling (compile-then-route) so the kind
/// (and thus extension: `.json` for messages, `.md` for markdown) is known before
/// the path is constructed. This is the single-file intrinsic extension path.
///
/// If `-o <path>` is given explicitly, that path is used verbatim, and once
/// [`admit_output`] has admitted it an ext-mismatch warning is emitted when the
/// extension contradicts the kind (AC-FUNC-11). If `-o -`, content is written to stdout.
/// No source map is written: `mds watch` emits none. The output is never written over a
/// file the compile read — the entry, a module it imported, or one of `reads`, the
/// `--vars` file and the `mds.json` in force (#425); such a write fails as any other.
///
/// All source reads use `compile_native_to_content` and `mds::compile_native_fs`,
/// which applies the resolver's file size cap.
fn compile_and_write(
    entry: &WatchedPath,
    output: &Option<String>,
    out_dir: &Option<PathBuf>,
    config: &Option<ProjectConfig>,
    reads: &[PathBuf],
    runtime_vars: Option<HashMap<String, mds::Value>>,
    quiet: bool,
) -> Result<CompileWriteOutcome> {
    let compiled = match entry.compile(runtime_vars, quiet, &Arc::new(mds::ReadLog::new())) {
        Ok(compiled) => compiled,
        Err(failure) => return Ok(CompileWriteOutcome::CompileFailed(failure.into_report())),
    };
    let output_path =
        resolve_output_path_for_kind(Some(entry.paths()), output, out_dir, config, compiled.kind)?;
    admit_output(
        written_path(&output_path),
        entry.paths(),
        output,
        compiled.kind,
        quiet,
    )
    .map_err(miette::Error::from)?;
    let inputs = compile_inputs(Some(&entry.canonical), &compiled.dependencies, reads);
    Ok(
        match write_session_output(
            output_path.as_ref(),
            &compiled.content,
            &inputs,
            quiet,
            true,
        ) {
            OutputWrite::Written => CompileWriteOutcome::Written((
                output_path,
                graph_keys(&compiled.dependencies),
                compiled.content,
            )),
            OutputWrite::Failed(failure) => CompileWriteOutcome::WriteFailed {
                deps: graph_keys(&compiled.dependencies),
                failure,
            },
            OutputWrite::StdoutClosed => CompileWriteOutcome::StdoutClosed,
        },
    )
}

/// Compile-time context for single-file watch mode.
///
/// Holds the parameters that are resolved once at startup and passed to every
/// rebuild — replaces the 6-7 individual constant args on `rebuild_file` and
/// `liveness_probe_file`, removing the `#[allow(clippy::too_many_arguments)]`
/// suppressions (issue #6 / zero-warnings policy).
struct FileCompileCtx {
    /// The watched entry, as typed and canonical ([`Watched::Entry`]).
    entry: WatchedPath,
    /// The working directory at startup, restored first by every rebuild.
    working_dir: WorkingDir,
    /// Canonicalized `--vars` path — matches notify's canonicalized event paths;
    /// used for `dirs_to_watch`/`files_of_interest` (never for display, #326).
    vars_path: Option<PathBuf>,
    /// The `--vars` path exactly as the user typed it, uncanonicalized (#326, D4).
    /// Used for `RuntimeVarArgs.vars` so the vars-file duplicate-key warning displays
    /// (and reads) the as-typed path rather than its canonical form.
    vars_path_typed: Option<PathBuf>,
    /// The files every compile reads besides the entry's own — the `--vars` file and the
    /// `mds.json` in force — which no output is written over (#425).
    reads: Vec<PathBuf>,
    static_set_vars: Vec<(String, String)>,
    static_set_string_vars: Vec<(String, String)>,
    quiet: bool,
}

/// What file mode's content-dedup map is keyed by: stdout, or the output file by the
/// path it is written to (#390).
///
/// A path, never its text: the text is lossy for a name that is not UTF-8, so two outputs
/// whose names differ only there would share one key.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum OutputKey {
    Stdout,
    File(PathBuf),
}

impl OutputKey {
    /// The key of the session's output: `None` is stdout (`-o -`).
    fn of(output: Option<&WriteTarget>) -> Self {
        match output {
            Some(target) => Self::File(target.path.clone()),
            None => Self::Stdout,
        }
    }
}

/// Where file mode writes its output, resolved at startup (#257). A route that fails to
/// resolve never gets here: it ends `mds watch` at startup.
#[derive(Debug, PartialEq, Eq)]
enum OutputRoute {
    /// The path an explicit `-o` names: every output is written there, whatever its
    /// kind. `None` is stdout (`-o -`).
    Named(Option<WriteTarget>),
    /// No `-o`: the route of each kind, resolved at startup, and every output takes its
    /// own kind's — after a startup compile that failed, and when an edit changes the
    /// kind (#257, #160).
    ByKind {
        markdown: Option<WriteTarget>,
        messages: Option<WriteTarget>,
    },
}

impl OutputRoute {
    /// The route an output of `kind` takes: the named one whatever the kind, or else
    /// that kind's.
    fn of(&self, kind: OutputKind) -> &Option<WriteTarget> {
        match self {
            Self::Named(route) => route,
            Self::ByKind { markdown, messages } => match kind {
                OutputKind::Markdown => markdown,
                OutputKind::Messages => messages,
            },
        }
    }

    /// The route an output of `kind` no longer takes once it is written: the other
    /// kind's — whose output a change of kind leaves behind (#160) — and none for a
    /// named route, which every kind takes.
    fn other_than(&self, kind: OutputKind) -> Option<&WriteTarget> {
        match self {
            Self::Named(_) => None,
            Self::ByKind { markdown, messages } => match kind {
                OutputKind::Markdown => messages.as_ref(),
                OutputKind::Messages => markdown.as_ref(),
            },
        }
    }
}

/// Mutable loop state for single-file watch mode.
///
/// Groups the per-loop variables that are updated on every rebuild or liveness tick,
/// mirroring `DirWatchState` for directory mode (eliminates the asymmetry noted in
/// the architecture review).
struct FileWatchState {
    /// Directories currently registered with `watcher`.
    watched_dirs: BTreeSet<PathBuf>,
    /// Subset of `watched_dirs` that have been successfully armed (registered with the
    /// OS watcher).  Used by `liveness_probe_file` to skip the `watcher.watch()` syscall
    /// for dirs that are already known-good — steady-state idle cost becomes O(missing_dirs)
    /// ≈ O(0) rather than O(watched_dirs) (reconcile rule / issue #1).
    armed_dirs: BTreeSet<PathBuf>,
    /// Set of paths relevant to the current build (entry + deps + vars).
    foi: HashSet<PathBuf>,
    /// Snapshot of `(mtime, size)` used by the liveness probe (reconcile rule), and by a
    /// rebuild to tell a file of interest emptied since (#380).
    last_mtimes: StampMap,
    /// The rebuild held while a file of interest is empty (#380).
    hold: EmptyHold,
    /// What this session last wrote, by where it wrote it: what a later write may skip as
    /// unchanged, and the bytes a removal or a write after a change of kind asks the file
    /// to still hold (#160). An entry goes with its file, so a file kept — changed, or a
    /// removal that failed — stays the session's.
    last_written: HashMap<OutputKey, String>,
    /// Where this session last wrote its output, if it has: a rebuild whose route is
    /// another — a change of kind — writes only where nothing is, or over its own file
    /// ([`write_after_change_of_kind`], #160).
    written_to: Option<OutputKey>,
    /// What the last rebuild kept from being written after a change of kind, the file
    /// there not being the session's (#160): the next rebuild of the same — another event
    /// of the same save — tries again but tells it no more. Any other rebuild clears it.
    kept: Option<String>,
    /// Where every rebuild writes ([`OutputRoute::of`]), and the output a change of kind
    /// leaves behind ([`OutputRoute::other_than`]).
    output: OutputRoute,
    /// The out-dir the output is written below, checked before every write; `None` for
    /// `-o` and for an output beside the entry.
    out_dir: Option<OutDirAnchor>,
    /// Whether the entry file was missing on the previous liveness tick.
    entry_was_missing: bool,
    /// True on the very first tick; forces a reconcile to close the startup race window.
    first_tick: bool,
    /// Parent dirs that were missing on the previous tick (edge-triggered recovery).
    missing_watched_dirs: BTreeSet<PathBuf>,
}

impl FileWatchState {
    /// Take the baseline over the files of interest again, from the stamps the rebuild's
    /// look took ([`baseline_over`], #380).
    fn rebaseline(&mut self) {
        let taken = std::mem::take(&mut self.last_mtimes);
        self.last_mtimes = baseline_over(taken, &self.foi);
    }
}

/// Outcome returned by `handle_fs_event_file` to tell the loop what to do next.
enum FileEventAction {
    /// Skip this message (Access event or irrelevant path) — go back to `recv_next`.
    Skip,
    /// Ctrl+C received — stop watching.
    Stop,
    /// Rebuild triggered.
    Rebuild,
}

/// Run the idle-tick liveness probe for single-file mode (reconcile rule).
///
/// Re-arms watches for dirs that were missing or not yet armed; skips the
/// `watcher.watch()` syscall for dirs already known-good (`armed_dirs`).
/// Applies edge-triggered recovery logic, checks `(mtime, size)` of all
/// files of interest.
///
/// Returns `true` when a rebuild is needed (recovery or mtime change detected).
fn liveness_probe_file(
    ctx: &FileCompileCtx,
    watcher: &mut RecommendedWatcher,
    state: &mut FileWatchState,
) -> bool {
    // 1. Re-arm watches for dirs that need attention (reconcile rule idle-O(1) fix).
    //    A dir "needs attention" if it was previously missing OR not yet armed.
    //    Already-armed, currently-present dirs are not touched — steady-state idle
    //    cost becomes O(missing_dirs) ≈ O(0), not O(watched_dirs).
    let desired_dirs: BTreeSet<PathBuf> =
        dirs_to_watch(&ctx.entry.canonical, &[], ctx.vars_path.as_deref())
            .union(&state.watched_dirs)
            .cloned()
            .collect();
    let dir_statuses: Vec<(PathBuf, bool, bool)> = desired_dirs
        .iter()
        .map(|d| {
            let exists = d.exists();
            // Only pay the watcher.watch() syscall when the dir was missing last tick
            // or has not yet been armed — existing armed dirs are left alone.
            let needs_arm = !state.armed_dirs.contains(d) || state.missing_watched_dirs.contains(d);
            let rearm_ok = if exists && needs_arm {
                let ok = watcher.watch(d, RecursiveMode::NonRecursive).is_ok();
                if ok {
                    state.armed_dirs.insert(d.clone());
                }
                ok
            } else {
                // Dir is already armed and was not missing — treat as armed-ok.
                // If it disappeared, external_recovery_decision will catch the
                // vanish→reappear edge on the next tick.
                exists
            };
            (d.clone(), exists, rearm_ok)
        })
        .collect();
    // Remove vanished dirs from armed_dirs using the already-computed exists flags
    // rather than re-stating each dir (avoids a second stat per dir per tick).
    for (d, exists, _) in &dir_statuses {
        if !exists {
            state.armed_dirs.remove(d);
        }
    }
    // Edge-triggered recovery (reconcile rule): mirrors external_recovery_decision used in
    // dir mode — a dir that STAYS missing must not trigger recovery every tick.
    let (dirs_recovery, now_missing_dirs) =
        external_recovery_decision(&state.missing_watched_dirs, &dir_statuses);
    state.missing_watched_dirs = now_missing_dirs;

    // 2. Determine if we need a full reconcile:
    //    (a) first tick, (b) edge-triggered dir recovery,
    //    (c) entry was missing and now exists (vanish→reappear edge).
    let entry_now_exists = ctx.entry.canonical.exists();
    let recovery =
        state.first_tick || dirs_recovery || (state.entry_was_missing && entry_now_exists);
    state.first_tick = false;
    state.entry_was_missing = !entry_now_exists;

    // 3. Cheap (mtime, size) check on files_of_interest.
    let changed = state_differs(&state.foi, &state.last_mtimes);

    recovery || changed
}

/// Classify an incoming `Msg` for single-file mode.
///
/// Returns the action the loop should take: skip irrelevant messages, stop on
/// Ctrl+C, or proceed to rebuild after draining the debounce window — with `--clear`,
/// that rebuild asks for the terminal to be cleared ([`crate::output::ask_clear`]).
fn handle_fs_event_file(
    msg: Msg,
    foi: &HashSet<PathBuf>,
    rx: &mpsc::Receiver<Msg>,
    debounce_ms: u64,
    clear: bool,
) -> FileEventAction {
    let interrupted = match msg {
        Msg::Interrupt => true,
        Msg::Fs(Err(e)) => {
            eprint_warning(&format!(
                "warning: watch error: {}",
                safe_inline(notify_cause(&e))
            ));
            // Non-fatal watch error — skip but don't rebuild.
            return FileEventAction::Skip;
        }
        Msg::Fs(Ok(ref event)) => {
            // Drop Access events (inotify reads) before path check.
            if !is_content_event(&event.kind) {
                return FileEventAction::Skip;
            }
            if !event_is_relevant(event, foi) {
                return FileEventAction::Skip; // Not relevant — skip debounce entirely.
            }
            false
        }
    };

    if interrupted {
        return FileEventAction::Stop;
    }

    // Drain the debounce window.
    // The drained paths are discarded: file mode has already decided relevance above
    // and rebuilds its single entry regardless of which path moved.
    if drain_debounce(rx, debounce_ms).interrupted() {
        return FileEventAction::Stop;
    }

    // The terminal is cleared, if requested (only when stderr is a TTY), before the first
    // thing the rebuild prints (#380).
    if clear {
        crate::output::ask_clear();
    }

    FileEventAction::Rebuild
}

/// Compile `entry`, resync watches, compare with last-written content, and write
/// if changed.  Called from the idle-tick, the held-rebuild and the FS-event arms of file
/// mode's live session (`file_startup::FileSession`'s `on_tick`, `on_hold_due` and
/// `on_message`) — the single canonical implementation of the
/// hold→compile→resync→route→dedup→write→settle sequence for single-file mode.
///
/// `ctx` holds compile-time constants; `state` holds all mutable loop state;
/// `watcher` is passed separately (non-Clone, distinct lifecycle role).
///
/// Returns `Break` when the session must stop: `-o -` found stdout's reader gone
/// (#157). Every other outcome, failures included, keeps watching.
///
/// # Holding while a file is empty (#380)
///
/// Before anything is read, a file of interest — the entry, a dependency, the `--vars`
/// file — found empty where the baseline saw bytes holds the rebuild back: nothing is
/// compiled, written or printed, and the baseline is left as it was ([`Settle::Defer`]),
/// so the next event or tick finds the file again. The hold ends at the first rebuild that
/// finds none emptied, or at its deadline ([`EmptyHold`]), when the files are compiled as
/// they are; an output published empty over the non-empty one before it is announced
/// ([`announce_emptied_output`]). A file the `--vars` load or the compile read found
/// emptied after that look — a truncation that began between the two — holds the rebuild
/// the same way, whether the read then failed or not, unless the deadline ended the hold in
/// it ([`EmptyHold::on_late_empty`]). A rebuild the look lets run takes the look's stamps
/// as its baseline before it reads anything, and keeps them however it ends
/// ([`baseline_over`]), so a file truncated after the compile read it whole is found
/// emptied by the next rebuild too. `due` is the hold's
/// deadline when that deadline runs this rebuild, which then ends the hold
/// ([`not_before`]); `None` for an event or a tick. A held rebuild prints nothing, the
/// `--clear` its event asked for included: that clear stays asked for, and the first thing
/// printed after it makes it — the rebuild that ends the hold, as a rule. Every other
/// rebuild drops the clear when it ends ([`end_rebuild_clear`]): the clear is made before
/// the first byte the rebuild prints, a compile warning among them, or not at all.
///
/// # Invariants preserved
/// - Freshness rule: `foi` and `watched_dirs` always recomputed from fresh dep output, by
///   every compile that succeeds — its output refused or not written included (#257).
/// - All source reads go through `compile_native_to_content`.
/// - Error-settle: every failure — the vars file, the compile, the output route or its
///   #425 refusal, the write — goes through [`settle`], except a repeated stdout failure,
///   which was reported already. A compile that panicked is settled the same way; the
///   panic hook was its report (#389).
/// - `last_written` records only content that was written, so a rebuild after a failed
///   write writes again even when its output has not changed (#157).
/// - A recreated working directory is restored before anything is read
///   ([`WorkingDir::restore_if_recreated`]).
fn rebuild_file(
    ctx: &FileCompileCtx,
    watcher: &mut RecommendedWatcher,
    state: &mut FileWatchState,
    due: Option<Instant>,
) -> ControlFlow<StopReason> {
    let flow = run_file_rebuild(ctx, watcher, state, due);
    end_rebuild_clear(&state.hold);
    flow
}

/// The rebuild [`rebuild_file`] runs and ends: every return of it is one the clear is
/// dropped after (unless held).
fn run_file_rebuild(
    ctx: &FileCompileCtx,
    watcher: &mut RecommendedWatcher,
    state: &mut FileWatchState,
    due: Option<Instant>,
) -> ControlFlow<StopReason> {
    ctx.working_dir.restore_if_recreated();
    // #380: a file of interest emptied holds the rebuild back — before `kept` is taken,
    // since a rebuild held is no rebuild. The look stamps each file of interest once.
    let look = snapshot_state(&state.foi);
    let emptied = emptied_in(&look, &state.last_mtimes).next().is_some();
    let verdict = state
        .hold
        .on_rebuild(emptied, not_before(Instant::now(), due));
    debug_assert!(
        due.is_none() || verdict == HoldVerdict::Compile,
        "a held rebuild's deadline ends its hold"
    );
    if verdict == HoldVerdict::Hold {
        settle(SettleInto::File(state), None, Settle::Defer);
        return ControlFlow::Continue(());
    }
    // The look's stamps are the rebuild's baseline from here, taken before anything is read:
    // every later look compares with them and every settle keeps them, so a file changed
    // after the look — one truncated after the compile read it whole included — is seen
    // again by the next look (#380). A file the look found emptied is in it empty: the
    // deadline compiles it as it is, and it is not held again.
    state.last_mtimes.extend(look);
    // A debug build's test pause (#380): the rebuild found no file emptied, and has read none.
    pause_after_look();
    // What the rebuild before this one kept from being written (#160): told again unless
    // this rebuild keeps the same once more, as another event of the same save does.
    let kept_before = state.kept.take();

    // Soft-error: vars file may be temporarily absent (AC-W7 / AC-C5).
    // Print the error, settle mtime to avoid re-fire, and keep watching.
    //
    // The vars-file duplicate-key warnings (#326) are NOT emitted here
    // unconditionally: `rebuild_file` is called both from a genuine fs-event
    // rebuild AND from the liveness probe's unconditional-on-first-tick
    // self-heal recompile (a documented "worst case: one redundant compile"
    // that normally dedups to no write, see the comment above this function).
    // Emitting here would double-report the same duplicate once per session on
    // every startup. Instead the resolved vars are held and the warning is
    // emitted below, once the write has decided what the rebuild shows — its
    // "Recompiled" line, a "Kept" notice, or a failed write's report — so the
    // vars-file duplicate is re-reported exactly once per OBSERVABLE rebuild
    // (tests I16, I18, I20; a kept change of kind, #160).
    let reads = Arc::new(mds::ReadLog::new());
    let loaded = load_and_compile(ctx, &reads);
    // A debug build's test pause (#380): the reads are done, the late look is not.
    pause_before_late_look();
    // #380: a file the `--vars` load or the compile read empty, which the baseline saw with
    // bytes — a truncation that began between the look above and the read — holds the
    // rebuild back as the look would have, with nothing reported or recorded, unless the
    // deadline ended the hold in this rebuild. The byte counts the reads gave decide
    // ([`read_empty`]), for a load or a compile that failed too.
    if held_after_look(&mut state.hold, read_empty(&reads, &state.last_mtimes)).is_some() {
        state.kept = kept_before;
        settle(SettleInto::File(state), None, Settle::Defer);
        return ControlFlow::Continue(());
    }
    let FileCompiled {
        resolved,
        started: t0,
        compiled,
        deps,
        foi,
    } = match loaded {
        Ok(done) => done,
        Err((failure, how)) => {
            settle(SettleInto::File(state), failure, how);
            return ControlFlow::Continue(());
        }
    };
    let entry = &ctx.entry;
    // Freshness rule: always recompute dep set from fresh output — before the output's
    // route is admitted, so the files a compile read are watched even when its output is
    // refused, a dependency in a directory no earlier compile reported included (#257).
    let new_dirs = dirs_to_watch(&entry.canonical, &deps, ctx.vars_path.as_deref());
    state.watched_dirs = resync_watches(
        watcher,
        &state.watched_dirs,
        &new_dirs,
        entry.dir_paths(),
        vars_dir_paths(ctx.vars_path.as_deref(), ctx.vars_path_typed.as_deref()),
    );
    // Keep armed_dirs in sync: all dirs in watched_dirs are successfully armed;
    // dirs removed by resync_watches are no longer in watched_dirs.
    state.armed_dirs = state.watched_dirs.clone();
    state.foi = foi;
    // A debug build's test pause (#380): the compile read every file, and none was found
    // emptied.
    pause_after_read();
    // The baseline over the files of interest the compile reported, even when its output is
    // unchanged: the stamps the look took, a file the compile discovered stamped now (#380).
    state.rebaseline();

    // The compiled kind's route, re-decided by every rebuild: one whose kind changed is
    // written to that kind's output (#257) — only where nothing is, or over the file this
    // session wrote there (#160).
    let output_path = state.output.of(compiled.kind).clone();
    // #425: a rebuild never writes over the entry — reachable after a failed startup
    // compile, which refuses no route, and after a change of kind: the route of the
    // compiled kind, or an explicit `-o`, can be the entry. A refused route writes
    // nothing, and is reported and settled as a failed compile is; the next rebuild
    // routes again. No `-o` extension warning (`&None`): startup printed it for the path
    // an explicit `-o` names, which every rebuild reuses.
    if let Err(refused) = admit_output(
        written_path(&output_path),
        entry.paths(),
        &None,
        compiled.kind,
        ctx.quiet,
    ) {
        settle(
            SettleInto::File(state),
            Some(miette::Report::from(refused)),
            Settle::MarkErrored(&entry.canonical),
        );
        return ControlFlow::Continue(());
    }

    // The content-dedup key: where the output is written.
    let output_key = OutputKey::of(output_path.as_ref());

    let out_dir = check_out_dir(state.out_dir.as_mut(), &mut state.last_written);

    // A change of kind (#160): the route is not the one this session last wrote to, so
    // the file there is written over only if it is the session's own.
    let kind_changed = state
        .written_to
        .as_ref()
        .is_some_and(|key| *key != output_key);
    // Content-based dedup: skip write + summary line when unchanged — never after a change
    // of kind, whose write is decided by the file there whatever the record of it holds.
    let content_changed = kind_changed
        || state
            .last_written
            .get(&output_key)
            .is_none_or(|prev| *prev != compiled.content);

    if !content_changed {
        return ControlFlow::Continue(());
    }
    // #326: the vars-file duplicate-key warnings are re-reported once for each rebuild
    // that shows something — its "Recompiled" line, a "Kept" notice or a failed write's
    // report, before the report — never by the liveness probe's redundant no-op
    // recompile, nor by a rebuild after a change of kind that keeps again what the one
    // before it kept and tells nothing (#160).
    let warn_duplicates = || crate::build::emit_duplicate_vars_file_warnings(&resolved, ctx.quiet);
    // The rebuild before this one kept the same from being written (#160): told already.
    let told = kept_before.as_ref() == Some(&compiled.content);
    let written = match output_path.as_ref() {
        Some(target) => match write_rebuilt(
            target,
            state.out_dir.as_ref(),
            out_dir,
            kind_changed.then(|| ChangeOfKind {
                record: Record::of_entry(state.last_written.get(&output_key)),
                told,
            }),
            &compiled.content,
            || {
                compile_inputs(
                    Some(&ctx.entry.canonical),
                    &compiled.dependencies,
                    &ctx.reads,
                )
            },
            ctx.quiet,
        ) {
            Ok(Rewritten::Written) => OutputWrite::Written,
            // Kept: nothing is written and nothing retired, and `last_written` is left as
            // it was, so a later save tries again.
            Ok(Rewritten::Kept) => {
                if !told {
                    warn_duplicates();
                }
                state.kept = Some(compiled.content);
                return ControlFlow::Continue(());
            }
            Err(e) => OutputWrite::Failed(Some(e)),
        },
        None => OutputWrite::from_stdout(write_stdout(compiled.content.as_bytes())),
    };
    match written {
        OutputWrite::Written => {
            warn_duplicates();
            announce_recompiled(
                shown_output(&output_path),
                deps.len(),
                t0,
                empties_output(
                    state.last_written.get(&output_key).map(String::as_str),
                    &compiled.content,
                ),
                ctx.quiet,
            );
            state
                .last_written
                .insert(output_key.clone(), compiled.content);
            state.written_to = Some(output_key);
            if let Some(anchor) = &mut state.out_dir {
                anchor.written();
            }
            // A change of kind (#160): the output this session last wrote, the other
            // kind's, is retired — removed only if the session wrote it and it holds what
            // was written, else kept with a notice. The record of it goes only with the
            // file, so one kept stays the session's, changed or restored.
            if let Some(stale) = state
                .output
                .other_than(compiled.kind)
                .filter(|_| kind_changed)
                .cloned()
            {
                let stale_key = OutputKey::of(Some(&stale));
                let gone = retire_output(
                    &stale,
                    state.out_dir.as_ref(),
                    out_dir,
                    Record::of_entry(state.last_written.get(&stale_key)),
                    Retirement::KindChanged,
                    ctx.quiet,
                );
                if gone {
                    state.last_written.remove(&stale_key);
                }
            }
        }
        // Not written: `last_written` keeps what was last written, so the next rebuild
        // writes again even when its output has not changed.
        OutputWrite::Failed(Some(e)) => {
            warn_duplicates();
            settle(
                SettleInto::File(state),
                Some(e),
                Settle::MarkErrored(&ctx.entry.canonical),
            );
        }
        // A repeat of a stdout failure reported already (#157): neither reported nor
        // settled again, and shown nothing.
        OutputWrite::Failed(None) => {}
        OutputWrite::StdoutClosed => return ControlFlow::Break(StopReason::StdoutClosed),
    }
    ControlFlow::Continue(())
}

/// What a file-mode rebuild's `--vars` load and compile gave ([`load_and_compile`]).
struct FileCompiled {
    /// The variables the load resolved, less the map the compile took: the duplicate keys
    /// of the `--vars` file are still to be reported (#326).
    resolved: RuntimeVars,
    /// When the compile began.
    started: Instant,
    compiled: CompileOutput,
    /// The dependencies the compile reported, as graph keys.
    deps: Vec<PathBuf>,
    /// The files of interest the compile gave: the entry, `deps` and the `--vars` file.
    foi: HashSet<PathBuf>,
}

/// A file-mode rebuild's `--vars` load and, when it succeeded, its compile of the entry: a
/// load that failed compiles nothing. A failure is returned as what to report — `None` for
/// a compile that panicked, which the panic hook reported (#389) — and how to settle it:
/// [`Settle::Rebaseline`] for the load, [`Settle::MarkErrored`] for the compile. Nothing is
/// reported or settled here: the caller's late look decides first ([`held_after_look`]).
/// The load and the compile record the byte count of every file they read in `reads`, a
/// failed one included.
fn load_and_compile<'a>(
    ctx: &'a FileCompileCtx,
    reads: &Arc<mds::ReadLog>,
) -> std::result::Result<FileCompiled, (Option<miette::Report>, Settle<'a>)> {
    let mut resolved = build_runtime_vars_logged(
        RuntimeVarArgs {
            vars: ctx.vars_path_typed.clone(),
            set_vars: ctx.static_set_vars.clone(),
            set_string_vars: ctx.static_set_string_vars.clone(),
        },
        reads,
    )
    .map_err(|e| (Some(e), Settle::Rebaseline))?;
    // Move the map out instead of cloning it: `compile_native_to_content` takes
    // `runtime_vars` by value, and the emitter in `run_file_rebuild` only ever reads
    // `resolved.vars_file` / `duplicate_vars_file_keys` /
    // `duplicate_vars_file_keys_omitted` — none of which need `.vars`.
    let runtime_vars = resolved.vars.take();

    let started = Instant::now();
    let entry = &ctx.entry;
    let compiled = entry
        .compile(runtime_vars, ctx.quiet, reads)
        .map_err(|failure| (failure.into_report(), Settle::MarkErrored(&entry.canonical)))?;
    let deps = graph_keys(&compiled.dependencies);
    let foi = files_of_interest(&entry.canonical, &deps, ctx.vars_path.as_deref());
    Ok(FileCompiled {
        resolved,
        started,
        compiled,
        deps,
        foi,
    })
}

// ── Settling a failure ────────────────────────────────────────────────────────

/// How `mds watch` settles a rebuild-time failure it keeps watching through (#257):
/// reading the vars file, a compile — a panic included (#389) — the output route, a
/// write; and a rebuild held back while a watched file is empty (#380), which is no
/// failure. The site picks the action and hands it to [`settle`] with the state to apply
/// it to ([`SettleInto`]). A startup failure settles through [`settle_startup_error`]
/// instead: there is no baseline yet to take again, so [`Settle::Rebaseline`] has nothing
/// to apply there, and no startup compile is ever held. The repeat of a stdout failure
/// reported already (#157) settles nothing, through neither.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Settle<'a> {
    /// Take the `(mtime, size)` baseline again, so the idle tick does not fire again on
    /// files that have not changed since — from the stamps the rebuild's look took before
    /// it read anything, never from the files as they are once it has read them, so a file
    /// truncated since is found emptied by the next look (#380).
    Rebaseline,
    /// The source failed, and a later change must compile it again even when the source
    /// itself has not changed. Directory mode records it as errored — re-seeded into every
    /// batch that carries a real change — keeping the dependency set its last successful
    /// compile recorded (#321); the batch takes the baseline once, at its end. File mode
    /// compiles its one source again on every change anyway, so there it takes the
    /// baseline again, as [`Settle::Rebaseline`] does.
    MarkErrored(&'a Path),
    /// The rebuild was held back, a watched file being empty (#380): nothing ran, so there
    /// is nothing to report and nothing to record, and the baseline is left as it is — as
    /// it was before a rebuild its look held, the look's stamps for one held by a file found
    /// emptied after the look — so the next event or tick finds the emptied file again, and
    /// the rebuild is held again or run.
    Defer,
}

/// The rebuild state a [`Settle`] is applied to.
enum SettleInto<'a> {
    /// A file-mode rebuild.
    File(&'a mut FileWatchState),
    /// A directory-mode rebuild.
    Dir(&'a mut DirWatchState),
}

/// Settle a rebuild-time failure `mds watch` keeps watching through (#257): report
/// `failure`, then apply `how` to `into`. `failure` is `None` when there is nothing to
/// report — a compile that panicked, which the panic hook reported (#389) — so a panic
/// settles exactly as an error at the same site does, reported once.
fn settle(into: SettleInto<'_>, failure: Option<miette::Report>, how: Settle<'_>) {
    settle_reporting(into, failure, how, eprint_error);
}

/// [`settle`], with `report` doing the reporting: the session's error renderer there, a
/// recorder in a test.
fn settle_reporting(
    into: SettleInto<'_>,
    failure: Option<miette::Report>,
    how: Settle<'_>,
    report: impl FnOnce(miette::Report),
) {
    if let Some(e) = failure {
        report(e);
    }
    match (into, how) {
        (SettleInto::File(state), Settle::Rebaseline | Settle::MarkErrored(_)) => {
            state.rebaseline();
        }
        (SettleInto::Dir(state), Settle::Rebaseline) => {
            state.rebaseline();
        }
        (SettleInto::Dir(state), Settle::MarkErrored(src)) => {
            state.record_error(src);
        }
        (SettleInto::File(_) | SettleInto::Dir(_), Settle::Defer) => {}
    }
}

/// The startup state a failure (#257) settles into: file mode's startup records nothing —
/// the session's first baseline is taken once the startup compile is done, the one
/// [`Settle::Rebaseline`] asks for in a rebuild; directory mode's startup records the
/// source as errored, keeping the dependency set its compile reported (empty for a source
/// new to the graph).
enum StartupInto<'a> {
    /// File mode's startup.
    File,
    /// Directory mode's startup.
    Dir(&'a mut DirWatchState),
}

/// Settle a startup failure `mds watch` keeps watching through (#257): report `failure`,
/// then mark `src` errored in directory mode. `failure` is `None` for a compile that
/// panicked, which the panic hook reported (#389). There is no [`Settle::Rebaseline`] at
/// startup — the baseline is still to come — so `StartupInto` takes no `how`: a startup
/// failure only ever means the source is errored.
fn settle_startup_error(into: StartupInto<'_>, failure: Option<miette::Report>, src: &Path) {
    settle_startup_error_reporting(into, failure, src, eprint_error);
}

/// [`settle_startup_error`], with `report` doing the reporting: the session's error
/// renderer there, a recorder in a test.
fn settle_startup_error_reporting(
    into: StartupInto<'_>,
    failure: Option<miette::Report>,
    src: &Path,
    report: impl FnOnce(miette::Report),
) {
    if let Some(e) = failure {
        report(e);
    }
    if let StartupInto::Dir(state) = into {
        state.record_error(src);
    }
}

/// A directory `mds watch` watches, as a message names it (#390). `root` is the directory
/// argument in directory mode, the entry's directory in file mode ([`RootPaths`]: the
/// canonical form watched, the form typed): it is named as typed, and a directory below
/// it — a dependency's — below it as typed. `vars` is the directory armed for the `--vars`
/// file, named by that file's directory as typed. Any other directory — a dependency's
/// outside both — has no typed form and is named by the path the compile reported.
fn shown_watched_dir(dir: &Path, root: RootPaths<'_>, vars: Option<RootPaths<'_>>) -> PathBuf {
    match vars {
        Some(vars) if dir == vars.walked && dir != root.walked => vars.typed.to_path_buf(),
        _ => root.typed_below(dir).unwrap_or_else(|| dir.to_path_buf()),
    }
}

/// The directory of file mode's `--vars` file in the two forms [`shown_watched_dir`]
/// takes: the canonical directory [`dirs_to_watch`] arms, and the file's directory as
/// typed.
fn vars_dir_paths<'a>(
    canonical: Option<&'a Path>,
    typed: Option<&'a Path>,
) -> Option<RootPaths<'a>> {
    canonical.zip(typed).map(|(canonical, typed)| RootPaths {
        typed: mds::effective_parent(typed),
        walked: mds::effective_parent(canonical),
    })
}

/// In directory mode, the `--vars` file's directory armed on its own, outside the root, in
/// the two forms a message names it by ([`shown_watched_dir`]): the canonical directory
/// armed, and the file's directory as typed.
fn extra_vars_dir<'a>(
    vars_dir_extra: Option<&'a Path>,
    vars_path_typed: Option<&'a Path>,
) -> Option<RootPaths<'a>> {
    vars_dir_extra
        .zip(vars_path_typed)
        .map(|(walked, typed)| RootPaths {
            typed: mds::effective_parent(typed),
            walked,
        })
}

/// Single-file watch: `entry.typed` is the path as typed — the entry is compiled by it
/// (#417), `mds.json` is looked up from it at startup (#413), and every status line
/// names the entry and its output by it (#390), so they name the files as the user
/// reaches them; `entry.canonical` is its canonical form, which everything else uses.
///
/// Startup runs in phases whose order the types enforce (#256, [`file_startup`]):
/// [`file_startup::arm_pre_read`] arms the watches and takes the baseline before anything
/// is read, [`file_startup::startup_compile`] compiles and writes once,
/// [`file_startup::arm_deps_and_seed`] arms the dependencies' directories and seeds what
/// every rebuild reads, and [`file_startup::Seeded::go_live`] goes live and watches until
/// the session stops.
fn run_watch_file(entry: WatchedPath, output: Option<String>, args: SessionArgs) -> Result<()> {
    let quiet = args.quiet;
    let armed = file_startup::arm_pre_read(entry, output, args)?;
    let compiled = match file_startup::startup_compile(armed)? {
        ControlFlow::Continue(compiled) => compiled,
        // stdout's reader is gone before the session went live: it stops here, and its
        // verdict is 0 — a closed pipe never changes the exit code (#157). The armed
        // watches it hands back are dropped after the stop line.
        ControlFlow::Break((why, _armed)) => {
            stop_watching(quiet, why);
            return Ok(());
        }
    };
    file_startup::arm_deps_and_seed(compiled)?.go_live();
    Ok(())
}

/// File mode's startup, in phases whose order the types enforce (#256).
///
/// Each phase takes the token only the phase before it makes, and every token's fields are
/// private to this module, so nothing outside it can make one: an
/// [`Armed`](file_startup::Armed) comes only from [`file_startup::arm_pre_read`], a
/// [`Compiled`](file_startup::Compiled) only from [`file_startup::startup_compile`] given an
/// `Armed`, a [`Seeded`](file_startup::Seeded) only from [`file_startup::arm_deps_and_seed`]
/// given a `Compiled`, and the session goes live only from a `Seeded`
/// ([`file_startup::Seeded::go_live`]). That is the order the session's change detection
/// rests on: the directories of the entry and the `--vars` file armed, and their
/// `(mtime, size)` baseline taken, before either is read; a dependency's baseline taken and
/// its directory armed once the compile reports it; Ctrl+C wired last, with nothing but the
/// loop after it. The compile takes the `Armed` and carries it on inside the `Compiled`, so
/// one `Armed` is compiled once, and a `Compiled` is seeded with the very watches it was
/// compiled under.
mod file_startup {
    use std::collections::{BTreeSet, HashMap};
    use std::ops::ControlFlow;
    use std::path::PathBuf;
    use std::sync::mpsc;
    use std::time::{Duration, Instant};

    use miette::Result;
    use notify::{RecommendedWatcher, RecursiveMode, Watcher};

    use crate::build::{
        admit_output, build_runtime_vars, emit_duplicate_var_warnings, load_config,
        resolve_output_path_for_kind, run_reads, OutputKind, ProjectConfig, RuntimeVarArgs,
    };
    use crate::output::{notify_cause, safe_inline, safe_path, WriteTarget};

    use super::{
        baseline_path, canonicalize_vars_path, compile_and_write, dirs_to_watch, files_of_interest,
        handle_fs_event_file, live, liveness_probe_file, rebuild_file, settle_startup_error,
        shown_watched_dir, snapshot_state, startup_race_probe, vars_dir_paths, written_path,
        CompileWriteOutcome, EmptyHold, FileCompileCtx, FileEventAction, FileWatchState, Msg,
        OutDirAnchor, OutputKey, OutputRoute, SessionArgs, StampMap, StartupInto, StopReason,
        WatchedPath, WorkingDir,
    };

    /// The session's first watches armed and its first baseline taken, before anything is
    /// read: made only by [`arm_pre_read`].
    pub(super) struct Armed {
        /// The watched entry, as typed and canonical ([`super::Watched::Entry`]).
        entry: WatchedPath,
        /// `-o` as text; `None` without it.
        output: Option<String>,
        out_dir: Option<PathBuf>,
        /// The working directory at startup, which every rebuild restores first.
        working_dir: WorkingDir,
        /// The `--vars` file, canonical: what notify names its events by (#326).
        vars_path: Option<PathBuf>,
        /// The `--vars` file as typed, which it is read and named by (#326).
        vars_path_typed: Option<PathBuf>,
        static_set_vars: Vec<(String, String)>,
        static_set_string_vars: Vec<(String, String)>,
        quiet: bool,
        clear: bool,
        debounce_ms: u64,
        tick: Option<Duration>,
        /// The channel the watcher sends on — and Ctrl+C, once the session is live.
        tx: mpsc::Sender<Msg>,
        rx: mpsc::Receiver<Msg>,
        watcher: RecommendedWatcher,
        /// The directories armed so far: the entry's and the `--vars` file's that exist
        /// and could be armed.
        watched_dirs: BTreeSet<PathBuf>,
        /// The entry's and the `--vars` file's `(mtime, size)`, taken before either is read.
        pre_mtimes: StampMap,
        /// Whether the entry was missing before its first read.
        entry_was_missing: bool,
    }

    /// The startup compile done, and its output written when it could be: made only by
    /// [`startup_compile`].
    pub(super) struct Compiled {
        /// The watches and baseline the compile ran under, handed on to
        /// [`arm_deps_and_seed`] with what it produced.
        armed: Armed,
        /// The `mds.json` in force, looked up from the entry as typed.
        config: Option<ProjectConfig>,
        /// The files every compile reads besides the entry's own (#425).
        reads: Vec<PathBuf>,
        /// Where every output is written ([`OutputRoute`]).
        output_route: OutputRoute,
        /// What the startup wrote and where, if it wrote.
        initial_written: Option<(Option<WriteTarget>, String)>,
        /// The dependencies the startup compile reported, as graph keys.
        initial_deps: Vec<PathBuf>,
    }

    /// Every directory armed and every baseline taken, with what every rebuild reads: made
    /// only by [`arm_deps_and_seed`].
    pub(super) struct Seeded {
        /// The sender the watcher was armed with, which Ctrl+C is wired to.
        tx: mpsc::Sender<Msg>,
        rx: mpsc::Receiver<Msg>,
        tick: Option<Duration>,
        session: FileSession,
    }

    /// A file-mode session once live ([`live::Session`]): what every rebuild reads, the
    /// watcher, the loop state, and how messages are coalesced.
    struct FileSession {
        ctx: FileCompileCtx,
        watcher: RecommendedWatcher,
        state: FileWatchState,
        debounce_ms: u64,
        clear: bool,
    }

    /// Record the working directory, check the `--vars` file and say what is watched; then
    /// arm the directories of the entry and the `--vars` file and take their baseline,
    /// before either is read.
    pub(super) fn arm_pre_read(
        entry: WatchedPath,
        output: Option<String>,
        args: SessionArgs,
    ) -> Result<Armed> {
        // Build runtime vars from the set_vars statics (vars file is reloaded each rebuild).
        let SessionArgs {
            out_dir,
            vars,
            set_vars: static_set_vars,
            set_string_vars: static_set_string_vars,
            clear,
            debounce_ms,
            quiet,
            tick,
        } = args;
        let working_dir = WorkingDir::record();
        // #326: keep the --vars argument as the user typed it, separately from the
        // canonicalized form below. `vars_path` (canonical) is used for everything that
        // must match notify's canonicalized event paths (dirs_to_watch, files_of_interest,
        // event matching); `vars_path_typed` is used only for `RuntimeVarArgs.vars`, so
        // the vars-file duplicate-key warning ("{path} = the --vars arg as typed")
        // displays and reads through the same path the user gave — reading a valid,
        // possibly symlinked path is fine either way, only the DISPLAYED text differs.
        let vars_path_typed = vars.clone();
        // Canonicalize so path matches notify event paths (resolves /tmp → /private/tmp on
        // macOS). Also rejects a symlinked vars file at startup (build parity).
        let vars_path = canonicalize_vars_path(vars).map_err(miette::Error::from)?;

        if !quiet {
            crate::output::ewriteln!("Watching {}", safe_path(&entry.typed));
        }

        // ── Arm before publish (startup race) ─────────────────────────────────
        //
        // GUARANTEED for the entry and the vars file: the directory watch is armed and
        // the `(mtime, size)` baseline captured strictly BEFORE either is first read.
        // Both are knowable from the command line, so both happen here, ahead of
        // `build_runtime_vars` (reads vars) and `compile_and_write` (reads the entry),
        // which [`startup_compile`] runs given the [`Armed`] this returns.
        //
        // NOT guaranteed for dependencies. A dep only becomes known when the compile
        // reports it, so a dep whose directory is not the entry's or the vars file's is
        // armed — and has its baseline taken — only *after* the compile has already read
        // it (see the post-compile arming loop and the baseline merge in
        // [`arm_deps_and_seed`]). An edit to such a dep inside that window is still
        // invisible to both detectors. Deps that happen to sit in an already-armed
        // directory are covered by the OS watch from the start; cross-directory deps are
        // the residual, and are what `MDS_TEST_READY` exists to let the integration suite
        // synchronise past.
        //
        // The watcher used to be created *after* the initial compile so the dedup
        // baseline was recorded "before any FSEvents arrive". That ordering left a
        // window — output written → watcher armed → baseline snapshotted — in which an
        // edit generated no event at all: inotify was not yet armed, so there was
        // nothing to deliver it to. A user who saved during startup saw no rebuild.
        //
        // Whether that was *late* or *permanent* was decided by the liveness probe, and
        // NOT by the poisoned baseline: `liveness_probe_file` returns `recovery ||
        // changed`, and `recovery` is true on `first_tick` unconditionally — so on an
        // idle tree the first tick rebuilt and the edit was recovered regardless of what
        // the baseline held. What made it permanent is that the tick may never arrive:
        // `recv_timeout` restarts its deadline on every message, so a steady stream of
        // irrelevant events in the watched tree starves the probe indefinitely. That
        // starvation is tracked separately as #319; closing this window is what stops it
        // being reachable from a normal startup.
        //
        // Arming first means the watcher may observe the compile's own reads and the
        // startup output write. Three pre-existing guards cover that, and each is
        // still load-bearing here:
        //   1. `is_content_event` drops every `Access(_)` event, which is exactly
        //      what a source-file *read* produces on Linux (IN_OPEN / IN_ACCESS /
        //      IN_CLOSE_NOWRITE). The startup compile can no longer busy-loop itself.
        //   2. `event_is_relevant` filters to `files_of_interest` — entry, deps and
        //      the vars file. The startup output write (and the temp sibling that
        //      `atomic_write_file` renames over it) is never in that set.
        //   3. `last_written` content-dedup is seeded by [`arm_deps_and_seed`], before
        //      the event loop begins. Queued events are only *processed* inside the
        //      loop, so any event that survives guards 1 and 2 recompiles to identical
        //      content and is suppressed without a write or a status line.
        // Worst case is therefore one redundant compile that dedups to no write.
        let (tx, rx) = mpsc::channel::<Msg>();
        let tx_fs = tx.clone();
        let mut watcher = RecommendedWatcher::new(
            move |res| {
                crate::output::panic_in_handler("notify");
                let _ = tx_fs.send(Msg::Fs(res));
            },
            notify::Config::default(),
        )
        .map_err(|e| {
            miette::miette!(
                "failed to initialize file watcher: {}",
                safe_inline(notify_cause(&e))
            )
        })?;

        // Arm the directories that are knowable before any read: the entry's parent
        // and the vars file's parent. Dependency dirs are unknown until the compile
        // reports them and are armed immediately afterwards.
        //
        // Best-effort here — a dir that is missing or fails to arm is re-attempted by
        // the post-compile loop in [`arm_deps_and_seed`], which owns the hard-error
        // contract for the full dir set. Splitting it this way keeps startup failure
        // messages identical to the pre-reorder behaviour.
        let mut watched_dirs: BTreeSet<PathBuf> = BTreeSet::new();
        for dir in dirs_to_watch(&entry.canonical, &[], vars_path.as_deref()) {
            if dir.exists() && watcher.watch(&dir, RecursiveMode::NonRecursive).is_ok() {
                watched_dirs.insert(dir);
            }
        }

        // Capture the entry/vars baseline BEFORE the first read of either. Both
        // `build_runtime_vars` (reads the vars file) and `compile_and_write` (reads
        // the entry) come after this point, so an edit landing during startup leaves
        // this snapshot strictly older than the file — and the liveness probe sees it.
        let pre_mtimes = snapshot_state(&files_of_interest(
            &entry.canonical,
            &[],
            vars_path.as_deref(),
        ));
        let entry_was_missing = !entry.canonical.exists();

        Ok(Armed {
            entry,
            output,
            out_dir,
            working_dir,
            vars_path,
            vars_path_typed,
            static_set_vars,
            static_set_string_vars,
            quiet,
            clear,
            debounce_ms,
            tick,
            tx,
            rx,
            watcher,
            watched_dirs,
            pre_mtimes,
            entry_was_missing,
        })
    }

    /// The startup compile, once [`arm_pre_read`] has armed what it reads, and its write.
    /// A compile or write error is reported, and watching continues. `Break` when stdout's
    /// reader is gone: the session stops, and the `Armed` comes back with the reason so
    /// its watches are dropped where they were before, after the stop line.
    pub(super) fn startup_compile(
        armed: Armed,
    ) -> Result<ControlFlow<(StopReason, Armed), Compiled>> {
        let Armed {
            entry,
            output,
            out_dir,
            vars_path,
            vars_path_typed,
            static_set_vars,
            static_set_string_vars,
            quiet,
            ..
        } = &armed;
        let quiet = *quiet;

        // Initial compile: compile first, derive output path from kind (compile-then-route).
        // For explicit -o / --out-dir the path is determined by the flag.
        // For the default case (no explicit flag), the path depends on the output kind,
        // which is only known after compilation — so we compile first, then derive.
        let resolved = build_runtime_vars(RuntimeVarArgs {
            vars: vars_path_typed.clone(),
            set_vars: static_set_vars.clone(),
            set_string_vars: static_set_string_vars.clone(),
        })?;
        emit_duplicate_var_warnings(&resolved, quiet);
        let runtime_vars = resolved.vars;

        // Load project config (for output_dir) — used if no explicit -o / --out-dir. By
        // the typed path, so a config error names `mds.json` as the input reaches it
        // (`./mds.json`), never by its canonical absolute path (#413); the config
        // directory it returns is canonical either way.
        let config = load_config(&entry.typed)?;

        // Initial compile: returns (output_path, deps, content).
        // content is captured here so the baseline block in [`arm_deps_and_seed`] can
        // reuse it without recompiling (issue 3 — avoids a redundant second compile at
        // startup). The outer `?` is an output route no rebuild can use — one that fails
        // to resolve, or the entry file itself (#425): refused at startup, exit 2, before
        // anything is written. A compile or write error is reported, and watching
        // continues.
        // The files every compile reads besides the entry's own: the `--vars` file and the
        // `mds.json` in force, which no output is written over (#425).
        let reads = run_reads(vars_path.as_deref(), config.as_ref());
        let startup =
            compile_and_write(entry, output, out_dir, &config, &reads, runtime_vars, quiet)?;
        // The route each output takes: an explicit `-o` names one whatever the kind;
        // without it, the route of each kind is resolved now and every output takes its
        // own kind's (#257, #160) — after a startup compile that failed, whose kind is
        // unknown, and when an edit changes the kind — so a `.json` output is never
        // written to `.md`. A route that fails to resolve is refused here, exit 2: no
        // rebuild could write anywhere else. Every rebuild refuses and reports a route
        // that is the entry (#425).
        let route_of = |kind| {
            resolve_output_path_for_kind(Some(entry.paths()), output, out_dir, &config, kind)
        };
        // What the startup wrote and where, if it wrote, and the dependencies its compile
        // reported.
        let (initial_written, initial_deps) = match startup {
            CompileWriteOutcome::Written((output_path, deps, content)) => {
                (Some((output_path, content)), deps)
            }
            // stdout's reader is gone before the session went live: it stops, and its
            // verdict is 0 — a closed pipe never changes the exit code (#157).
            CompileWriteOutcome::StdoutClosed => {
                return Ok(ControlFlow::Break((StopReason::StdoutClosed, armed)));
            }
            // Compiled and routed, but not written: report it and keep watching, with the
            // dependencies the compile reported — an edit to one rebuilds (#257). Nothing
            // was written, so the dedup map stays empty and the next rebuild writes even
            // when its output has not changed.
            CompileWriteOutcome::WriteFailed { deps, failure } => {
                settle_startup_error(StartupInto::File, failure, &entry.canonical);
                (None, deps)
            }
            CompileWriteOutcome::CompileFailed(e) => {
                // Initial compile error: print and continue watching (entry dir still
                // watched). Nothing is written now.
                settle_startup_error(StartupInto::File, e, &entry.canonical);
                if output.is_some() {
                    // An explicit `-o` names the route whatever the kind. Its refusal is
                    // dropped here: admitting it only decides whether the `-o` extension
                    // warning, which announces a write, is printed — never for an output
                    // that is the entry.
                    let _ = admit_output(
                        written_path(&route_of(OutputKind::Markdown)?),
                        entry.paths(),
                        output,
                        OutputKind::Markdown,
                        quiet,
                    );
                }
                (None, vec![])
            }
        };
        let output_route = if output.is_some() {
            OutputRoute::Named(route_of(OutputKind::Markdown)?)
        } else {
            OutputRoute::ByKind {
                markdown: route_of(OutputKind::Markdown)?,
                messages: route_of(OutputKind::Messages)?,
            }
        };

        Ok(ControlFlow::Continue(Compiled {
            armed,
            config,
            reads,
            output_route,
            initial_written,
            initial_deps,
        }))
    }

    /// Take the baseline of the dependencies the startup compile reported and arm their
    /// directories — one that cannot be armed ends the session at startup — then seed what
    /// every rebuild reads: the content-dedup map, the files of interest and the merged
    /// baseline.
    pub(super) fn arm_deps_and_seed(compiled: Compiled) -> Result<Seeded> {
        let Compiled {
            armed,
            config,
            reads,
            output_route,
            initial_written,
            initial_deps,
        } = compiled;
        let Armed {
            entry,
            output,
            out_dir,
            working_dir,
            vars_path,
            vars_path_typed,
            static_set_vars,
            static_set_string_vars,
            quiet,
            clear,
            debounce_ms,
            tick,
            tx,
            rx,
            mut watcher,
            mut watched_dirs,
            mut pre_mtimes,
            entry_was_missing,
        } = armed;

        // Baseline the dependencies the compile just reported, before anything else runs.
        //
        // The entry and vars baselines precede their own reads ([`arm_pre_read`]); a
        // dependency's cannot, because the compile is what discovers the dependency
        // exists. Taking it here rather than with the post-compile snapshot below shrinks
        // the window in which an edit to a dependency is invisible to the baseline from
        // "the rest of startup" to the gap between the compile returning and this loop.
        // `baseline_path` keeps the older of any two entries.
        //
        // HONEST SCOPE: this is defence in depth and has **no measured observable effect**
        // today. `liveness_probe_file` returns `recovery || changed` with `recovery`
        // including `first_tick`, so file mode's first tick rebuilds unconditionally and
        // recovers such an edit whatever the baseline says — an arm with this loop removed
        // still passed the covering test 10/10. What it buys is that `last_mtimes` means
        // what its name says, so the probe stays correct if that unconditional first-tick
        // rebuild is ever removed. Directory mode has no such fallback, which is why the
        // equivalent capture there is load-bearing and measured (#321).
        for dep in &initial_deps {
            baseline_path(dep, &mut pre_mtimes);
        }

        // The startup output is now published — the positive-control injection point.
        startup_race_probe();

        // Arm the dependency directories the compile just reported. Dirs already armed by
        // [`arm_pre_read`] are skipped; anything still unarmed — including a pre-arm
        // attempt that failed — is a hard startup error, as it was before the reorder.
        let init_dirs = dirs_to_watch(&entry.canonical, &initial_deps, vars_path.as_deref());
        let unarmed: Vec<PathBuf> = init_dirs.difference(&watched_dirs).cloned().collect();
        for dir in unarmed {
            match watcher.watch(&dir, RecursiveMode::NonRecursive) {
                Ok(()) => {
                    watched_dirs.insert(dir);
                }
                Err(e) => {
                    let vars = vars_dir_paths(vars_path.as_deref(), vars_path_typed.as_deref());
                    return Err(miette::miette!(
                        "failed to watch directory {}: {}\n\
                         hint: on Linux you may need to increase fs.inotify.max_user_watches",
                        safe_path(&shown_watched_dir(&dir, entry.dir_paths(), vars)),
                        safe_inline(notify_cause(&e))
                    ));
                }
            }
        }

        // Record the dedup baseline. The event loop has not started, so nothing can
        // consult this map before it is populated (guard 3 in [`arm_pre_read`]).
        // Reuse the content the startup wrote (issue 3 — no second compile needed), an
        // empty one included: what the startup wrote is the session's, as a rebuild's is
        // (#160). When the initial compile or write failed nothing was written:
        // last_written stays empty, so the next successful rebuild writes, and is no
        // change of kind.
        let mut last_written: HashMap<OutputKey, String> = HashMap::new();
        let written_to = initial_written.map(|(written, content)| {
            let key = OutputKey::of(written.as_ref());
            last_written.insert(key.clone(), content);
            key
        });

        let foi = files_of_interest(&entry.canonical, &initial_deps, vars_path.as_deref());

        // Build pre-loop FileWatchState (mtime snapshot + edge-trigger seeds).
        let missing_watched_dirs: BTreeSet<PathBuf> = {
            let desired = dirs_to_watch(&entry.canonical, &[], vars_path.as_deref())
                .union(&watched_dirs)
                .cloned()
                .collect::<BTreeSet<_>>();
            desired.into_iter().filter(|d| !d.exists()).collect()
        };

        // Merge the two baselines. Dependencies are only discovered by the compile, so
        // theirs is captured now; the entry/vars entries taken before the compile
        // overwrite the fresh ones because they are strictly older. That is what makes
        // an edit landing anywhere inside the startup window still register as a
        // difference on the first liveness tick.
        let mut last_mtimes = snapshot_state(&foi);
        // Witness for the assertion below. The merge DIRECTION is the load-bearing part:
        // only the pre-compile pair predates an edit that landed during startup, so
        // inverting the merge (or switching to an `or_insert`-style one that keeps the
        // value already present) silently restores the lost-save bug while every test
        // still passes. `entry.canonical` is inserted verbatim by `files_of_interest`, so
        // this lookup hits. The previous assertion here compared the key sets of
        // `files_of_interest(entry, &[], vars)` and `files_of_interest(entry, &deps, vars)`
        // — a subset relation those two calls guarantee by construction, so it could
        // never fail and guarded nothing.
        let entry_pre = pre_mtimes.get(&entry.canonical).copied();
        last_mtimes.extend(pre_mtimes);
        debug_assert_eq!(
            last_mtimes.get(&entry.canonical).copied(),
            entry_pre,
            "baseline merge inverted: the entry's pre-compile (mtime, size) must survive \
             the merge with the post-compile snapshot, or an edit made during startup can \
             never register as a difference"
        );

        let state = FileWatchState {
            // armed_dirs mirrors watched_dirs at startup: all dirs that were successfully
            // registered in the loop above are considered armed (reconcile rule idle-O(1)
            // fix).
            armed_dirs: watched_dirs.clone(),
            watched_dirs,
            foi,
            last_mtimes,
            hold: EmptyHold::Off,
            last_written,
            written_to,
            kept: None,
            output: output_route,
            // After the startup write, so the directory it made is the one the first
            // rebuild compares; `-o` names its own path, which no out-dir is below.
            out_dir: if output.is_some() {
                None
            } else {
                OutDirAnchor::record(out_dir.as_deref(), config.as_ref())
            },
            entry_was_missing,
            first_tick: true,
            missing_watched_dirs,
        };

        // What every rebuild and liveness tick reads, fixed for the session.
        let ctx = FileCompileCtx {
            entry,
            working_dir,
            vars_path,
            vars_path_typed,
            reads,
            static_set_vars,
            static_set_string_vars,
            quiet,
        };

        Ok(Seeded {
            tx,
            rx,
            tick,
            session: FileSession {
                ctx,
                watcher,
                state,
                debounce_ms,
                clear,
            },
        })
    }

    impl Seeded {
        /// Every watch armed and every baseline taken: go live — Ctrl+C wired last — and
        /// watch until the session stops ([`live::run_session`]).
        pub(super) fn go_live(self) {
            let Seeded {
                tx,
                rx,
                tick,
                session,
            } = self;
            live::run_session(tx, rx, tick, session);
        }
    }

    impl live::Session for FileSession {
        fn is_quiet(&self) -> bool {
            self.ctx.quiet
        }

        fn hold_deadline(&self) -> Option<Instant> {
            self.state.hold.deadline()
        }

        fn on_tick(&mut self) -> ControlFlow<StopReason> {
            // Idle tick — run liveness probe (reconcile rule).
            if liveness_probe_file(&self.ctx, &mut self.watcher, &mut self.state) {
                rebuild_file(&self.ctx, &mut self.watcher, &mut self.state, None)
            } else {
                ControlFlow::Continue(())
            }
        }

        fn on_hold_due(&mut self) -> ControlFlow<StopReason> {
            // The rebuild decides the hold first, at an instant no earlier than its
            // deadline, so it ends the hold whatever the files hold or the clock does
            // (#380).
            let due = self.state.hold.deadline();
            rebuild_file(&self.ctx, &mut self.watcher, &mut self.state, due)
        }

        fn on_message(&mut self, msg: Msg, rx: &mpsc::Receiver<Msg>) -> ControlFlow<StopReason> {
            let action =
                handle_fs_event_file(msg, &self.state.foi, rx, self.debounce_ms, self.clear);
            match action {
                FileEventAction::Skip => ControlFlow::Continue(()),
                FileEventAction::Stop => ControlFlow::Break(StopReason::Interrupted),
                FileEventAction::Rebuild => {
                    rebuild_file(&self.ctx, &mut self.watcher, &mut self.state, None)
                }
            }
        }
    }
}

// ── Directory watch ───────────────────────────────────────────────────────────

const MAX_COLLECT_DEPTH: usize = 64;

/// Mutable state for the directory-mode watch loop.
struct DirWatchState {
    /// Forward dependency map: canonical source → its canonical (transitive) deps.
    /// Dep values are graph keys already: every compile's list goes through
    /// [`graph_keys`]; do not re-canonicalize.
    forward_deps: HashMap<PathBuf, Vec<PathBuf>>,
    /// Sources whose last compile attempt failed. Re-seeded into every batch that
    /// carries a real change, so a fix to whatever broke them is picked up — and stamped by
    /// every batch's look, so none is stamped after that compile read it (#380).
    errored: HashSet<PathBuf>,
    /// Last-seen collected `.mds` set for reconcile/rename detection.
    known_files: BTreeSet<PathBuf>,
    /// By the path each output is written to (`WriteTarget.path`): what this session last
    /// wrote there and for which source — what a later write for that source may skip as
    /// unchanged, the proof a removal or a write after a change of kind asks for, and
    /// whose output the file is (#160). An entry goes when its file is removed, another
    /// source's write replaces it, or its source is forgotten; a file kept stays its
    /// source's.
    last_written: HashMap<PathBuf, WrittenOutput>,
    /// The output each source last had written this session, by source: where a deleted
    /// source's outputs are looked for (#160). A source with no entry — a partial, a
    /// dependency outside the root, one never written — has none to remove; what is where
    /// a source never written would have its outputs is kept, with a notice
    /// ([`DirWatchState::retire_deleted`]).
    outputs: HashMap<PathBuf, WriteTarget>,
    /// By source: what its last rebuild kept from being written after a change of kind,
    /// the file there not being the session's (#160) — the next rebuild of the same tries
    /// again but tells it no more. Any other rebuild of the source clears it, as does
    /// forgetting the source.
    kept: HashMap<PathBuf, String>,
    /// The out-dir every output is written below, checked before each write; `None` when
    /// outputs go beside their sources.
    out_dir: Option<OutDirAnchor>,
    /// The files every compile reads besides its source's own — the `--vars` file and the
    /// `mds.json` in force — which no output is written over (#425); each write adds the
    /// `mds.json` nearest its source ([`source_inputs`]).
    reads: Vec<PathBuf>,
    /// Parent dirs of dependencies located outside the watched root.
    /// Watched NonRecursive; re-armed by liveness probe.
    external_dep_dirs: BTreeSet<PathBuf>,
    /// The `--vars` file, canonical, if one is given: outside [`Self::tracked_paths`], but
    /// in [`Self::watched_set`], since a rebuild is held while it is empty as while a
    /// source is, and the idle tick looks for a change to it as to a source's (#380).
    vars_file: Option<PathBuf>,
    /// `(mtime, size)` baseline over [`DirWatchState::baselined_paths`] — sources,
    /// dependencies, the `--vars` file, the sources held back and the files a held compile
    /// read empty. Read by the idle tick's
    /// content backstop over the watched set, and by a batch to tell a file emptied since
    /// (#380); re-written at the end of every batch, so the tick reports only what the
    /// batch did not already handle (#321).
    last_mtimes: StampMap,
    /// The rebuild held while a watched file is empty (#380).
    hold: EmptyHold,
    /// What the batches held back carried, rebuilt with the batch that ends the hold — and
    /// what a batch the `--vars` file could not be read for carried, rebuilt with the next
    /// batch (#380).
    held: HeldBatch,
}

/// The paths a directory-mode rebuild covers, and whether one of them changed the `--vars`
/// file (#380): what a batch is from its look to its compiles, and what is kept
/// ([`HeldBatch`]) to be rebuilt with the next.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Batch {
    paths: BTreeSet<PathBuf>,
    vars_changed: bool,
}

/// What the batches held back while a watched file is empty carried (#380): every path
/// they named, and whether one changed the `--vars` file. A directory-mode hold holds the
/// whole batch back — a source that imports the emptied file, or reads the emptied vars
/// file, would compile against nothing — and the batch that ends the hold rebuilds what
/// they named with its own, so no change made during the hold waits for a later one.
///
/// A batch the `--vars` file cannot be read for is kept here too ([`HeldBatch::carry`]),
/// with no hold running, and the next batch rebuilds what it named — the one that fixes
/// the file compiles a source created meanwhile, which no other record names.
///
/// A source whose compile read a file emptied after the batch looked is held alone
/// ([`HeldBatch::hold_read_empty`]), and the file stays in the baseline's domain until the
/// hold ends ([`HeldBatch::read_empty`]): the truncation's own event starts a batch that
/// names it, and a dependency outside the root that the source imports for the first time is
/// no source and no dependency the session tracks, since the held compile recorded none.
#[derive(Debug, Default, PartialEq, Eq)]
struct HeldBatch {
    /// The paths of the batches held back.
    paths: BTreeSet<PathBuf>,
    /// The sources of the watch among them ([`names_a_source`]): of the paths held back, the
    /// ones the run reads that the watched files may not hold yet — a source no compile has
    /// read, or none has succeeded on — and so the ones the look stamps and the baseline keeps
    /// (#380). A path held back that the run reads otherwise is a watched file already; one
    /// nothing reads — a `.mds` file beside a dependency outside the root that no source
    /// imports — is rebuilt with the batch that ends the hold, but kept out of the baseline,
    /// so its emptying holds nothing.
    sources: BTreeSet<PathBuf>,
    /// The files the compiles held back read empty, after the look that stamped them whole:
    /// kept in the baseline like [`HeldBatch::sources`], so the look of a batch that names
    /// one finds it emptied and holds that batch too. A compile reads only files the run
    /// reads, so none of these is a file nothing reads.
    read_empty: BTreeSet<PathBuf>,
    /// Whether one of them changed the `--vars` file.
    vars_changed: bool,
}

impl HeldBatch {
    /// Hold `batch` back beside the batches held before it, a hold running; those of its
    /// paths that are sources of the watch below `root` are kept as [`HeldBatch::sources`]
    /// too.
    fn hold(&mut self, batch: &Batch, root: &Path) {
        for path in &batch.paths {
            if names_a_source(root, path) {
                self.sources.insert(path.clone());
            }
            self.paths.insert(path.clone());
        }
        self.vars_changed |= batch.vars_changed;
    }

    /// Carry `batch` to the next one, no hold running: a batch the `--vars` file could not
    /// be read for. It is kept as [`HeldBatch::hold`] keeps one, and released with it.
    fn carry(&mut self, batch: &Batch, root: &Path) {
        self.hold(batch, root);
    }

    /// Hold `source` back as [`HeldBatch::hold`] does, for a compile that read the files in
    /// `emptied` empty, and keep them in the baseline until the hold ends.
    fn hold_read_empty(&mut self, source: &Path, emptied: BTreeSet<PathBuf>, root: &Path) {
        let batch = Batch {
            paths: BTreeSet::from([source.to_path_buf()]),
            vars_changed: false,
        };
        self.hold(&batch, root);
        self.read_empty.extend(emptied);
    }

    /// The batch that ends the hold, or the next after a batch the vars file could not be
    /// read for: `batch` and every batch kept, with whether any of them changed the vars
    /// file. Nothing stays held, the files read empty included: they leave the baseline's
    /// domain with the hold.
    fn release(&mut self, batch: Batch) -> Batch {
        let held = std::mem::take(self);
        let mut paths = held.paths;
        paths.extend(batch.paths);
        Batch {
            paths,
            vars_changed: batch.vars_changed || held.vars_changed,
        }
    }
}

/// `batch` with the watched files a look found `emptied` joined to it (#380): the `--vars`
/// file as a change to it, every other file as a path of the batch — whether or not its own
/// event came — so the batch that ends a hold rebuilds it.
fn join_emptied(mut batch: Batch, emptied: &BTreeSet<PathBuf>, vars_file: Option<&Path>) -> Batch {
    let (vars, paths): (Vec<&PathBuf>, Vec<&PathBuf>) = emptied
        .iter()
        .partition(|path| Some(path.as_path()) == vars_file);
    batch.paths.extend(paths.into_iter().cloned());
    batch.vars_changed |= !vars.is_empty();
    batch
}

impl DirWatchState {
    /// Record a successful compile for `src` with the given dep paths and output content.
    ///
    /// Updates `forward_deps`, removes from `errored`, inserts into `known_files`,
    /// and updates `external_dep_dirs` for any deps outside `root`.
    fn record_success(
        &mut self,
        src: &Path,
        dep_paths: Vec<PathBuf>,
        root: &Path,
        out: Option<&WriteTarget>,
        content: Option<String>,
    ) {
        // Track external dep dirs (DD3 — cross-root).
        for dep in &dep_paths {
            if let Some(parent) = dep.parent() {
                if !parent.starts_with(root) {
                    self.external_dep_dirs.insert(parent.to_path_buf());
                }
            }
        }
        self.forward_deps.insert(src.to_path_buf(), dep_paths);
        self.errored.remove(src);
        self.known_files.insert(src.to_path_buf());
        if let (Some(out), Some(content)) = (out, content) {
            self.wrote(src, out, content);
        }
    }

    /// `content` was written to `out`, the output of `src`: what a later write for `src`
    /// may skip as unchanged and a removal asks the file to still hold, recorded as
    /// `src`'s — whichever source the session wrote there for before — and where the
    /// source's outputs are once it is deleted (#160).
    fn wrote(&mut self, src: &Path, out: &WriteTarget, content: String) {
        let written = WrittenOutput {
            source: src.to_path_buf(),
            content,
        };
        self.last_written.insert(out.path.clone(), written);
        self.outputs.insert(src.to_path_buf(), out.clone());
    }

    /// What the session's record says of the file at `path` for `src` (#160).
    fn record(&self, path: &Path, src: &Path) -> Record<'_> {
        match self.last_written.get(path) {
            None => Record::Unwritten,
            Some(written) if written.source == src => Record::Own(&written.content),
            Some(_) => Record::OtherSource,
        }
    }

    /// Retire `out`, an output `src` no longer has ([`retire_output`]), and drop the
    /// record of it once the file is gone, if the record was `src`'s (#160).
    fn retire(
        &mut self,
        src: &Path,
        out: &WriteTarget,
        now: OutDirNow,
        why: Retirement,
        quiet: bool,
    ) {
        let record = self.record(&out.path, src);
        let own = matches!(record, Record::Own(_));
        if retire_output(out, self.out_dir.as_ref(), now, record, why, quiet) && own {
            self.last_written.remove(&out.path);
        }
    }

    /// Record a compile error for `src`, **keeping** whatever dep set the last
    /// successful compile recorded (an empty one when there has never been one).
    ///
    /// Discarding the dep set here is what made a cross-root edit unrecoverable
    /// (#321). Every batch recomputes `external_dep_dirs` from `forward_deps`
    /// ([`Self::dep_dirs_outside`]), so clearing an importer's deps on a failed
    /// compile also dropped the external directory those deps live in. The next
    /// event for that directory was then rejected by `handle_fs_event_dir` as
    /// "neither under root nor in a known external dep dir", and the liveness probe
    /// went on to `unwatch()` the directory outright. A single compile against a
    /// half-written file — an editor's `O_TRUNC` open observed before its `write`
    /// lands — was enough to blind the watcher to that dependency for the rest of
    /// the session, with the failed compile as the only trace.
    ///
    /// The retained set is used only to decide what to *watch* and what to re-seed —
    /// never as a substitute for recompiling. It therefore only ever widens what may
    /// trigger a rebuild, and the cost of a stale edge is one recompile whose output
    /// the `last_written` dedup then suppresses. The freshness rule is about the
    /// dep set a *rebuild* records, and that still comes from fresh `compile_native_to_content`
    /// output on every success; a failed compile produces no fresh set to record.
    fn record_error(&mut self, src: &Path) {
        self.errored.insert(src.to_path_buf());
        self.forward_deps.entry(src.to_path_buf()).or_default();
    }

    /// The directories outside `root` that the recorded dependencies live in: what
    /// `external_dep_dirs` holds once a batch is done, so a directory no source imports
    /// from any more leaves it (#257).
    fn dep_dirs_outside(&self, root: &Path) -> BTreeSet<PathBuf> {
        self.forward_deps
            .values()
            .flatten()
            .filter_map(|dep| dep.parent())
            .filter(|parent| !parent.starts_with(root))
            .map(Path::to_path_buf)
            .collect()
    }

    /// Every path whose **content** the watcher must react to: all known sources
    /// plus every dependency they pull in, including cross-root ones outside the
    /// watched root — a dependency several sources import comes once for each.
    ///
    /// With the `--vars` file, these are the domain of the idle-tick content backstop and
    /// of the `last_mtimes` baseline that feeds it (#321, [`Self::watched_set`]).
    /// `known_files` alone cannot serve: it holds exactly what `collect_mds_files(root)`
    /// returns, so a cross-root dependency is never in it, and a probe diffing only that
    /// walk can see such a file appear or vanish but never *change*.
    fn tracked_paths(&self) -> impl Iterator<Item = &PathBuf> {
        self.known_files
            .iter()
            .chain(self.forward_deps.values().flatten())
    }

    /// [`Self::tracked_paths`], as a set.
    #[cfg(test)]
    fn tracked_set(&self) -> HashSet<PathBuf> {
        self.tracked_paths().cloned().collect()
    }

    /// The watched files: with the sources held back ([`Self::baselined_paths`]), every path
    /// whose emptying holds a batch back and the domain of the `last_mtimes` baseline (#380);
    /// alone, the domain of the idle tick's content backstop. [`Self::tracked_paths`] and the
    /// `--vars` file, which every compile reads — so a change to the vars file whose event
    /// was lost still reaches a batch (#380).
    fn watched_set(&self) -> HashSet<PathBuf> {
        self.watched_paths().cloned().collect()
    }

    /// [`Self::watched_set`]'s paths, borrowed, as a batch's look and its baseline go
    /// through them without building the set (#380): a dependency several sources import
    /// comes once for each.
    fn watched_paths(&self) -> impl Iterator<Item = &PathBuf> {
        self.tracked_paths().chain(self.vars_file.iter())
    }

    /// The domain of the `last_mtimes` baseline (#380): [`Self::watched_paths`], the
    /// sources of the batches held back ([`HeldBatch::sources`]) — a source a batch named
    /// before any compile of it succeeded, which its compile held, among them — and the files
    /// a compile held back read empty ([`HeldBatch::read_empty`]), so a source held keeps the
    /// stamp the look that named it took, and one emptied before the batch that ends the
    /// hold is found emptied by that batch's look, as a source the session compiled is. So
    /// is a file a held compile read empty, a dependency outside the root that a source
    /// imports for the first time among them, which the held compile recorded no edge for:
    /// the batch its truncation starts is held too. Every file in it is one the run reads: a
    /// path held back that nothing reads is no part of it, so its emptying holds nothing.
    fn baselined_paths(&self) -> impl Iterator<Item = &PathBuf> {
        self.watched_paths()
            .chain(&self.held.sources)
            .chain(&self.held.read_empty)
    }

    /// A batch whose `--vars` load failed (#380): a watched file emptied since the batch's
    /// look — the vars file the load read empty, a truncation that began between the two —
    /// holds the whole batch back as the look would have ([`held_after_look`]), every file
    /// found emptied joined to it, its own event lost or not ([`join_emptied`]). Returns
    /// whether the batch was held; nothing else is recorded, and nothing is held when the
    /// deadline ended the hold in this rebuild. The vars file is found emptied by the byte
    /// count its load read (`reads`, [`read_empty`]); the other watched files, which nothing
    /// read, by a `stat`.
    fn hold_after_vars_load_failed(
        &mut self,
        batch: &Batch,
        root: &Path,
        reads: &mds::ReadLog,
    ) -> bool {
        let watched = self.watched_set();
        let mut emptied = emptied_paths(&watched, &self.last_mtimes);
        emptied.extend(read_empty(reads, &self.last_mtimes));
        let Some(emptied) = held_after_look(&mut self.hold, emptied) else {
            return false;
        };
        let batch = join_emptied(batch.clone(), &emptied, self.vars_file.as_deref());
        self.held.hold(&batch, root);
        true
    }

    /// Hold `src` back, a compile of it having read a file emptied since the batch looked
    /// (#380): nothing is written or recorded, and what the rebuild before kept from being
    /// written (`kept_before`) stays kept, to be told again as it would have been. The files
    /// in `read_empty` stay in the baseline until the hold ends
    /// ([`HeldBatch::hold_read_empty`]).
    fn hold_back(
        &mut self,
        src: &Path,
        kept_before: Option<String>,
        read_empty: BTreeSet<PathBuf>,
        root: &Path,
    ) {
        let source = src.to_path_buf();
        if let Some(kept) = kept_before {
            self.kept.insert(source.clone(), kept);
        }
        self.held.hold_read_empty(&source, read_empty, root);
    }

    /// Take the baseline over [`Self::baselined_paths`] again, from the stamps the batch's
    /// look took ([`baseline_over`], #380): only a file no look stamped is stamped now.
    fn rebaseline(&mut self) {
        let taken = std::mem::take(&mut self.last_mtimes);
        self.last_mtimes = baseline_over(taken, self.baselined_paths());
    }

    /// Remove every GRAPH record of `src` — its forward edges, its error flag and its
    /// known-files membership.
    fn forget_graph(&mut self, src: &Path) {
        self.forward_deps.remove(src);
        self.errored.remove(src);
        self.known_files.remove(src);
    }

    /// Remove all state for `src`, a source that is gone: its graph records, the record of
    /// where its output is, and the records of what the session wrote for it, so nothing
    /// written for it is this session's to remove any more (#160) — a file another source
    /// was written to since keeps that source's record. The outputs are the ones recorded
    /// when they were written, never ones guessed from the source's path: a dependency
    /// outside the root has none (#217). A source's records are only ever at its outputs
    /// of the two kinds.
    fn forget(&mut self, src: &Path) {
        if let Some(out) = self.outputs.remove(src) {
            for kind in [OutputKind::Markdown, OutputKind::Messages] {
                let path = out.path.with_extension(kind.extension());
                if self
                    .last_written
                    .get(&path)
                    .is_some_and(|written| written.source == src)
                {
                    self.last_written.remove(&path);
                }
            }
        }
        self.kept.remove(src);
        self.forget_graph(src);
    }

    /// Retire the outputs of `src`, a deleted source, and forget it (#160): the output it
    /// was last written to and the other kind's beside it, each removed only if this
    /// session wrote it for `src` and it is unchanged, or else kept ([`retire_output`]) —
    /// one the session last wrote for another source is that source's. A source the
    /// session never wrote an output for — its compile, or every write, failed for the
    /// whole session — has its outputs where a write below `watch_root` would put them
    /// ([`output_path_for`] with `output_base`): nothing the session wrote is there for it,
    /// so whatever is there is kept, with its notice. A partial has none. A source that is
    /// there again — unlinked and created anew within the batch, as an editor's save, a
    /// branch checkout or `git stash` does — keeps its output and its state: the event that
    /// created it rebuilds it.
    fn retire_deleted(
        &mut self,
        src: &Path,
        watch_root: &WatchedPath,
        output_base: &OutputBase,
        quiet: bool,
    ) {
        if src.exists() {
            return;
        }
        // A source still known — walked, or errored — and not forgotten already by an
        // earlier batch of the same deletion, whose notices were told then.
        let known = self.known_files.contains(src) || self.errored.contains(src);
        let out = match self.outputs.get(src) {
            Some(out) => Some(out.clone()),
            // Only a source below the root has outputs, so this never takes the flattened
            // arm of a source outside it, nor reports it (#217).
            None if known
                && classify(&watch_root.canonical, src, &self.external_dep_dirs)
                    == Node::Source =>
            {
                Some(output_path_for(
                    src,
                    watch_root.root_paths(),
                    output_base,
                    OutputKind::Markdown.extension(),
                ))
            }
            None => None,
        };
        if let Some(out) = out {
            let now = check_out_dir(self.out_dir.as_mut(), &mut self.last_written);
            for kind in [OutputKind::Markdown, OutputKind::Messages] {
                let candidate = out.sibling(|path| path.with_extension(kind.extension()));
                self.retire(src, &candidate, now, Retirement::SourceDeleted, quiet);
            }
        }
        self.forget(src);
    }
}

/// State for the dir-mode liveness probe (reconcile rule).
struct LivenessState {
    /// Set to true on the very first tick so we do a reconcile after startup.
    first_tick: bool,
    /// Tracks whether the root existed on the previous tick.
    root_was_missing: bool,
    /// Whether the OS watcher was successfully armed for the root on the last tick.
    ///
    /// Mirrors the `armed_dirs` discipline from file mode: skip `watcher.watch(root, …)`
    /// on healthy ticks so the OS-level re-WalkDir / FSEvents stream teardown does not
    /// happen every idle tick — O(1) idle cost regardless of subtree size (reconcile rule).
    root_armed: bool,
    /// External dep dirs that were missing on the previous tick.
    ///
    /// Recovery is **edge-triggered**: a missing external dir triggers a full
    /// reconcile only when it *reappears* (vanish→reappear), never while it stays
    /// missing. A permanently-missing external dir must NOT force an O(tree) walk
    /// on every idle tick (reconcile rule / AC-P1).
    missing_external_dirs: BTreeSet<PathBuf>,
    /// The directories outside the root that the OS watcher holds, non-recursively: the
    /// dependencies' and the `--vars` file's — one entry for a directory both share, as
    /// file mode's `armed_dirs` holds them.
    ///
    /// A directory is watched only while it is not held here (#257): a repeat watch of a
    /// held path is no no-op — macOS restarts its event stream, dropping the events that
    /// land meanwhile, and Windows opens another handle, which delivers every event once
    /// more. One that vanishes leaves the set with no `unwatch` — its watch went with it —
    /// so it is watched once more when it comes back. Used to call `watcher.unwatch()` when a
    /// dependency's directory is pruned from `state.external_dep_dirs` (e.g. because a
    /// cross-root @import was edited away), which prevents inotify/FSEvents watch leaks for
    /// the process lifetime (avoids approaching `fs.inotify.max_user_watches`). Mirrors the
    /// `resync_watches` discipline from file mode.
    armed_dirs: BTreeSet<PathBuf>,
    /// The dependencies' directories outside the root whose last watch failed and was
    /// reported ([`arm_dir`]): each is reported once for as long as its watch keeps failing
    /// — until a watch of it succeeds, or no source imports from it any more (#257).
    failing_dirs: BTreeSet<PathBuf>,
}

/// The variables a directory batch compiles its sources with, and the `--vars` file's
/// duplicate keys, reported once for the batch by the first of its sources that shows
/// something — its `Recompiled` line, a `Kept` notice it prints, or its failed write's
/// report — as a file rebuild reports them (#326): never by a batch that shows nothing,
/// such as one of the batches a single save at `--debounce 0` starts after the first, or
/// the idle tick's for the same edit, which find the output unchanged.
struct BatchVars<'a> {
    /// The variables, given to every compile of the batch.
    map: &'a Option<HashMap<String, mds::Value>>,
    /// What the variables were resolved from, while the duplicate keys of its `--vars` file
    /// are still to be reported for the batch: `None` once they are.
    unreported: Option<&'a RuntimeVars>,
}

impl<'a> BatchVars<'a> {
    /// The variables `resolved` holds, its `--vars` file's duplicate keys still to report.
    fn of(resolved: &'a RuntimeVars) -> Self {
        Self {
            map: &resolved.vars,
            unreported: Some(resolved),
        }
    }

    /// The variables `map` holds, with no duplicate keys to report: a unit test's batch.
    #[cfg(test)]
    fn map_only(map: &'a Option<HashMap<String, mds::Value>>) -> Self {
        Self {
            map,
            unreported: None,
        }
    }

    /// A source of the batch shows something: report the duplicate keys, unless the batch
    /// has reported them already. `--quiet` prints none.
    fn shown(&mut self, quiet: bool) {
        if let Some(resolved) = self.unreported.take() {
            crate::build::emit_duplicate_vars_file_warnings(resolved, quiet);
        }
    }
}

/// What every source of one directory batch is compiled and shown with: the watched
/// directory, where an output below it is named, the batch's variables and `--quiet`.
/// [`run_dir_batch`] builds it once for a batch, from the session's [`DirWatchCtx`] and the
/// variables it has just resolved.
struct BatchCtx<'a> {
    /// The watched directory ([`Watched::Root`]).
    watch_root: &'a WatchedPath,
    /// What an output below the root is named by.
    output_base: &'a OutputBase,
    /// The variables the batch compiles with, and the `--vars` file's duplicate keys it
    /// has still to report.
    vars: BatchVars<'a>,
    /// Whether `--quiet` is set.
    quiet: bool,
}

/// Compile a single in-root source file, update `state`, and optionally write output.
///
/// This is the shared kernel for both the `vars_changed` full-recompile loop and the
/// per-affected-source incremental loop in `process_dir_batch` — collapsing the
/// 2× duplicated compile→dedup→write block inside that function.
///
/// A partial refreshes the graph and writes no output of its own; any other source's
/// output is written when its content changed. A compile that succeeds records the
/// dependencies it reported even when its write fails (#257). A compile that fails
/// because `src` is gone since the batch found it there retires it as a deleted source
/// ([`DirWatchState::retire_deleted`], #160). A compile that read a file emptied since the
/// batch looked — whether it then failed or would write — holds `src` back, unless the
/// deadline ended the hold in this rebuild ([`held_after_look`], #380). Either way the
/// files it read empty stay in the baseline until the hold ends
/// ([`HeldBatch::hold_read_empty`]). A source
/// whose output is written, kept with a notice, or not written with a report shows
/// something: the batch's `--vars` duplicate keys are reported with it, before its
/// `Recompiled` line, after the notice, or before the report, unless an earlier source of
/// the batch reported them ([`BatchVars`], #326).
///
/// # Invariants preserved
/// - Freshness rule: dep set recomputed from fresh `compile_native_to_content` output.
/// - All source reads go through `compile_native_to_content`.
///
/// Does **not** touch `state.last_mtimes`: the content backstop's baseline is settled
/// once per batch by `process_dir_batch`, over the whole watched set (#321).
///
/// Compile success/failure is already signalled via `state.errored`; the caller uses
/// that set for error tracking.
fn compile_one_source(src: &Path, ctx: &mut BatchCtx<'_>, state: &mut DirWatchState) {
    let BatchCtx {
        watch_root,
        output_base,
        quiet,
        ..
    } = *ctx;
    let root = watch_root.canonical.as_path();
    let t0 = Instant::now();
    // What the rebuild of `src` before this one kept from being written (#160): told again
    // unless this rebuild keeps the same once more, as another event of the same save does.
    let kept_before = state.kept.remove(src);
    // A debug build's test pause (#160): the batch found `src` there, and has not read it.
    pause_after_batch_split();
    let reads = Arc::new(mds::ReadLog::new());
    let compiled = watch_root.compile_source(src, ctx.vars.map.clone(), quiet, &reads);
    // A debug build's test pause (#380): the reads are done, the late look is not.
    pause_before_late_look();
    let compiled = match compiled {
        Ok(compiled) => compiled,
        // The source went after the batch found it there (#160): whatever the compile
        // said of a file that is no longer there — `file not found`, or a read that
        // failed — it is a deleted source, retired by the same rule, never a compile
        // error. A source still there, or one whose presence cannot be told, fails as
        // any other compile does.
        Err(CompileFailure::Error(_)) if matches!(src.try_exists(), Ok(false)) => {
            state.retire_deleted(src, watch_root, output_base, quiet);
            return;
        }
        Err(failure) => {
            // #380: a file the compile read empty, which the baseline saw with bytes — a
            // truncation that began between the batch's look and the read, failed on —
            // holds `src` back as the look would have, unless the deadline ended the hold in
            // this rebuild: nothing reported or recorded, `src` kept to be rebuilt with the
            // batch that ends the hold, and the files it read empty kept in the baseline until
            // then, as for a compile that would write. The byte counts the reads gave decide
            // ([`read_empty`]).
            if let Some(read_empty) =
                held_after_look(&mut state.hold, read_empty(&reads, &state.last_mtimes))
            {
                state.hold_back(src, kept_before, read_empty, root);
                return;
            }
            settle(
                SettleInto::Dir(state),
                failure.into_report(),
                Settle::MarkErrored(src),
            );
            return;
        }
    };
    let dep_paths = graph_keys(&compiled.dependencies);

    // Partials (DD2): refresh graph edges but do NOT write output.
    if is_partial(src) {
        state.record_success(src, dep_paths, root, None, None);
        return;
    }

    // Derive the output path from the compiled kind (intrinsic extension).
    // AC-FUNC-23: a @message template writes .json; a plain template writes .md.
    //
    // Invariant: `src` is strictly below `root`, so this never takes the
    // out-of-root flatten arm and never emits its report (#217). Every path that
    // reaches here is a source: one `names_a_source` admits, in both passes, or a
    // known one in `process_dir_batch_vars_changed`; out-of-root deps take the
    // dep-refresh-only branch and in-root ones that are no source are left to their
    // importers, so neither calls this function (#380).
    let ext = compiled.kind.extension();
    let out = output_path_for(src, watch_root.root_paths(), output_base, ext);

    let out_dir = check_out_dir(state.out_dir.as_mut(), &mut state.last_written);

    // A change of kind (#160): the output this session last wrote for `src` is
    // the other kind's, so the file at `out` is written over only if it is the
    // session's own, written for `src`.
    let previous = state
        .outputs
        .get(src)
        .filter(|last| last.path != out.path)
        .cloned();
    // Content-based dedup: skip the write when the session last wrote the same
    // there for `src` — never after a change of kind, whose write is decided by the
    // file there whatever the record of it holds.
    let content_changed =
        previous.is_some() || state.record(&out.path, src) != Record::Own(&compiled.content);
    // Whether the write empties the output the session wrote there for `src`,
    // decided before the write replaces the record (#380).
    let emptied = match state.record(&out.path, src) {
        Record::Own(before) => empties_output(Some(before), &compiled.content),
        Record::Unwritten | Record::OtherSource => false,
    };

    if !content_changed {
        // Content unchanged — still refresh graph edges + known_files.
        state.record_success(src, dep_paths, root, None, None);
        return;
    }
    // #380: a file the compile read empty, which the baseline saw with bytes — a
    // truncation that began between the batch's look and the read — holds `src` back as
    // the look would have, unless the deadline ended the hold in this rebuild: nothing
    // written or recorded, `src` kept to be rebuilt with the batch that ends the hold, and
    // the files it read empty kept in the baseline until then. The byte counts the reads
    // gave decide ([`read_empty`]). The batch's `--vars` load parsed a JSON object, so it
    // did not read the vars file empty.
    if let Some(read_empty) =
        held_after_look(&mut state.hold, read_empty(&reads, &state.last_mtimes))
    {
        state.hold_back(src, kept_before, read_empty, root);
        return;
    }
    // The rebuild of `src` before this one kept the same from being written
    // (#160): told already.
    let told = kept_before.as_ref() == Some(&compiled.content);
    let written = write_rebuilt(
        &out,
        state.out_dir.as_ref(),
        out_dir,
        previous.is_some().then(|| ChangeOfKind {
            record: state.record(&out.path, src),
            told,
        }),
        &compiled.content,
        || source_inputs(src, &compiled.dependencies, &state.reads),
        quiet,
    );
    match written {
        // Kept: nothing is written and nothing retired, and the record of the
        // old kind's output stays, so a later save tries again. A notice told
        // shows something, a kept rebuild that tells nothing does not (#326).
        Ok(Rewritten::Kept) => {
            if !told {
                ctx.vars.shown(quiet);
            }
            state.kept.insert(src.to_path_buf(), compiled.content);
            state.record_success(src, dep_paths, root, None, None);
            return;
        }
        // The compile succeeded: the dependencies it reported are the
        // source's now, as at startup, so an edit to one of them rebuilds
        // it — one outside the root included (#257). Nothing is recorded
        // as written, and the source is marked errored and the failure
        // reported, which shows something (#326).
        Err(e) => {
            state.record_success(src, dep_paths, root, None, None);
            ctx.vars.shown(quiet);
            settle(SettleInto::Dir(state), Some(e), Settle::MarkErrored(src));
            return;
        }
        Ok(Rewritten::Written) => {}
    }
    ctx.vars.shown(quiet);
    if let Some(anchor) = &mut state.out_dir {
        anchor.written();
    }
    announce_recompiled(&out.shown, compiled.dependencies.len(), t0, emptied, quiet);
    // A change of kind (#160): the output the session last wrote for
    // `src`, the other kind's, is retired — removed only if the
    // session's record says it wrote it for `src` and it still holds
    // what was written, else kept with a notice: one the session wrote
    // for another source (beside its sources `a.b.mds` and `a.mds` both
    // name theirs `a.md`), or one in an out-dir made since, is not
    // `src`'s. The removal, below the directory the write's check
    // found, triggers no rebuild: it is no `.mds` file. A rebuild's
    // failure never changes how the session exits, so one to remove
    // it stays a warning (#157).
    if let Some(previous) = &previous {
        state.retire(src, previous, out_dir, Retirement::KindChanged, quiet);
    }

    state.record_success(src, dep_paths, root, Some(&out), Some(compiled.content));
}

/// Compile-time context for directory-mode watch, parallel to `FileCompileCtx`.
///
/// Groups the parameters resolved once at startup and threaded into every
/// liveness-probe and event-handler call — removes `#[allow(clippy::too_many_arguments)]`
/// from the extracted helper functions (issue #6 / zero-warnings policy).
struct DirWatchCtx {
    /// The watched directory, as typed and canonical ([`Watched::Root`]).
    root: WatchedPath,
    /// The working directory at startup, restored first by every rebuild.
    working_dir: WorkingDir,
    /// Canonicalized `--vars` path — matches notify's canonicalized event paths;
    /// used for matching/watching (never for display, #326).
    vars_path: Option<PathBuf>,
    /// The `--vars` path exactly as the user typed it, uncanonicalized (#326, D4).
    /// Used for `RuntimeVarArgs.vars` so the vars-file duplicate-key warning displays
    /// (and reads) the as-typed path rather than its canonical form.
    vars_path_typed: Option<PathBuf>,
    static_set_vars: Vec<(String, String)>,
    static_set_string_vars: Vec<(String, String)>,
    output_base: OutputBase,
    exclude_prefix: Option<PathBuf>,
    vars_dir_extra: Option<PathBuf>,
    clear: bool,
    debounce_ms: u64,
    quiet: bool,
}

/// What [`arm_dir`] came to for one directory — a failure is reported once for as long as
/// it lasts, as [`StdoutOutcome`] reports stdout's (#257).
#[derive(Debug)]
enum DirArm {
    /// The watcher held it already: nothing was asked of it.
    Held,
    /// Its watch is in place now.
    Armed,
    /// Its watch failed, the first failure since a watch of it last succeeded, or since it
    /// was imported: the caller reports it.
    Failed(notify::Error),
    /// Its watch failed again, with no watch of it succeeding in between: it was reported,
    /// and is not reported a second time.
    FailedAgain,
}

/// Watch `dir` unless `armed` holds it, and hold it there once its watch is in place
/// (#257). A failure is noted in `failing`, and only the first of a run of them is
/// [`DirArm::Failed`], for the caller to report; a watch that succeeds ends the run. So a
/// directory that exists but cannot be watched — EACCES, inotify's `max_user_watches`
/// spent — is tried again by every rebuild and warned about once, not after each one.
fn arm_dir(
    dir: &Path,
    armed: &mut BTreeSet<PathBuf>,
    failing: &mut BTreeSet<PathBuf>,
    watch: impl FnOnce(&Path) -> notify::Result<()>,
) -> DirArm {
    if armed.contains(dir) {
        return DirArm::Held;
    }
    match watch(dir) {
        Ok(()) => {
            armed.insert(dir.to_path_buf());
            failing.remove(dir);
            DirArm::Armed
        }
        Err(e) if failing.insert(dir.to_path_buf()) => DirArm::Failed(e),
        Err(_) => DirArm::FailedAgain,
    }
}

/// Arm each of `dirs` — directories of dependencies outside the root — that `armed` does
/// not hold yet, with `watch`, and add it to `armed` once its watch is in place (#257).
/// One whose watch fails is left out of `armed`, so the next rebuild and the liveness tick
/// arm it again — `armed` holds only directories the watcher holds — and is reported,
/// named through [`shown_watched_dir`] with `root` and `vars`, once for as long as its
/// watch keeps failing ([`arm_dir`], `failing`).
fn arm_external_dep_dirs<'a>(
    dirs: impl IntoIterator<Item = &'a PathBuf>,
    armed: &mut BTreeSet<PathBuf>,
    failing: &mut BTreeSet<PathBuf>,
    mut watch: impl FnMut(&Path) -> notify::Result<()>,
    root: RootPaths<'_>,
    vars: Option<RootPaths<'_>>,
) {
    for dir in dirs {
        match arm_dir(dir, armed, failing, &mut watch) {
            DirArm::Failed(e) => eprint_warning(&format!(
                "warning: failed to watch external dep dir {}: {}",
                safe_path(&shown_watched_dir(dir, root, vars)),
                safe_inline(notify_cause(&e))
            )),
            DirArm::Held | DirArm::Armed | DirArm::FailedAgain => {}
        }
    }
}

/// Unwatch every directory outside the root that the watcher holds and that no source
/// imports from any more — not in `imported` — but the `--vars` file's, which it holds for
/// that file whatever the sources import. Each leaves `armed_dirs`; an `unwatch` that fails
/// is ignored, the directory perhaps gone and its watch with it. A directory no source
/// imports leaves `failing_dirs` too, so an import that brings it back reports its first
/// failed watch again ([`arm_dir`]).
fn unwatch_unimported_dirs(
    ctx: &DirWatchCtx,
    watcher: &mut dyn Watcher,
    liveness: &mut LivenessState,
    imported: &BTreeSet<PathBuf>,
) {
    let unimported: Vec<PathBuf> = liveness
        .armed_dirs
        .iter()
        .filter(|dir| !imported.contains(*dir) && ctx.vars_dir_extra.as_ref() != Some(*dir))
        .cloned()
        .collect();
    for dir in &unimported {
        let _ = watcher.unwatch(dir);
        liveness.armed_dirs.remove(dir);
    }
    liveness.failing_dirs.retain(|dir| imported.contains(dir));
}

/// Once a rebuild has run, unwatch the directories outside the root that no source imports
/// from any more ([`unwatch_unimported_dirs`]), and arm the directories of the dependencies
/// outside the root that are not armed — one its compile reported first, and one whose
/// earlier watch failed — so an edit in one rebuilds at once and the watches follow the
/// imports, not only at an idle tick, which `--poll-interval 0` never runs (#257). A
/// directory that does not exist is left to the liveness tick, which arms it when it
/// reappears.
fn arm_external_dirs_after_rebuild(
    ctx: &DirWatchCtx,
    watcher: &mut dyn Watcher,
    liveness: &mut LivenessState,
    state: &DirWatchState,
) {
    unwatch_unimported_dirs(ctx, watcher, liveness, &state.external_dep_dirs);
    // A directory the watcher holds is passed over before it is looked at: a rebuild costs
    // no `stat` per armed directory.
    let unarmed: Vec<&PathBuf> = state
        .external_dep_dirs
        .iter()
        .filter(|dir| !liveness.armed_dirs.contains(*dir) && dir.exists())
        .collect();
    arm_external_dep_dirs(
        unarmed,
        &mut liveness.armed_dirs,
        &mut liveness.failing_dirs,
        |dir| watcher.watch(dir, RecursiveMode::NonRecursive),
        ctx.root.root_paths(),
        extra_vars_dir(
            ctx.vars_dir_extra.as_deref(),
            ctx.vars_path_typed.as_deref(),
        ),
    );
}

/// Run the idle-tick liveness probe for directory mode (reconcile rule, DD1).
///
/// Re-arms the root, the external dirs and the vars dir that the watcher does not hold —
/// a tick that finds every watch in place asks nothing of the watcher (#257). Applies
/// edge-triggered recovery to decide whether a full reconcile (collect_mds_files diff) is
/// needed. Mutates `liveness` state for next tick.
fn liveness_probe_dir(
    ctx: &DirWatchCtx,
    watcher: &mut dyn Watcher,
    liveness: &mut LivenessState,
    state: &mut DirWatchState,
) {
    // 1. Re-arm root as Recursive (gated — reconcile rule / issue #1 idle O(1) fix).
    //
    // Skip the `watcher.watch()` syscall on healthy ticks when root is already armed:
    // on Linux `notify` re-WalkDirs the entire subtree + calls `inotify_add_watch` per
    // subdirectory on every `watch()` call regardless of mode; on macOS it tears down
    // and recreates the FSEvents stream, and on Windows it opens a second handle that
    // delivers every event again (#257).  Only re-arm when:
    //   (a) root was missing last tick but now exists (vanish→reappear edge)
    //   (b) root_armed is false — a previous arm attempt failed; retry
    // The first tick is no reason: the startup armed the root before anything was read,
    // and the first tick's reconcile walk (`recovery` below) does not need it armed again.
    let root_now_exists = ctx.root.canonical.exists();
    let need_root_rearm = (liveness.root_was_missing && root_now_exists) || !liveness.root_armed;
    let root_ok = if root_now_exists && need_root_rearm {
        let ok = watcher
            .watch(&ctx.root.canonical, RecursiveMode::Recursive)
            .is_ok();
        liveness.root_armed = ok;
        ok
    } else if root_now_exists {
        // Already armed and still healthy — treat as ok without a syscall.
        true
    } else {
        // Root does not exist — unarmed until it reappears.
        liveness.root_armed = false;
        false
    };

    // Unwatch dirs that were pruned from external_dep_dirs by a previous batch (issue #2
    // fix: release OS watches when cross-root @imports are edited away, to prevent
    // inotify/FSEvents watch leaks approaching fs.inotify.max_user_watches) — the step
    // every rebuild ends with too ([`arm_external_dirs_after_rebuild`]), so on a tick it
    // asks nothing of the watcher unless the two disagree.
    unwatch_unimported_dirs(ctx, watcher, liveness, &state.external_dep_dirs);

    // Also clean up any stale entries from missing_external_dirs.
    liveness
        .missing_external_dirs
        .retain(|d| state.external_dep_dirs.contains(d));

    // Re-arm external dirs — gated like root re-arm: skip the syscall for dirs
    // that are already armed and still healthy (O(1) per healthy dir per tick).
    let ext_statuses: Vec<(PathBuf, bool, bool)> = state
        .external_dep_dirs
        .iter()
        .map(|ext_dir| {
            let exists = ext_dir.exists();
            let already_armed = liveness.armed_dirs.contains(ext_dir);
            let rearm_ok = if exists {
                if already_armed {
                    // Already armed and healthy — skip the syscall.
                    true
                } else {
                    let ok = watcher.watch(ext_dir, RecursiveMode::NonRecursive).is_ok();
                    if ok {
                        // A watch that succeeds ends a run of failed ones (`arm_dir`).
                        liveness.armed_dirs.insert(ext_dir.clone());
                        liveness.failing_dirs.remove(ext_dir);
                    }
                    ok
                }
            } else {
                // Dir does not exist — ensure it is not marked as armed.
                liveness.armed_dirs.remove(ext_dir);
                false
            };
            (ext_dir.clone(), exists, rearm_ok)
        })
        .collect();
    let (external_recovery, now_missing_external) =
        external_recovery_decision(&liveness.missing_external_dirs, &ext_statuses);
    // The `--vars` file's directory outside the root, gated like the external dirs (#257):
    // watched only while the watcher does not hold it — its startup watch failed, or it
    // vanished and came back — never again on every tick.
    if let Some(vd) = ctx.vars_dir_extra.as_deref() {
        if !vd.exists() {
            liveness.armed_dirs.remove(vd);
        } else if !liveness.armed_dirs.contains(vd)
            && watcher.watch(vd, RecursiveMode::NonRecursive).is_ok()
        {
            liveness.armed_dirs.insert(vd.to_path_buf());
        }
    }

    // 2. Recovery trigger (reconcile rule):
    //    `root_now_exists && !root_ok` = existing root whose re-arm failed (genuine watch loss).
    //    A *missing* root is handled by the `root_was_missing && root_now_exists` vanish→reappear
    //    edge and must NOT trigger recovery on every tick while absent (per-tick error spam).
    //    Note: `root_now_exists` and `root_ok` are already computed above in section 1.
    let recovery = liveness.first_tick
        || (root_now_exists && !root_ok)
        || external_recovery
        || (liveness.root_was_missing && root_now_exists);
    liveness.first_tick = false;
    liveness.root_was_missing = !root_now_exists;
    liveness.missing_external_dirs = now_missing_external;

    // 3. Content backstop (#321), and the full reconcile (appeared/removed) on a recovery
    //    edge ([`scan_directory`]).
    let found = scan_directory(ctx, state, recovery);

    if !found.paths.is_empty() || found.vars_changed {
        // The event handler's rebuild path, so a recompile driven purely by this
        // content-backstop/full-reconcile tick (no FS event ever delivered, e.g. after a
        // root delete+recreate) re-reports the vars-file duplicate keys under the same
        // content-changed gate, and one logical edit observed by both paths still warns
        // once — tests I17 and I19.
        rebuild_dir_batch(ctx, &found.paths, found.vars_changed, state, None);
        arm_external_dirs_after_rebuild(ctx, watcher, liveness, state);
    }
    // No baseline refresh here: `process_dir_batch` re-baselines `last_mtimes` over the
    // post-batch watched set, and an empty batch means nothing appeared, was removed, or
    // changed — so the existing baseline is by definition still accurate.
}

/// What a directory watch finds by looking for changes it was not told of (#321, #257): the
/// watched files whose `(mtime, size)` differ from the baseline — the `--vars` file among them,
/// as a change to it — and, with `walk`, the `.mds` files that appeared under the root since
/// the last walk or were removed from it. The idle tick looks for the first alone, and for
/// both on a recovery edge; an event that says events were lost looks for both at once
/// ([`handle_fs_event_dir`]).
///
/// Content backstop (#321). A reconcile diffs `collect_mds_files(root)` against
/// `known_files`, which reports only files that *appeared* or were *removed* under the root.
/// A change to a file's contents is invisible to it, and a cross-root dependency is not even
/// in that walk — so until this check existed, `last_mtimes` was written on every batch in
/// dir mode and never once read, and an edit whose event went undelivered was lost for good.
/// The events that go undelivered are not hypothetical: a cross-root dependency is discovered
/// by the compile that reads it, so its directory cannot be armed until after that first
/// read.
///
/// Cost is one `stat` per watched path, short-circuited by nothing — the full set is walked
/// so every changed path joins the same batch. That is the same price single-file mode has
/// always paid via `state_differs` on its files-of-interest, and it is O(sources + deps), not
/// O(tree).
///
/// The watched set holds the `--vars` file too, as single-file mode's files of interest do
/// (#380): its event can be lost like any other — to an inotify queue overflow, to an
/// FSEvents stream restart — and nothing else would ever rebuild the outputs with the file as
/// it now reads. A change found there is a vars change, which recompiles every source, as the
/// batch of its event does.
///
/// Full reconcile (appeared/removed). `known_files` is replaced with the fresh walk *before*
/// the batch runs, so the re-baseline at the end of `process_dir_batch` already covers every
/// file the walk found — including one that appeared and then failed to compile, which
/// `record_error` deliberately does not add to `known_files`. Replacing afterwards would
/// leave such a file outside the baseline and cost one redundant compile on the following
/// tick.
fn scan_directory(ctx: &DirWatchCtx, state: &mut DirWatchState, walk: bool) -> Batch {
    let watched = state.watched_set();
    let mut paths: BTreeSet<PathBuf> = watched
        .iter()
        .filter(|p| path_state_differs(p, &state.last_mtimes))
        .cloned()
        .collect();
    let vars_changed = state
        .vars_file
        .as_ref()
        .is_some_and(|vars| paths.remove(vars));

    if walk {
        let current: BTreeSet<PathBuf> = collect_mds_files(
            &ctx.root.canonical,
            MAX_COLLECT_DEPTH,
            ctx.exclude_prefix.as_deref(),
        )
        .into_iter()
        .map(|p| graph_key(&p))
        .collect();
        paths.extend(current.difference(&state.known_files).cloned());
        paths.extend(state.known_files.difference(&current).cloned());
        state.known_files = current;
    }
    Batch {
        paths,
        vars_changed,
    }
}

/// Rebuild `batch` in directory mode — the one rebuild path of the event handler, of the
/// idle tick's content backstop and of a held rebuild's deadline alike.
///
/// A recreated working directory is restored first ([`WorkingDir::restore_if_recreated`]),
/// before anything is read. A watched file — a source, a dependency or the `--vars` file
/// ([`DirWatchState::watched_set`]) — found empty where the baseline saw bytes then holds
/// the whole batch back (#380): nothing is compiled, written or printed, the baseline is
/// left as it was ([`Settle::Defer`]), and the batch is kept ([`HeldBatch`]) to be rebuilt
/// with the one that ends the hold — the first to find no watched file emptied, or the
/// first at or past its deadline ([`EmptyHold`]), which compiles the files as they are.
/// Every file the look finds emptied joins the batch, its own event lost or not
/// ([`join_emptied`]), so that batch rebuilds it. A source whose compile read a file
/// emptied after the look is held the same way, alone, whether the compile then failed or
/// not ([`compile_one_source`]), and a `--vars` load that failed on the file emptied after
/// the look holds the whole batch. The look stamps the watched files, every path the batch
/// names, and the sources ([`names_a_source`]) of the batches held back and those whose last
/// compile failed, which a batch with a change compiles again without naming them. So a
/// source no compile has read yet, or none has succeeded on, and a dependency outside the
/// root that a source of the batch imports for the first time, is stamped before its compile
/// reads it, and a source its compile holds keeps that stamp
/// ([`DirWatchState::baselined_paths`]); a path nothing reads — a `.mds` file beside a
/// dependency outside the root that no source imports — is stamped at the look and dropped
/// from the baseline when the batch ends, so its emptying holds nothing. The batch takes
/// the look's stamps as its baseline before it reads anything, and keeps the ones in the
/// baseline's domain however it ends ([`baseline_over`]) — at its
/// end, or when its `--vars` load fails ([`Settle::Rebaseline`]): a file emptied while
/// the batch runs, after its look, that no compile read empty — read whole before, or not
/// read — stays emptied in the baseline the batch leaves, so the rebuild its own events
/// start is held; only a file the deadline compiles as it is is taken in empty. `due` is
/// the hold's deadline when that deadline runs this rebuild, which then ends the hold
/// ([`not_before`]); `None` for an event or a tick. A held batch prints nothing, the
/// `--clear` its event asked for included: that clear stays asked for, and the first thing
/// printed after it makes it — the batch that ends the hold, as a rule. Every other batch
/// drops the clear when it ends ([`end_rebuild_clear`]): the clear is made before the first
/// byte the batch prints, a compile warning among them, or not at all.
/// The vars file is then reloaded (freshness rule), and a
/// failure to read it is reported and settled: it may be temporarily absent (AC-W7 /
/// AC-C5). `--set`/`--set-string` are fixed for the session and warned once at startup —
/// discarded here (via `resolved.vars`). The vars file's duplicate keys are re-reported
/// once for each batch that shows something, by the first of its sources that does — a
/// `Recompiled` line, a `Kept` notice, a failed write's report ([`BatchVars`]) — never by
/// a batch that shows nothing (#326, test I17): at `--debounce 0` a single edit can
/// generate more than one raw FS event, each reaching the event handler separately, and
/// the idle tick can observe the same edit again, but only the first batch finds the
/// output changed — one logical edit warns once. A batch the vars file cannot be
/// read for is kept ([`HeldBatch`]) and rebuilt with the next one, so a source created
/// while the file cannot be read is compiled by the batch that reads it again (#380).
fn rebuild_dir_batch(
    ctx: &DirWatchCtx,
    batch: &BTreeSet<PathBuf>,
    vars_changed: bool,
    state: &mut DirWatchState,
    due: Option<Instant>,
) {
    let batch = Batch {
        paths: batch.clone(),
        vars_changed,
    };
    run_dir_batch(ctx, batch, state, due);
    end_rebuild_clear(&state.hold);
}

/// The batch [`rebuild_dir_batch`] runs and ends: every return of it is one the clear is
/// dropped after (unless held).
fn run_dir_batch(ctx: &DirWatchCtx, batch: Batch, state: &mut DirWatchState, due: Option<Instant>) {
    ctx.working_dir.restore_if_recreated();

    // #380: a watched file emptied holds the whole batch back, and joins it. The look stamps
    // each file the run may read once — the watched files, the sources held back, every path
    // the batch names (a dependency outside the root that a source of the batch imports for
    // the first time among them, which no record of the session names yet) and the sources
    // a failed compile left errored, which the batch compiles again without naming them —
    // and its stamps are the batch's baseline if it runs, so no file a compile of the batch
    // reads is stamped after the read. A path nothing reads is stamped too, and the batch's
    // end drops it from the baseline ([`DirWatchState::baselined_paths`]), so it holds nothing.
    let root = ctx.root.canonical.as_path();
    let errored_sources = state
        .errored
        .iter()
        .filter(|path| names_a_source(root, path));
    let look = look_at(
        state
            .baselined_paths()
            .chain(&batch.paths)
            .chain(errored_sources),
    );
    let emptied: BTreeSet<PathBuf> = emptied_in(&look, &state.last_mtimes).cloned().collect();
    let verdict = state
        .hold
        .on_rebuild(!emptied.is_empty(), not_before(Instant::now(), due));
    debug_assert!(
        due.is_none() || verdict == HoldVerdict::Compile,
        "a held rebuild's deadline ends its hold"
    );
    let batch = join_emptied(batch, &emptied, state.vars_file.as_deref());
    if verdict == HoldVerdict::Hold {
        state.held.hold(&batch, root);
        settle(SettleInto::Dir(state), None, Settle::Defer);
        return;
    }
    // The look's stamps are the batch's baseline from here, taken before anything is read:
    // every later look compares with them, and a `--vars` load that fails and the batch's
    // end both keep them (#380). A file the look found emptied — the hold's deadline runs
    // this batch — is in it empty: the batch compiles it as it is, and it is not held again.
    state.last_mtimes.extend(look);
    let batch = state.held.release(batch);
    // A debug build's test pause (#380): the batch found no file emptied, and has read none.
    pause_after_look();

    let reads = mds::ReadLog::new();
    let resolved = match build_runtime_vars_logged(
        RuntimeVarArgs {
            vars: ctx.vars_path_typed.clone(),
            set_vars: ctx.static_set_vars.clone(),
            set_string_vars: ctx.static_set_string_vars.clone(),
        },
        &reads,
    ) {
        Ok(v) => v,
        Err(e) => {
            // #380: a watched file emptied since the look above — the vars file the load read
            // empty, a truncation that began between the two — holds the whole batch back,
            // with nothing reported or recorded, unless the deadline ended the hold in this
            // rebuild.
            if state.hold_after_vars_load_failed(&batch, root, &reads) {
                settle(SettleInto::Dir(state), None, Settle::Defer);
                return;
            }
            // Keep the batch, as a held one is kept, for the next batch to rebuild (#380):
            // a source created while the vars file cannot be read is in no other record,
            // so the batch that reads the file again would leave it unbuilt. The look's
            // stamps of its sources are kept with it; a path it named that nothing reads is
            // rebuilt but not stamped, so its emptying holds nothing.
            state.held.carry(&batch, root);
            // Re-baseline so the idle-tick content backstop does not report the same
            // change again and turn one unreadable vars file into per-tick error spam.
            settle(SettleInto::Dir(state), Some(e), Settle::Rebaseline);
            return;
        }
    };
    // A source its compile finds a file emptied for is held alone, the others printing. The
    // batch borrows the variables rather than cloning them, and its first source that
    // shows something reports the vars file's duplicate keys (#326).
    process_dir_batch(
        &batch.paths,
        batch.vars_changed,
        &mut BatchCtx {
            watch_root: &ctx.root,
            output_base: &ctx.output_base,
            vars: BatchVars::of(&resolved),
            quiet: ctx.quiet,
        },
        state,
    );
}

/// Outcome returned by `handle_fs_event_dir` to tell the loop what to do next.
enum DirEventOutcome {
    /// Skip — nothing relevant (Access event, no .mds path or imported file, no vars change).
    Skip,
    /// Ctrl+C received — stop watching.
    Stop,
    /// Batch computed and process_dir_batch already called by the handler.
    Done,
}

/// Process a single incoming `Msg` for directory mode.
///
/// Collects changed paths, drains the debounce window, filters irrelevant paths, and
/// rebuilds what is left through [`rebuild_dir_batch`]. Returns `DirEventOutcome` so the
/// caller knows whether to `continue`, `return`, or proceed.
fn handle_fs_event_dir(
    msg: Msg,
    ctx: &DirWatchCtx,
    rx: &mpsc::Receiver<Msg>,
    state: &mut DirWatchState,
) -> DirEventOutcome {
    let mut changed: BTreeSet<PathBuf> = BTreeSet::new();
    // Whether an event said events were lost ([`notify::Event::need_rescan`]).
    let mut rescan = false;

    let interrupted = match msg {
        Msg::Interrupt => true,
        Msg::Fs(Err(e)) => {
            eprint_warning(&format!(
                "warning: watch error: {}",
                safe_inline(notify_cause(&e))
            ));
            return DirEventOutcome::Skip;
        }
        Msg::Fs(Ok(event)) => {
            // Drop Access events (inotify IN_ACCESS/IN_OPEN/IN_CLOSE_NOWRITE).
            // On Linux reading a .mds source file during compile emits Access
            // events that would re-seed the watcher in a busy-loop (~3000/s).
            if is_content_event(&event.kind) {
                rescan = event.need_rescan();
                for p in event.paths {
                    changed.insert(p);
                }
            }
            false
        }
    };

    if interrupted {
        return DirEventOutcome::Stop;
    }

    // Drain debounce window.
    let drained = drain_debounce(rx, ctx.debounce_ms);
    if drained.interrupted() {
        return DirEventOutcome::Stop;
    }
    changed.extend(drained.paths);
    rescan |= drained.rescan;

    // Check if the vars file changed — before the filters below drop the paths in the
    // out-dir and in the hidden directories and `node_modules/` below the root: a `--vars`
    // file there is read by every compile all the same (#380).
    let mut vars_changed = ctx
        .vars_path
        .as_deref()
        .map(|vf| changed.contains(vf))
        .unwrap_or(false);

    // Defense-in-depth: ignore events from inside the out-dir subtree.
    if let OutputBase::Dir {
        canonical: ref od, ..
    } = ctx.output_base
    {
        changed.retain(|p| !p.starts_with(od));
    }

    // PF-004: drop events from default-excluded subdirectories (hidden dirs and
    // node_modules/) inside the watch root.  The initial walker never seeds files
    // from those dirs, so they are not in the dep graph and processing their
    // events would cause spurious rebuilds (e.g. npm install writing to
    // node_modules/ triggers a full re-scan on every package update).
    changed.retain(|p| !is_within_default_excluded_dir(&ctx.root.canonical, p));

    // Collect the paths a rebuild may name: .mds paths either under root OR in known
    // external dep dirs, and any other file some source imports — a `type: mds` `.md`
    // module, below the root or outside it — whose edit rebuilds its importers.
    let dependencies: OnceCell<HashSet<&PathBuf>> = OnceCell::new();
    let mut mds_changed: BTreeSet<PathBuf> = changed
        .iter()
        .filter_map(|p| {
            let key = graph_key(p);
            let admitted = (has_mds_extension(p)
                && classify(&ctx.root.canonical, p, &state.external_dep_dirs) != Node::Unrelated)
                || dependencies
                    .get_or_init(|| state.forward_deps.values().flatten().collect())
                    .contains(&key);
            admitted.then_some(key)
        })
        .collect();

    // An event that says events were lost (an overflowed inotify queue, FSEvents'
    // `MustScanSubDirs`) names no path: what the lost events would have said is looked for
    // at once, as a recovery edge of the idle tick would — a source created, one removed, a
    // watched file or the `--vars` file changed — and joins the batch, whether or not a tick
    // runs (#257).
    if rescan {
        let found = scan_directory(ctx, state, true);
        mds_changed.extend(found.paths);
        vars_changed |= found.vars_changed;
    }

    if mds_changed.is_empty() && !vars_changed {
        return DirEventOutcome::Skip; // Nothing relevant changed.
    }

    // The terminal is cleared, if requested (only when stderr is a TTY), before the first
    // thing the batch prints (#380).
    if ctx.clear {
        crate::output::ask_clear();
    }

    rebuild_dir_batch(ctx, &mds_changed, vars_changed, state, None);
    DirEventOutcome::Done
}

/// Directory watch: `root.typed` is the directory as typed — `mds.json` is looked up from it
/// (#413) and every status line names it, and the directories below it, by it (#390);
/// `root.canonical` is its canonical form, which notify reports event paths under.
///
/// Startup runs in phases whose order the types enforce (#429, [`dir_startup`]):
/// [`dir_startup::arm_pre_read`] arms the root, and the `--vars` file's directory outside
/// it, before any source is read, [`dir_startup::startup_compile`] compiles each source once
/// and writes its output, [`dir_startup::arm_deps_and_seed`] arms the directories of the
/// dependencies outside the root and seeds what every rebuild reads, and
/// [`dir_startup::Seeded::go_live`] goes live and watches until the session stops.
fn run_watch_dir(root: WatchedPath, args: SessionArgs) -> Result<()> {
    let armed = dir_startup::arm_pre_read(root, args)?;
    let compiled = dir_startup::startup_compile(armed)?;
    dir_startup::arm_deps_and_seed(compiled).go_live();
    Ok(())
}

/// Directory mode's startup, in phases whose order the types enforce (#429).
///
/// Each phase takes the token only the phase before it makes, and every token's fields are
/// private to this module, so nothing outside it can make one: an
/// [`Armed`](dir_startup::Armed) comes only from [`dir_startup::arm_pre_read`], a
/// [`Compiled`](dir_startup::Compiled) only from [`dir_startup::startup_compile`] given an
/// `Armed`, a [`Seeded`](dir_startup::Seeded) only from [`dir_startup::arm_deps_and_seed`]
/// given a `Compiled`, and the session goes live only from a `Seeded`
/// ([`dir_startup::Seeded::go_live`]). That is the order the session's change detection
/// rests on: the root armed recursively, and the `--vars` file's directory outside it,
/// before the tree is walked or any source read; every source's `(mtime, size)` baseline
/// taken before the first of them is read, and a dependency's as soon as the compile that
/// reports it returns; the directories of the dependencies outside the root armed once
/// every startup output is published; Ctrl+C wired last, with nothing but the loop after
/// it. The compile takes the `Armed` and carries it on inside the `Compiled`, so one
/// `Armed` is compiled once, and a `Compiled` is seeded with the very watches it was
/// compiled under.
mod dir_startup {
    use std::collections::{BTreeSet, HashMap, HashSet};
    use std::ops::ControlFlow;
    use std::path::PathBuf;
    use std::sync::{mpsc, Arc};
    use std::time::{Duration, Instant};

    use miette::Result;
    use notify::{RecommendedWatcher, RecursiveMode, Watcher};

    use crate::build::{
        build_runtime_vars, emit_duplicate_var_warnings, load_config, run_reads, source_inputs,
        write_output, ProjectConfig, RuntimeVarArgs,
    };
    use crate::output::{
        collect_mds_files, eprint_warning, is_partial, notify_cause, output_path_for, safe_inline,
        safe_path, OutputBase,
    };

    use super::{
        arm_external_dep_dirs, arm_external_dirs_after_rebuild, baseline_path,
        canonicalize_vars_path, extra_vars_dir, graph_key, graph_keys, handle_fs_event_dir, live,
        liveness_probe_dir, rebuild_dir_batch, resolve_output_base, settle_startup_error,
        shown_watched_dir, snapshot_state, startup_race_probe, DirEventOutcome, DirWatchCtx,
        DirWatchState, EmptyHold, FileStamp, HeldBatch, LivenessState, Msg, OutDirAnchor,
        SessionArgs, StampMap, StartupInto, StopReason, WatchedPath, WorkingDir, MAX_COLLECT_DEPTH,
    };

    /// The root armed recursively, and the `--vars` file's directory outside it, before the
    /// tree is walked or any source read: made only by [`arm_pre_read`].
    pub(super) struct Armed {
        /// The watched directory, as typed and canonical ([`super::Watched::Root`]).
        root: WatchedPath,
        /// `--out-dir`.
        out_dir: Option<PathBuf>,
        /// The working directory at startup, which every rebuild restores first.
        working_dir: WorkingDir,
        /// The `mds.json` in force, looked up from the root as typed.
        config: Option<ProjectConfig>,
        /// The `--vars` file, canonical: what notify names its events by (#326).
        vars_path: Option<PathBuf>,
        /// The `--vars` file as typed, which it is read and named by (#326).
        vars_path_typed: Option<PathBuf>,
        static_set_vars: Vec<(String, String)>,
        static_set_string_vars: Vec<(String, String)>,
        /// Where every output is written ([`OutputBase`]).
        output_base: OutputBase,
        /// The out-dir when it is inside the root, which the walk leaves out.
        exclude_prefix: Option<PathBuf>,
        /// The `--vars` file's directory when it is outside the root, armed on its own.
        vars_dir_extra: Option<PathBuf>,
        /// The directories outside the root whose watch is in place: the `--vars` file's,
        /// when its watch succeeded. The dependencies' join them once the compile reports
        /// them, and a directory held here is never watched a second time (#257).
        armed_dirs: BTreeSet<PathBuf>,
        quiet: bool,
        clear: bool,
        debounce_ms: u64,
        tick: Option<Duration>,
        /// The channel the watcher sends on — and Ctrl+C, once the session is live.
        tx: mpsc::Sender<Msg>,
        rx: mpsc::Receiver<Msg>,
        watcher: RecommendedWatcher,
    }

    /// Every source compiled once, and its output written when it could be: made only by
    /// [`startup_compile`].
    pub(super) struct Compiled {
        /// The watches the compile ran under, handed on to [`arm_deps_and_seed`] with what
        /// it produced.
        armed: Armed,
        /// The dependency graph, what was written and where, and the sources errored.
        state: DirWatchState,
        /// Every source's `(mtime, size)` and the `--vars` file's, taken before the first of
        /// them was read, and each dependency's, taken as the compile that reported it
        /// returned.
        pre_mtimes: StampMap,
    }

    /// Every directory armed and every baseline taken, with what every rebuild reads: made
    /// only by [`arm_deps_and_seed`].
    pub(super) struct Seeded {
        /// The sender the watcher was armed with, which Ctrl+C is wired to.
        tx: mpsc::Sender<Msg>,
        rx: mpsc::Receiver<Msg>,
        tick: Option<Duration>,
        session: DirSession,
    }

    /// A directory-mode session once live ([`live::Session`]): what every rebuild reads, the
    /// watcher, the loop state and the liveness probe's.
    struct DirSession {
        ctx: DirWatchCtx,
        watcher: RecommendedWatcher,
        state: DirWatchState,
        liveness: LivenessState,
    }

    /// Record the working directory, load `mds.json`, check the `--vars` file and the
    /// out-dir, and say what is watched; then arm the root, and the `--vars` file's
    /// directory outside it, before the tree is walked or any source read.
    pub(super) fn arm_pre_read(watch_root: WatchedPath, args: SessionArgs) -> Result<Armed> {
        let SessionArgs {
            out_dir,
            vars,
            set_vars,
            set_string_vars,
            clear,
            debounce_ms,
            quiet,
            tick,
        } = args;
        let working_dir = WorkingDir::record();
        let root = watch_root.canonical.as_path();
        // Load config once from the root directory, as typed, so a config error names
        // `mds.json` as the input reaches it (`./mds.json`, `src/../mds.json`), never by its
        // canonical absolute path (#413); the config directory it returns is canonical.
        let config = load_config(&watch_root.typed)?;
        // #326: keep the --vars argument as the user typed it (see FileCompileCtx's
        // vars_path_typed doc for why) — `vars_path` below stays canonical for matching.
        let vars_path_typed = vars.clone();
        // Canonicalize so path matches notify event paths (resolves /tmp → /private/tmp on macOS).
        // Also rejects a symlinked vars file at startup (build parity).
        let vars_path = canonicalize_vars_path(vars).map_err(miette::Error::from)?;
        let static_set_vars = set_vars;
        let static_set_string_vars = set_string_vars;

        // Compute the OutputBase (Fix 2 — subtree mirroring). Reject `..` at startup. The
        // out-dir's canonical form keeps the starts_with(&root) in-root exclusion check
        // reliable even when cwd contains symlinks (root is already canonical — security #8).
        let output_base = resolve_output_base(out_dir.as_ref(), &config)?;

        // When the out-dir is inside root, exclude it from collection so the watcher
        // doesn't self-pollute: its own outputs would trigger rebuilds.
        let exclude_prefix: Option<PathBuf> = match &output_base {
            OutputBase::Dir { canonical: d, .. } if d.starts_with(root) => Some(d.clone()),
            _ => None,
        };

        if !quiet {
            crate::output::ewriteln!("Watching directory {}", safe_path(&watch_root.typed));
        }

        // Additionally watch the vars file's parent if it is outside root.
        let vars_dir_extra: Option<PathBuf> = vars_path.as_deref().and_then(|vf| {
            let parent = vf.parent()?;
            // Only watch if outside root to avoid redundancy.
            if !parent.starts_with(root) {
                Some(parent.to_path_buf())
            } else {
                None
            }
        });
        // That directory in the two forms a message names it by ([`shown_watched_dir`]).
        let vars_dir = extra_vars_dir(vars_dir_extra.as_deref(), vars_path_typed.as_deref());

        // ── Arm before publish (startup race) ─────────────────────────────────
        //
        // The recursive root watch is armed BEFORE the tree is walked, before any
        // source is read, and before any output is written, so that every in-root edit
        // from this point on generates an event that is queued on `rx` and drained once
        // the event loop starts. That is the primary detector and the cheapest one.
        //
        // The idle tick's content backstop (#321) is the second detector and covers what
        // arming order cannot: a dependency whose directory is unknowable until the
        // compile that reads it returns. Ordering is still what keeps that backstop cheap
        // — arming first means the backstop almost never has to fire.
        //
        // Arming first also means the watcher observes the startup compile's own
        // reads and writes. Three pre-existing guards absorb that, and all three are
        // still in force:
        //   1. `is_content_event` drops `Access(_)` — every read the compile performs.
        //   2. `handle_fs_event_dir` keeps only paths with a `.mds` extension, so the
        //      `.md`/`.json` outputs this startup writes can never seed a rebuild.
        //      This is the guard that covers in-place output (`OutputBase::NextToSource`),
        //      where outputs land beside their sources inside the watched root.
        //   3. `last_written` content-dedup in `compile_one_source`.
        //
        // When `--out-dir` sits inside the root, arming early widens the window in
        // which the watcher sees its own outputs, so that case is covered twice:
        // `exclude_prefix` keeps the out-dir out of `collect_mds_files`, and
        // `handle_fs_event_dir` drops every event whose path is under an
        // `OutputBase::Dir` before the extension filter even runs. The out-dir is
        // created by the first write *after* the recursive watch is armed, so notify
        // adds it to the watch set — the exclusion is what keeps that harmless.
        let (tx, rx) = mpsc::channel::<Msg>();
        let tx_fs = tx.clone();
        let mut watcher = RecommendedWatcher::new(
            move |res| {
                crate::output::panic_in_handler("notify");
                let _ = tx_fs.send(Msg::Fs(res));
            },
            notify::Config::default(),
        )
        .map_err(|e| {
            miette::miette!(
                "failed to initialize file watcher: {}",
                safe_inline(notify_cause(&e))
            )
        })?;

        // Watch the root recursively.
        watcher.watch(root, RecursiveMode::Recursive).map_err(|e| {
            miette::miette!(
                "failed to watch directory {}: {}\n\
                     hint: on Linux you may need to increase fs.inotify.max_user_watches",
                safe_path(&shown_watched_dir(root, watch_root.root_paths(), vars_dir)),
                safe_inline(notify_cause(&e))
            )
        })?;

        // Watch the vars dir if it is outside root — soft warning on failure (mirrors the
        // external-dep-dir convention and the liveness probe's best-effort re-arm
        // semantics; a transient failure must not abort the session, applies the reconcile
        // rule / consistency fix). Held as armed only once its watch is in place, so the
        // liveness tick tries a failed one again and leaves a held one alone (#257).
        let mut armed_dirs = BTreeSet::new();
        if let Some(ref vd) = vars_dir_extra {
            match watcher.watch(vd, RecursiveMode::NonRecursive) {
                Ok(()) => {
                    armed_dirs.insert(vd.clone());
                }
                Err(e) => eprint_warning(&format!(
                    "warning: failed to watch vars directory {}: {}",
                    safe_path(&shown_watched_dir(vd, watch_root.root_paths(), vars_dir)),
                    safe_inline(notify_cause(&e))
                )),
            }
        }

        Ok(Armed {
            root: watch_root,
            out_dir,
            working_dir,
            config,
            vars_path,
            vars_path_typed,
            static_set_vars,
            static_set_string_vars,
            output_base,
            exclude_prefix,
            vars_dir_extra,
            armed_dirs,
            quiet,
            clear,
            debounce_ms,
            tick,
            tx,
            rx,
            watcher,
        })
    }

    /// Once [`arm_pre_read`] has armed what the walk and the compiles read: walk the root,
    /// take every source's baseline before the first is read, then compile each source once
    /// and write its output. A source whose compile or write fails is reported and marked
    /// errored, and watching continues.
    pub(super) fn startup_compile(armed: Armed) -> Result<Compiled> {
        let Armed {
            root: watch_root,
            out_dir,
            config,
            vars_path,
            vars_path_typed,
            static_set_vars,
            static_set_string_vars,
            output_base,
            exclude_prefix,
            ..
        } = &armed;
        let root = watch_root.canonical.as_path();
        let quiet = armed.quiet;

        // Startup compile: compile all .mds files found under root.
        let all_files = collect_mds_files(root, MAX_COLLECT_DEPTH, exclude_prefix.as_deref());

        // Capture the content baseline BEFORE the first read of any watched file — the
        // `--vars` file, which is loaded first, and every source — mirroring single-file
        // mode (#321). What makes the backstop sound is that this snapshot is strictly
        // older than the reads whose results were published: an edit that lands anywhere
        // after this point therefore registers as a difference on the first idle tick,
        // even when no filesystem event announced it, and a truncation of a file the
        // startup read whole is found emptied by the first rebuild (#380).
        //
        // Taking it afterwards instead would be worse than useless — it would record the
        // *post*-edit state as the baseline, so the watcher would believe an output
        // compiled from the pre-edit content was up to date, and hold that belief forever.
        //
        // Keys go through `graph_key`, exactly as `known_files` below does. `watched_set`
        // is built from those canonical keys, so a raw key here would never match one of
        // them — every source would read as "not in the baseline", i.e. changed, and the
        // first idle tick would recompile the whole tree. `collect_mds_files` walks a root
        // that is already canonical, but a symlinked subdirectory inside it still resolves
        // to something else, and the rest of this function does not assume otherwise. The
        // `--vars` file's key is its canonical path, as `watched_set` holds it.
        let mut pre_mtimes = snapshot_state(
            &all_files
                .iter()
                .map(|p| graph_key(p))
                .chain(vars_path.iter().cloned())
                .collect::<HashSet<_>>(),
        );

        let resolved = build_runtime_vars(RuntimeVarArgs {
            vars: vars_path_typed.clone(),
            set_vars: static_set_vars.clone(),
            set_string_vars: static_set_string_vars.clone(),
        })?;
        emit_duplicate_var_warnings(&resolved, quiet);
        let runtime_vars = resolved.vars;

        // Build the dependency graph and compile all files at startup.
        let mut state = DirWatchState {
            forward_deps: HashMap::new(),
            errored: HashSet::new(),
            known_files: BTreeSet::new(),
            last_written: HashMap::new(),
            outputs: HashMap::new(),
            kept: HashMap::new(),
            // Recorded below, once the startup writes have made the out-dir.
            out_dir: None,
            reads: run_reads(vars_path.as_deref(), config.as_ref()),
            external_dep_dirs: BTreeSet::new(),
            vars_file: vars_path.clone(),
            last_mtimes: HashMap::new(),
            hold: EmptyHold::Off,
            held: HeldBatch::default(),
        };

        for source in &all_files {
            let key = graph_key(source);
            match watch_root.compile_source(
                source,
                runtime_vars.clone(),
                quiet,
                &Arc::new(mds::ReadLog::new()),
            ) {
                Ok(compiled) => {
                    let dep_paths = graph_keys(&compiled.dependencies);

                    // Track external dep dirs (DD3 — cross-root).
                    for dep in &dep_paths {
                        if let Some(parent) = dep.parent() {
                            if !parent.starts_with(root) {
                                state.external_dep_dirs.insert(parent.to_path_buf());
                            }
                        }
                    }

                    // Baseline each dependency the instant the compile that discovered it
                    // returns, not in one pass after the whole tree is done. A dependency's
                    // existence is unknown until it is read, so its baseline can never
                    // precede its own read — but it can precede everything else, which
                    // shrinks its blind window from "the rest of startup" to the gap
                    // between one read and the next statement. `baseline_path` keeps the
                    // pre-compile value for any dependency that is also an in-root source:
                    // the older of the two is always the safe one.
                    for dep in &dep_paths {
                        baseline_path(dep, &mut pre_mtimes);
                    }

                    state.forward_deps.insert(key.clone(), dep_paths);
                    state.known_files.insert(key.clone());

                    // Partials (DD2): track in graph but don't emit their own output.
                    if !is_partial(source) {
                        // Derive the output path from the compiled kind (intrinsic extension).
                        //
                        // Invariant: `key` is `graph_key(source)` for a source the walker
                        // collected under the already-canonical `root`, and the walker skips
                        // symlinked files and directories — so the canonical key is still
                        // prefixed by `root` and the out-of-root flatten arm cannot fire
                        // here (#217).
                        let ext = compiled.kind.extension();
                        let out = output_path_for(&key, watch_root.root_paths(), output_base, ext);
                        // The content dedup holds only what was written: a source whose
                        // write failed is errored instead, so the next rebuild with a real
                        // change writes it even when its content has not changed (#257) —
                        // and nothing it did not write is ever its to remove (#160).
                        let inputs = source_inputs(&key, &compiled.dependencies, &state.reads);
                        if let Err(e) =
                            write_output(Some(&out), &compiled.content, &inputs, quiet, true)
                        {
                            settle_startup_error(StartupInto::Dir(&mut state), Some(e), &key);
                        } else {
                            state.wrote(&key, &out, compiled.content);
                        }
                    }
                }
                Err(failure) => {
                    // `key` is new to the graph — each source is compiled once here — so the
                    // errored source's dependency set is the empty one.
                    settle_startup_error(StartupInto::Dir(&mut state), failure.into_report(), &key);
                    state.known_files.insert(key);
                }
            }
        }
        // The directory the startup writes made, or found, is the one the first rebuild's
        // write compares (#160).
        state.out_dir = OutDirAnchor::record(out_dir.as_deref(), config.as_ref());

        Ok(Compiled {
            armed,
            state,
            pre_mtimes,
        })
    }

    /// Arm the directories of the dependencies outside the root that the startup compile
    /// reported — one that cannot be armed is a warning — then seed what every rebuild
    /// reads: the merged baseline, the liveness probe's state and the session's context.
    pub(super) fn arm_deps_and_seed(compiled: Compiled) -> Seeded {
        let Compiled {
            armed,
            mut state,
            pre_mtimes,
        } = compiled;
        let Armed {
            root: watch_root,
            out_dir: _,
            working_dir,
            config: _,
            vars_path,
            vars_path_typed,
            static_set_vars,
            static_set_string_vars,
            output_base,
            exclude_prefix,
            vars_dir_extra,
            mut armed_dirs,
            quiet,
            clear,
            debounce_ms,
            tick,
            tx,
            rx,
            mut watcher,
        } = armed;
        let root = watch_root.canonical.as_path();

        // All startup outputs are now published — the positive-control injection point.
        startup_race_probe();

        // Watch external dep dirs NonRecursive (DD3). Cross-root dependencies are only
        // discovered by the startup compile, so unlike the root they cannot be armed
        // before the first read; an edit landing in that window produces no event for
        // anyone. What closes it is the baseline [`startup_compile`] captured, which
        // predates the read — the idle tick's content backstop compares against it and
        // recompiles (#321). `MDS_WATCH_READY` still marks the instant both detectors
        // cover every path, so tests can synchronise on arming rather than on a tick.
        // Only a directory whose watch is in place is held as armed: one whose watch
        // failed is tried again by the next rebuild and the liveness tick (#257). The
        // `--vars` file's directory, when a dependency shares it, is held already and is
        // not watched a second time. A failed one is warned about here, and not again until
        // a watch of it has succeeded.
        let mut failing_dirs = BTreeSet::new();
        arm_external_dep_dirs(
            &state.external_dep_dirs,
            &mut armed_dirs,
            &mut failing_dirs,
            |dir| watcher.watch(dir, RecursiveMode::NonRecursive),
            watch_root.root_paths(),
            extra_vars_dir(vars_dir_extra.as_deref(), vars_path_typed.as_deref()),
        );

        // Seed the content backstop's baseline (#321), over the watched set: the `--vars`
        // file too, so a batch can tell it emptied (#380).
        //
        // The merge DIRECTION is load-bearing, exactly as in single-file mode: the
        // pre-compile pairs in `pre_mtimes` overwrite the post-compile ones, because only
        // they predate the reads whose results were published. Inverting the merge — or
        // switching to one that keeps the value already present — would silently restore
        // the lost-save bug while every test still passes.
        let mut last_mtimes = snapshot_state(&state.watched_set());
        // Witness for the assertion below, taken before the merge consumes `pre_mtimes`.
        // Chosen by `min()` rather than by iteration order: a `HashMap` yields an arbitrary
        // first element, which would make a failure reproduce only sometimes.
        //
        // This can only fire when the two snapshots actually differ for the witness path —
        // i.e. when the file changed during startup, which is the `startup-race-probe`
        // suite's scenario and no other. It is a canary against a future refactor inverting
        // the merge, not a runtime guarantee, and it is deliberately `debug_assert`: the
        // property is a property of the code's shape, not of any input, so a release-time
        // check would guard nothing a debug run does not already catch.
        let witness: Option<(PathBuf, FileStamp)> =
            pre_mtimes.keys().min().map(|p| (p.clone(), pre_mtimes[p]));
        last_mtimes.extend(pre_mtimes);
        if let Some((path, pre)) = witness {
            debug_assert_eq!(
                last_mtimes.get(&path).copied(),
                Some(pre),
                "baseline merge inverted: a pre-compile (mtime, size) must survive the merge \
                 with the post-compile snapshot, or an edit made during startup can never \
                 register as a difference on the idle tick"
            );
        }
        state.last_mtimes = last_mtimes;

        let liveness = LivenessState {
            first_tick: true,
            root_was_missing: !root.exists(),
            // root_armed = true when root existed at startup (watcher.watch was just called).
            // false when root was missing at startup so the first tick re-arms it on appearance.
            root_armed: root.exists(),
            // Seed with any external dep dirs that don't exist yet so their first
            // appearance is treated as a recovery edge (not a per-tick walk).
            missing_external_dirs: state
                .external_dep_dirs
                .iter()
                .filter(|d| !d.exists())
                .cloned()
                .collect(),
            // The directories whose startup watch is in place, and only those.
            armed_dirs,
            // The dependencies' directories whose startup watch failed, warned about.
            failing_dirs,
        };

        let ctx = DirWatchCtx {
            root: watch_root,
            working_dir,
            vars_path,
            vars_path_typed,
            static_set_vars,
            static_set_string_vars,
            output_base,
            exclude_prefix,
            vars_dir_extra,
            clear,
            debounce_ms,
            quiet,
        };

        Seeded {
            tx,
            rx,
            tick,
            session: DirSession {
                ctx,
                watcher,
                state,
                liveness,
            },
        }
    }

    impl Seeded {
        /// Every watch armed and every baseline taken: go live — Ctrl+C wired last — and
        /// watch until the session stops ([`live::run_session`]).
        pub(super) fn go_live(self) {
            let Seeded {
                tx,
                rx,
                tick,
                session,
            } = self;
            live::run_session(tx, rx, tick, session);
        }
    }

    impl live::Session for DirSession {
        fn is_quiet(&self) -> bool {
            self.ctx.quiet
        }

        fn hold_deadline(&self) -> Option<Instant> {
            self.state.hold.deadline()
        }

        fn on_tick(&mut self) -> ControlFlow<StopReason> {
            // Idle tick — run liveness probe (reconcile rule, DD1).
            liveness_probe_dir(
                &self.ctx,
                &mut self.watcher,
                &mut self.liveness,
                &mut self.state,
            );
            ControlFlow::Continue(())
        }

        fn on_hold_due(&mut self) -> ControlFlow<StopReason> {
            // The batches held back, with nothing new: the rebuild decides the hold first,
            // at an instant no earlier than its deadline, so it ends the hold whatever the
            // files hold or the clock does (#380).
            let due = self.state.hold.deadline();
            rebuild_dir_batch(&self.ctx, &BTreeSet::new(), false, &mut self.state, due);
            arm_external_dirs_after_rebuild(
                &self.ctx,
                &mut self.watcher,
                &mut self.liveness,
                &self.state,
            );
            ControlFlow::Continue(())
        }

        fn on_message(&mut self, msg: Msg, rx: &mpsc::Receiver<Msg>) -> ControlFlow<StopReason> {
            match handle_fs_event_dir(msg, &self.ctx, rx, &mut self.state) {
                DirEventOutcome::Skip => ControlFlow::Continue(()),
                DirEventOutcome::Done => {
                    arm_external_dirs_after_rebuild(
                        &self.ctx,
                        &mut self.watcher,
                        &mut self.liveness,
                        &self.state,
                    );
                    ControlFlow::Continue(())
                }
                DirEventOutcome::Stop => ControlFlow::Break(StopReason::Interrupted),
            }
        }
    }
}

/// Process a batch of changed `.mds` paths in directory mode.
///
/// Thin dispatcher: delegates to `process_dir_batch_vars_changed` when every source
/// must be recompiled (vars file changed) — the known ones, those the batch names and
/// those whose last compile failed — or to `process_dir_batch_incremental` for a normal
/// seed-and-propagate pass.
///
/// Called by both the event path and the reconcile path so the same state
/// transitions apply uniformly.
///
/// `ctx.vars` reports the `--vars` file's duplicate keys with the first source that shows
/// something, and only then (#326): a single logical edit can reach this function more
/// than once (e.g. multiple raw FS events for one write at `--debounce 0`, or a
/// liveness-probe self-heal tick racing a real FS event for the same change), and only
/// the first batch finds an output changed.
fn process_dir_batch(
    changed: &BTreeSet<PathBuf>,
    vars_changed: bool,
    ctx: &mut BatchCtx<'_>,
    state: &mut DirWatchState,
) {
    if vars_changed {
        process_dir_batch_vars_changed(changed, ctx, state);
    } else {
        process_dir_batch_incremental(changed, ctx, state);
    }

    // Re-baseline the content backstop over the post-batch watched set (#321) — the
    // tracked set and the `--vars` file, so a file the batch compiled empty is not taken
    // for one emptied since (#380) — and over the sources the batch held back (#380).
    //
    // This is the single settle point for `last_mtimes`, and it has to be here rather
    // than at each compile site: the batch is what the idle tick must not report again,
    // and only the batch as a whole knows which paths it covered. Doing it once, over
    // the whole set, also settles the sources a *failed* compile touched (so an
    // unchanged broken file does not re-fire every tick) and drops keys for sources the
    // batch deleted, which are no longer watched.
    //
    // The stamps are the ones the batch's look took, before anything was read (#380) — a
    // source the batch named included, one it created too, and one no compile of which had
    // succeeded, compiled again for that failure by a batch that does not name it. Only a
    // file no look stamped is `stat`ed here: a dependency a compile discovered. A file
    // changed since the look therefore still differs: one truncated while the batch ran —
    // after the batch read it, or in a batch that does not read it — is found emptied by
    // the next look, where its own events would otherwise rebuild against an empty file
    // taken for the one the session saw, publishing it empty or reporting it; one whose
    // compile read it emptied, which held its source, stays emptied; and one saved after
    // the look is found changed again by the idle tick.
    state.rebaseline();
}

/// What a path a directory batch names is to the watch, by where it is and what it is
/// called (#380): the one answer the event filter, the batches' source lists and the
/// compile dispatch all take ([`classify`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Node {
    /// A `.mds` file below the root, outside the directories the walk skips, whose name
    /// does not start with `_`: compiled, and its output written.
    Source,
    /// A source whose name starts with `_`: compiled for its dependencies, never written.
    Partial,
    /// A file below the root that is no `.mds` file and outside the directories the walk
    /// skips — a `type: mds` `.md` module: left to the sources that import it.
    InRootModule,
    /// A file in a directory outside the root that a source imports from.
    ExternalDep,
    /// A file in a directory below the root that the walk skips (hidden directories,
    /// `node_modules/`).
    ExcludedDep,
    /// Anything else: no file the watch reads.
    Unrelated,
}

impl Node {
    /// Whether the path is a source of the watch: what a full walk would find.
    fn is_source(self) -> bool {
        matches!(self, Node::Source | Node::Partial)
    }
}

/// Whether `path` is named as a `.mds` file.
fn has_mds_extension(path: &Path) -> bool {
    path.extension().is_some_and(|ext| ext == "mds")
}

/// What `path` is to the watch of `root`, a directory outside which `external_dirs` are the
/// directories dependencies are read from ([`DirWatchState::external_dep_dirs`]).
fn classify(root: &Path, path: &Path, external_dirs: &BTreeSet<PathBuf>) -> Node {
    if path.starts_with(root) {
        if is_within_default_excluded_dir(root, path) {
            Node::ExcludedDep
        } else if !has_mds_extension(path) {
            Node::InRootModule
        } else if is_partial(path) {
            Node::Partial
        } else {
            Node::Source
        }
    } else if external_dirs
        .iter()
        .any(|dir| path.parent() == Some(dir.as_path()))
    {
        Node::ExternalDep
    } else {
        Node::Unrelated
    }
}

/// Whether `path`, which a directory batch names, is a source of the watch below `root`: a
/// `.mds` file there, outside the directories the walk skips — what a full walk would
/// find (#380). A dependency the batch names, an in-root module that is no `.mds` file
/// included, is none. Whether it is one never depends on the directories outside the root,
/// so a caller that holds none asks this.
fn names_a_source(root: &Path, path: &Path) -> bool {
    classify(root, path, &BTreeSet::new()).is_source()
}

/// Full recompile of every source triggered by a vars-file change: the known ones, and
/// those `changed` names that no walk has found ([`names_a_source`]) — one created in the
/// same batch, in a batch held with it, or in one the vars file could not be read for,
/// which is then known as the walk's are (#380) — and those whose last compile failed,
/// which only `errored` may name: one created by a batch whose compile failed (#380).
/// A dependency `changed` names is recompiled through its importers, which all are; an
/// errored dependency is no source, and is left to its importers the same way.
///
/// Recomputes the entire forward-deps graph, external-dep-dirs, and errored set
/// from scratch (prunes stale entries left over from deleted sources) — but a source whose
/// compile fails, or is held, keeps the dependencies its last compile reported, as an
/// incremental batch keeps them (#380).
///
/// Also runs the same deletion cleanup that `process_dir_batch_incremental` does so
/// that a `.mds` deleted in the same debounce window as a vars edit does not orphan its
/// output `.md` or leave stale `last_written` / `forward_deps` / `errored` entries
/// (rust.md / reliability issue #3 fix). A source found gone later in the batch — before
/// its compile, during it, or after it — is retired the same way (#160).
///
/// Uses `compile_one_source` for the shared compile→dedup→write sequence.
fn process_dir_batch_vars_changed(
    changed: &BTreeSet<PathBuf>,
    ctx: &mut BatchCtx<'_>,
    state: &mut DirWatchState,
) {
    let BatchCtx {
        watch_root,
        output_base,
        quiet,
        ..
    } = *ctx;
    let root = watch_root.canonical.as_path();
    let all_sources: BTreeSet<PathBuf> = state
        .known_files
        .iter()
        .chain(
            state
                .errored
                .iter()
                .chain(changed)
                .filter(|path| names_a_source(root, path)),
        )
        .cloned()
        .collect();

    // Determine which of them no longer exist — their outputs are retired just as in the
    // incremental deletion step (step 5), by the same rule (#160).
    for del_src in all_sources.iter().filter(|p| !p.exists()) {
        state.retire_deleted(del_src, watch_root, output_base, quiet);
    }

    // The graph is built again by the compiles below, so the records of a path that is no
    // source any more go. A source whose compile fails, or is held because a file it read
    // was emptied since the batch looked, reports no dependencies of its own: it keeps the
    // ones its last compile reported (#380), so the directory of one outside the root stays
    // watched, and a failed compile's look for a file emptied since takes them in.
    let mut previous = std::mem::take(&mut state.forward_deps);
    state.errored.clear();

    for src in &all_sources {
        // A source gone since the pass above is a deleted source too (#160).
        if !src.exists() {
            state.retire_deleted(src, watch_root, output_base, quiet);
            continue;
        }
        // A compile that succeeds records the dependencies it reported in their place.
        if let Some(deps) = previous.remove(src) {
            state.forward_deps.insert(src.clone(), deps);
        }
        compile_one_source(src, ctx, state);
    }
    state.external_dep_dirs = state.dep_dirs_outside(root);

    // Keep the sources still there. One gone since its compile is a deleted source as
    // well, retired by the same rule rather than dropped with its outputs left (#160).
    let (present, gone): (BTreeSet<PathBuf>, BTreeSet<PathBuf>) =
        all_sources.into_iter().partition(|p| p.exists());
    for src in &gone {
        state.retire_deleted(src, watch_root, output_base, quiet);
    }
    state.known_files = present;
}

/// Refresh the edges of `src`, a dependency outside the root or in a directory the walk
/// skips ([`Node::ExternalDep`], [`Node::ExcludedDep`]): compiled quietly, for the
/// dependencies it reports and never for an output.
fn refresh_dependency(src: &Path, ctx: &BatchCtx<'_>, state: &mut DirWatchState) {
    // Compile to refresh deps only; suppress output by using quiet=true.
    match ctx.watch_root.compile_source(
        src,
        ctx.vars.map.clone(),
        true,
        &Arc::new(mds::ReadLog::new()),
    ) {
        Ok(compiled) => {
            state
                .forward_deps
                .insert(src.to_path_buf(), graph_keys(&compiled.dependencies));
            state.errored.remove(src);
        }
        Err(failure) => {
            settle(
                SettleInto::Dir(state),
                failure.into_report(),
                Settle::MarkErrored(src),
            );
        }
    }
}

/// Incremental recompile: compile only transitive importers of the changed seeds.
///
/// Steps:
/// 1. Partition changed paths into `existing` / `deleted`.
/// 2. Compute seeds = existing ∪ deleted ∪ (errored ∩ real-change batch).
/// 3. Compute affected = transitive importers of seeds (freshness-rule snapshot).
/// 4. Compile each affected source ([`Node::Source`], [`Node::Partial`]) that exists; one
///    in the root found gone here, or by its compile, is retired as a deleted source
///    (#160). An affected dependency is no source: one outside the root or in a skipped
///    directory gets a quiet refresh of its own edges ([`refresh_dependency`]), and one in
///    the root — a `type: mds` `.md` module — none, its importers being affected with it
///    (#380).
/// 5. Delete outputs for removed sources.
///
/// Uses `compile_one_source` for the shared compile→dedup→write sequence.
fn process_dir_batch_incremental(
    changed: &BTreeSet<PathBuf>,
    ctx: &mut BatchCtx<'_>,
    state: &mut DirWatchState,
) {
    let BatchCtx {
        watch_root,
        output_base,
        quiet,
        ..
    } = *ctx;
    let root = watch_root.canonical.as_path();

    // 1. Partition.
    let (existing, deleted): (BTreeSet<PathBuf>, BTreeSet<PathBuf>) =
        changed.iter().cloned().partition(|p| p.exists());

    // 2. Seeds = existing ∪ deleted ∪ errored-if-real-change.
    let has_real_change = !existing.is_empty() || !deleted.is_empty();
    let mut seeds: BTreeSet<PathBuf> = existing.union(&deleted).cloned().collect();
    if has_real_change {
        seeds.extend(state.errored.iter().cloned());
    }

    if seeds.is_empty() {
        return;
    }

    // 3. Affected = seeds ∪ transitive importers (uses start-of-batch graph snapshot).
    let affected = affected_sources(&state.forward_deps, &seeds);

    // A debug build's test pause (#160): the batch has told its sources still there from
    // those gone, and has compiled none of them.
    pause_after_batch_split();

    // 4. Compile each affected source that exists; refresh each dependency outside the
    //    root or in a skipped directory, and leave one in the root to its importers.
    for src in &affected {
        let node = classify(root, src, &state.external_dep_dirs);

        // Not in root and not a known external dep — skip.
        if node == Node::Unrelated {
            continue;
        }

        if !src.exists() {
            // If `src` is in the `deleted` set, it is retired in step 5. If it is NOT —
            // deleted since this batch's partition, or seeded from `errored` while its
            // delete event never came (issue #7) — a source in the root is a deleted
            // source all the same: its outputs are retired now, by the same rule, and its
            // records go with them, so it does not stay a ghost entry (#160). An external
            // dependency has no output (#217), and is only forgotten.
            if !deleted.contains(src) {
                if node == Node::ExternalDep {
                    state.forget(src);
                } else {
                    state.retire_deleted(src, watch_root, output_base, quiet);
                }
            }
            continue;
        }

        match node {
            // In-root source: full compile→dedup→write via shared helper.
            Node::Source | Node::Partial => compile_one_source(src, ctx, state),
            // External deps (out-of-root) AND excluded-in-root paths (node_modules/, .git/,
            // hidden dirs) are graph nodes but never emit their own output (DD3 pattern).
            // The same limit as the initial walker's, which never recurses into those
            // dirs, applied here on the parallel event-processing path so the two paths
            // stay consistent.
            Node::ExternalDep | Node::ExcludedDep if has_mds_extension(src) => {
                refresh_dependency(src, ctx, state)
            }
            // A dependency that is no `.mds` file — a `type: mds` `.md` module, in the root
            // or not — is rebuilt through its importers, which `affected` holds, and never
            // compiled as an entry (#380). Its edges from them stay. Compiled as an entry,
            // a module edited into a plain `.md` was refused under its own path, beside
            // its importers' refusal, in every batch with a change that followed.
            Node::InRootModule | Node::ExternalDep | Node::ExcludedDep | Node::Unrelated => {}
        }
    }

    // 5. Deletions: after importers recompiled, retire the outputs and forget the graph
    //    records of each deleted source (#160).
    for del_src in &deleted {
        state.retire_deleted(del_src, watch_root, output_base, quiet);
    }

    // 6. Prune external_dep_dirs to only dirs still referenced by live forward_deps.
    //
    // `external_dep_dirs` is monotonically grown by `record_success` on every compile
    // (issue #2 / reliability.md): when a cross-root @import is edited away, the now-
    // unused dir stays in the set, causing the liveness probe to re-arm it on every tick
    // forever. Recompute from the current `forward_deps` after each batch so abandoned
    // external dirs are unwatched and removed (applies the reconcile rule / mirrors the prune
    // already done in `process_dir_batch_vars_changed`).
    //
    // The watcher is not in scope here: every rebuild is followed by
    // `arm_external_dirs_after_rebuild`, which unwatches the dirs no longer live — under
    // `--poll-interval 0` too, where no liveness tick runs (#257).
    state.external_dep_dirs = state.dep_dirs_outside(root);
}

// ── Test-only pause between a directory batch's split and its compile (#160) ──

/// `MDS_TEST_PAUSE_AFTER_BATCH_SPLIT`: how a debug build is made to stop a directory
/// watch's rebuild batch once it has told the sources still there from the sources gone,
/// and before it compiles them — after an incremental batch's partition, and again just
/// before each source's compile — so that a test can delete a source in that window
/// (`tests/cli_watch.rs`). `MDS_TEST_PAUSE_AFTER_LOOK`: how it is made to stop a rebuild,
/// in either mode, once it has looked for emptied files and found none, before it reads
/// any — so that a test can truncate a file the rebuild is about to read
/// (`tests/cli_watch_truncate.rs`, #380). `MDS_TEST_PAUSE_AFTER_READ`: how it is made to
/// stop a file-mode rebuild once its compile has read every file and none was found
/// emptied, before the rebuild takes its baseline — so that a test can truncate a file the
/// rebuild has read whole (`tests/cli_watch_truncate.rs`, #380).
/// The compile pause stops after the watched-path check and before entry resolution.
/// `MDS_TEST_PAUSE_BEFORE_LATE_LOOK`: how it is made to stop a file-mode rebuild once its
/// `--vars` load and compile have read their files, or a directory batch once one source's
/// compile has read its files, before the late look
/// ([`held_after_look`]) — so that a test can write a file the compile read empty
/// (`tests/cli_watch_truncate.rs`, #380).
/// A release build has none of these pauses.
#[cfg(debug_assertions)]
mod batch_pause_trigger {
    use std::path::PathBuf;
    use std::time::Duration;

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

    /// The variable naming the file that ends the pause after a batch's split. 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_AFTER_BATCH_SPLIT";

    /// The variable naming the file that ends the pause after a rebuild's look, which says
    /// it has stopped in the same way. A unit test that stops a batch there sets it in a
    /// child process of its own.
    pub(super) const LOOK_VARIABLE: &str = "MDS_TEST_PAUSE_AFTER_LOOK";

    /// The variable naming the file that ends the pause after a file rebuild's reads, which
    /// says it has stopped in the same way.
    const READ_VARIABLE: &str = "MDS_TEST_PAUSE_AFTER_READ";

    /// The file that ends the pause after the watched-path check, before entry resolution.
    const COMPILE_VARIABLE: &str = "MDS_TEST_PAUSE_BEFORE_WATCH_COMPILE";

    /// The variable naming the file that ends the pause after a rebuild's compile read its
    /// files, before the late look, which says it has stopped in the same way.
    const LATE_LOOK_VARIABLE: &str = "MDS_TEST_PAUSE_BEFORE_LATE_LOOK";

    /// 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 batch goes on regardless: ten seconds.
    const MAX_POLLS: u32 = 2_000;

    /// Stop here when `MDS_TEST_PAUSE_AFTER_BATCH_SPLIT` names a file ([`pause_on`]).
    pub(super) fn pause_after_batch_split() {
        pause_on(VARIABLE);
    }

    /// Stop here when `MDS_TEST_PAUSE_AFTER_LOOK` names a file ([`pause_on`]).
    pub(super) fn pause_after_look() {
        pause_on(LOOK_VARIABLE);
    }

    /// Stop here when `MDS_TEST_PAUSE_AFTER_READ` names a file ([`pause_on`]).
    pub(super) fn pause_after_read() {
        pause_on(READ_VARIABLE);
    }

    /// Stop before entry resolution when the compile pause names a file ([`pause_on`]).
    pub(super) fn pause_before_compile() {
        pause_on(COMPILE_VARIABLE);
    }

    /// Stop here when `MDS_TEST_PAUSE_BEFORE_LATE_LOOK` names a file ([`pause_on`]).
    pub(super) fn pause_before_late_look() {
        pause_on(LATE_LOOK_VARIABLE);
    }

    /// Stop here when `variable` names a file: say so by writing `<file>.paused`, then wait
    /// until `<file>` exists, or until [`MAX_POLLS`] looks have found none.
    fn pause_on(variable: &str) {
        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 batch 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)]
use batch_pause_trigger::{
    pause_after_batch_split, pause_after_look, pause_after_read, pause_before_compile,
    pause_before_late_look,
};

/// A release build's pause between a directory batch's split and its compile: none.
#[cfg(not(debug_assertions))]
fn pause_after_batch_split() {}

/// A release build's pause between a rebuild's look and its reads: none.
#[cfg(not(debug_assertions))]
fn pause_after_look() {}

/// A release build's pause between a file rebuild's reads and its baseline: none.
#[cfg(not(debug_assertions))]
fn pause_after_read() {}

/// A release build has no pause before entry resolution.
#[cfg(not(debug_assertions))]
fn pause_before_compile() {}

/// A release build's pause between a rebuild's compile and its late look: none.
#[cfg(not(debug_assertions))]
fn pause_before_late_look() {}

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

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

    /// #265: a `--vars` path carrying a forbidden character is refused before the
    /// filesystem is touched — whether or not it exists — with the message
    /// `NativeFs::check_symlink` gives an existing one; a clean missing path is still
    /// kept for later creation (control).
    #[test]
    fn canonicalize_vars_path_refuses_a_forbidden_char_before_existence() {
        let dir = tempfile::tempdir().unwrap();
        for ch in ['\t', '\x1b', '\n', '\u{202E}'] {
            let hostile = dir.path().join(format!("v{ch}q")).join("x.json");
            let err = canonicalize_vars_path(Some(hostile.clone()))
                .expect_err("a hostile --vars path is refused");
            let s = err.serialize();
            assert_eq!(s.code, "mds::io", "U+{:04X}", u32::from(ch));
            assert!(
                s.message.starts_with(&format!(
                    "path contains forbidden character U+{:04X}: \"",
                    u32::from(ch)
                )),
                "got: {}",
                s.message
            );
            assert!(!s.message.contains(ch), "raw char: {:?}", s.message);
        }

        let clean = dir.path().join("missing.json");
        assert_eq!(
            canonicalize_vars_path(Some(clean.clone())).unwrap(),
            Some(clean),
            "control: a clean missing --vars path is kept"
        );
    }

    // T-U1: dirs_to_watch deduplicates parents.
    #[test]
    fn dirs_to_watch_deduplicates_parents() {
        let entry = PathBuf::from("/project/src/entry.mds");
        let deps = vec![
            PathBuf::from("/project/src/a.mds"),
            PathBuf::from("/project/src/b.mds"), // same parent as entry
            PathBuf::from("/project/lib/c.mds"), // different parent
        ];
        let vars = PathBuf::from("/project/vars.json");
        let dirs = dirs_to_watch(&entry, &deps, Some(&vars));
        // Expect exactly 3 unique parents: /project/src, /project/lib, /project
        assert!(dirs.contains(&PathBuf::from("/project/src")));
        assert!(dirs.contains(&PathBuf::from("/project/lib")));
        assert!(dirs.contains(&PathBuf::from("/project")));
        assert_eq!(dirs.len(), 3, "should deduplicate identical parent dirs");
    }

    // T-U2: files_of_interest contains entry + deps + vars.
    #[test]
    fn files_of_interest_contains_all() {
        let entry = PathBuf::from("/a/entry.mds");
        let deps = vec![PathBuf::from("/a/dep1.mds"), PathBuf::from("/b/dep2.mds")];
        let vars = PathBuf::from("/c/vars.json");
        let foi = files_of_interest(&entry, &deps, Some(&vars));
        assert!(foi.contains(&PathBuf::from("/a/entry.mds")));
        assert!(foi.contains(&PathBuf::from("/a/dep1.mds")));
        assert!(foi.contains(&PathBuf::from("/b/dep2.mds")));
        assert!(foi.contains(&PathBuf::from("/c/vars.json")));
        assert_eq!(foi.len(), 4);
    }

    /// #390: a graph key and file mode's content-dedup key are paths, never their text.
    /// Two paths whose names differ only in bytes that are not UTF-8 are one text once
    /// made lossy — the key the text mapping built, which let them share one graph node
    /// and one dedup entry — and stay two keys.
    ///
    /// The paths are built from bytes and no such file is created, so it runs on every
    /// unix: macOS's filesystem refuses such a name, but nothing here asks it for one.
    #[cfg(unix)]
    #[test]
    fn distinct_non_utf8_paths_stay_distinct_graph_and_output_keys() {
        use std::ffi::OsStr;
        use std::os::unix::ffi::OsStrExt;

        let dir = tempfile::tempdir().unwrap();
        let a = dir.path().join(OsStr::from_bytes(b"\xff.mds"));
        let b = dir.path().join(OsStr::from_bytes(b"\xfe.mds"));
        // Control: one text once made lossy.
        assert_ne!(a, b);
        assert_eq!(a.display().to_string(), b.display().to_string());

        let keys = graph_keys(&[a.clone(), b.clone()]);
        assert_eq!(keys.len(), 2);
        assert_ne!(keys[0], keys[1], "two dependencies, two graph keys");
        assert_eq!(keys[0].file_name(), a.file_name(), "a key keeps its bytes");

        let key = |p: &Path| OutputKey::of(Some(&WriteTarget::as_typed(p.with_extension("md"))));
        assert_ne!(key(&a), key(&b), "two outputs, two dedup keys");
        assert_ne!(key(&a), OutputKey::Stdout);
        assert_eq!(OutputKey::of(None), OutputKey::Stdout);
    }

    /// #409: watch keys a compile's dependencies by [`graph_key`] — the canonical form
    /// notify event paths are compared in — from the list the compiler reports, which
    /// `compile_native_to_content` passes on as it is. On Windows the key is verbatim while the
    /// reported path is not: the mismatch the mapping exists for.
    #[test]
    fn a_compile_s_dependencies_are_keyed_as_notify_reports_them() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(
            dir.path().join("main.mds"),
            "@import \"./lib.mds\" as lib\n{{lib.hi()}}\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("lib.mds"), "@define hi():\nHi\n@end\n").unwrap();
        let main = dir.path().join("main.mds");

        let compiled = compile_caught(
            &main,
            &main.canonicalize().unwrap(),
            None,
            true,
            &Arc::new(mds::ReadLog::new()),
        )
        .unwrap();
        let reported = mds::compile_with_deps(&main, None).unwrap().dependencies;
        assert_eq!(
            compiled.dependencies, reported,
            "the compiler's list, passed on as it is"
        );
        assert_eq!(
            graph_keys(&compiled.dependencies),
            [graph_key(&dir.path().join("lib.mds"))],
            "the dependency is keyed by the watch graph key of the imported file"
        );

        #[cfg(windows)]
        {
            assert!(graph_keys(&reported)[0]
                .to_string_lossy()
                .starts_with(r"\\?\"));
            assert!(!reported[0].starts_with(r"\\?\"));
        }
    }

    /// #390: a message about watching a directory names the entry's directory in file
    /// mode, or the directory argument, as typed, and a dependency's directory below it
    /// below it as typed; the `--vars` file's directory as that file was typed. A
    /// dependency's directory outside both has no typed form and keeps the path the
    /// compile reported. Every line that names a watched directory goes through
    /// `shown_watched_dir`: file mode's startup `failed to watch directory` and
    /// rebuild-time `failed to watch`, directory mode's `failed to watch directory`,
    /// `failed to watch vars directory` and `failed to watch external dep dir`.
    #[test]
    fn a_watched_directory_is_named_as_the_user_typed_it() {
        use std::ffi::OsStr;

        // File mode: `mds watch page.mds --vars ../v.json` in `/project`.
        let entry = WatchedPath {
            typed: PathBuf::from("page.mds"),
            canonical: PathBuf::from("/project/page.mds"),
            what: Watched::Entry,
        };
        let vars = vars_dir_paths(
            Some(Path::new("/elsewhere/v.json")),
            Some(Path::new("../v.json")),
        );
        let shown = |dir: &str| shown_watched_dir(Path::new(dir), entry.dir_paths(), vars);

        // As typed exactly — no separator added to the directory itself.
        assert_eq!(shown("/project").as_os_str(), OsStr::new("."));
        assert_eq!(shown("/elsewhere").as_os_str(), OsStr::new(".."));
        // A dependency's directory below the entry's is named below it as typed.
        assert_eq!(shown("/project/lib"), Path::new("./lib"));
        assert_eq!(shown("/project/lib/deep"), Path::new("./lib/deep"));
        // Outside the entry's directory: no typed form, below the `--vars` directory
        // included.
        assert_eq!(shown("/lib"), Path::new("/lib"));
        assert_eq!(shown("/elsewhere/sub"), Path::new("/elsewhere/sub"));
        assert_eq!(
            shown_watched_dir(Path::new("/elsewhere"), entry.dir_paths(), None),
            Path::new("/elsewhere")
        );
        // A `--vars` file beside the entry: its directory is the entry's, named as such.
        let beside = vars_dir_paths(
            Some(Path::new("/project/v.json")),
            Some(Path::new("../project/v.json")),
        );
        assert_eq!(
            shown_watched_dir(Path::new("/project"), entry.dir_paths(), beside).as_os_str(),
            OsStr::new(".")
        );

        // Directory mode: `mds watch src --vars cfg/v.json`, the `--vars` directory armed
        // as `cfg` — what a missing file's directory is, as typed.
        let root = WatchedPath {
            typed: PathBuf::from("src"),
            canonical: PathBuf::from("/project/src"),
            what: Watched::Root,
        };
        let vars = Some(RootPaths {
            typed: Path::new("cfg"),
            walked: Path::new("cfg"),
        });
        let shown = |dir: &str| shown_watched_dir(Path::new(dir), root.root_paths(), vars);
        assert_eq!(shown("/project/src").as_os_str(), OsStr::new("src"));
        assert_eq!(shown("/project/src/sub"), Path::new("src/sub"));
        assert_eq!(shown("cfg").as_os_str(), OsStr::new("cfg"));
        assert_eq!(shown("/project/shared"), Path::new("/project/shared"));
    }

    /// #257: a dependency directory outside the root is held as armed only once its
    /// watch is in place. One whose watch failed, though it exists, is tried again by the
    /// next call — the next rebuild's — and stays unarmed for the liveness tick to try; one
    /// already armed is not watched again.
    #[test]
    fn an_external_dep_dir_is_armed_only_once_its_watch_succeeds() {
        let scratch = tempfile::tempdir().unwrap();
        let (ok, refused) = (scratch.path().join("ok"), scratch.path().join("refused"));
        std::fs::create_dir(&ok).unwrap();
        std::fs::create_dir(&refused).unwrap();
        let dirs = BTreeSet::from([ok.clone(), refused.clone()]);
        let root = RootPaths {
            typed: Path::new("src"),
            walked: Path::new("/project/src"),
        };

        let (mut armed, mut failing) = (BTreeSet::new(), BTreeSet::new());
        let mut watched = Vec::new();
        let first = |dir: &Path| {
            watched.push(dir.to_path_buf());
            if dir == refused {
                Err(notify::Error::generic("refused"))
            } else {
                Ok(())
            }
        };
        arm_external_dep_dirs(&dirs, &mut armed, &mut failing, first, root, None);
        // Control: both directories exist, so existence cannot tell them apart.
        assert!(ok.is_dir() && refused.is_dir());
        assert_eq!(watched, [ok.clone(), refused.clone()]);
        assert_eq!(
            armed,
            BTreeSet::from([ok.clone()]),
            "only the directory whose watch succeeded is armed"
        );

        let mut again = Vec::new();
        let second = |dir: &Path| {
            again.push(dir.to_path_buf());
            Ok(())
        };
        arm_external_dep_dirs(&dirs, &mut armed, &mut failing, second, root, None);
        assert_eq!(
            again,
            [refused],
            "the refused directory is tried again, the armed one is not"
        );
        assert_eq!(armed, dirs);
    }

    // T-U3a: is_content_event filters Access events, passes Modify/Create/Remove/Any/Other.
    //
    // Rationale: on Linux inotify emits Access events whenever a file is read.
    // The compile step reads .mds sources, producing Access events that would
    // re-trigger compilation in a feedback loop.  is_content_event drops all
    // Access variants and lets through every kind that represents a real change.
    #[test]
    fn is_content_event_filters_access_passes_others() {
        use notify::event::{AccessKind, AccessMode, CreateKind, ModifyKind, RemoveKind};

        // All Access variants must return false.
        assert!(!is_content_event(&notify::EventKind::Access(
            AccessKind::Read
        )));
        assert!(!is_content_event(&notify::EventKind::Access(
            AccessKind::Open(AccessMode::Read)
        )));
        assert!(!is_content_event(&notify::EventKind::Access(
            AccessKind::Close(AccessMode::Read)
        )));
        assert!(!is_content_event(&notify::EventKind::Access(
            AccessKind::Close(AccessMode::Write)
        )));
        assert!(!is_content_event(&notify::EventKind::Access(
            AccessKind::Any
        )));
        assert!(!is_content_event(&notify::EventKind::Access(
            AccessKind::Other
        )));

        // Content-changing kinds must return true.
        assert!(is_content_event(&notify::EventKind::Modify(
            ModifyKind::Any
        )));
        assert!(is_content_event(&notify::EventKind::Modify(
            ModifyKind::Data(notify::event::DataChange::Any)
        )));
        assert!(is_content_event(&notify::EventKind::Create(
            CreateKind::File
        )));
        assert!(is_content_event(&notify::EventKind::Remove(
            RemoveKind::File
        )));
        assert!(is_content_event(&notify::EventKind::Any));
        assert!(is_content_event(&notify::EventKind::Other));
    }

    // T-U3: event_is_relevant matches tracked path, rejects sibling.
    #[test]
    fn event_is_relevant_matches_and_rejects() {
        let watched_path = PathBuf::from("/project/src/entry.mds");
        let sibling = PathBuf::from("/project/src/other.mds");
        let mut watched = HashSet::new();
        watched.insert(watched_path.clone());

        // Build a minimal Event with only the paths field set.
        let relevant_event = notify::Event {
            kind: notify::EventKind::Modify(notify::event::ModifyKind::Any),
            paths: vec![watched_path.clone()],
            attrs: Default::default(),
        };
        let irrelevant_event = notify::Event {
            kind: notify::EventKind::Modify(notify::event::ModifyKind::Any),
            paths: vec![sibling],
            attrs: Default::default(),
        };

        assert!(event_is_relevant(&relevant_event, &watched));
        assert!(!event_is_relevant(&irrelevant_event, &watched));
    }

    // #481: after a case-only rename on a case-insensitive volume, the event names the
    // watched file by its new spelling and the watch set holds the spelling it had at
    // startup. On a case-sensitive volume the two spellings are two files. A probe of
    // the volume picks the arm, not the OS, and each arm asserts a match and a refusal.
    #[test]
    fn event_is_relevant_matches_a_case_only_rename_of_a_watched_file() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let watched_path = root.join("Main.mds");
        std::fs::write(&watched_path, "watched").unwrap();
        let case_insensitive = root.join("MAIN.mds").exists();
        let other_case = root.join("main.mds");
        let unrelated = root.join("other.mds");
        let output = root.join("Main.md");
        std::fs::write(&unrelated, "unrelated").unwrap();
        std::fs::write(&output, "output").unwrap();
        let watched = HashSet::from([watched_path.clone()]);
        let event = |p: &Path| notify::Event {
            kind: notify::EventKind::Modify(notify::event::ModifyKind::Any),
            paths: vec![p.to_path_buf()],
            attrs: Default::default(),
        };

        if case_insensitive {
            std::fs::rename(&watched_path, &other_case).unwrap();
            let names: Vec<String> = std::fs::read_dir(&root)
                .unwrap()
                .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
                .collect();
            assert!(
                names.iter().any(|n| n == "main.mds") && !names.iter().any(|n| n == "Main.mds"),
                "arm: case-insensitive volume. The rename must change the stored name, or \
                 the event below names the old spelling and never reaches the case-only \
                 path: {names:?}"
            );
            assert!(
                event_is_relevant(&event(&other_case), &watched),
                "arm: case-insensitive volume. An event for the new spelling must match the \
                 watched old spelling"
            );
        } else {
            std::fs::write(&other_case, "another file").unwrap();
            assert_eq!(
                std::fs::read_to_string(&watched_path).unwrap(),
                "watched",
                "arm: case-sensitive volume. Main.mds and main.mds must be two files on this \
                 volume"
            );
            assert!(
                !event_is_relevant(&event(&other_case), &watched),
                "arm: case-sensitive volume. An event for another file whose name differs \
                 only in case must not match"
            );
            assert!(
                event_is_relevant(&event(&watched_path), &watched),
                "arm: case-sensitive volume. An event for the watched file must match"
            );
        }
        // Both arms: another file and the output beside the watched file never match.
        let arm = if case_insensitive {
            "case-insensitive"
        } else {
            "case-sensitive"
        };
        assert!(
            !event_is_relevant(&event(&unrelated), &watched),
            "arm: {arm} volume. An event for an unrelated file must not match"
        );
        assert!(
            !event_is_relevant(&event(&output), &watched),
            "arm: {arm} volume. An event for the output beside the watched file must not match"
        );
    }

    // T-U4: collect_mds_files recurses and is depth-bounded.
    #[test]
    fn collect_mds_files_recurses_and_depth_bounded() {
        let dir = tempfile::tempdir().unwrap();
        let sub = dir.path().join("sub");
        std::fs::create_dir(&sub).unwrap();
        let deep = sub.join("deep");
        std::fs::create_dir(&deep).unwrap();

        std::fs::write(dir.path().join("a.mds"), "Hello!").unwrap();
        std::fs::write(sub.join("b.mds"), "World!").unwrap();
        std::fs::write(deep.join("c.mds"), "Deep!").unwrap();
        std::fs::write(dir.path().join("ignore.txt"), "not mds").unwrap();

        // depth=64 should find all 3.
        let all = collect_mds_files(dir.path(), 64, None);
        let names: Vec<_> = all
            .iter()
            .filter_map(|p| p.file_name().and_then(|n| n.to_str()))
            .collect();
        assert!(names.contains(&"a.mds"), "should find top-level a.mds");
        assert!(names.contains(&"b.mds"), "should find sub/b.mds");
        assert!(names.contains(&"c.mds"), "should find deep/c.mds");
        assert!(!names.contains(&"ignore.txt"), "should skip non-.mds files");

        // depth=0 should find only top-level files.
        let top_only = collect_mds_files(dir.path(), 0, None);
        assert_eq!(top_only.len(), 1, "depth=0 should return only root files");
    }

    // T-U4b: collect_mds_files respects exclude_prefix.
    #[test]
    fn collect_mds_files_excludes_prefix() {
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("out");
        std::fs::create_dir(&out).unwrap();
        std::fs::write(dir.path().join("a.mds"), "A").unwrap();
        std::fs::write(out.join("b.mds"), "B (should be excluded)").unwrap();

        let files = collect_mds_files(dir.path(), 64, Some(&out));
        let names: Vec<_> = files
            .iter()
            .filter_map(|p| p.file_name().and_then(|n| n.to_str()))
            .collect();
        assert!(names.contains(&"a.mds"), "a.mds should be included");
        assert!(
            !names.contains(&"b.mds"),
            "b.mds inside out/ should be excluded"
        );
    }

    // Fix 2 unit tests — output_path_for / resolve_output_base

    /// An out-dir whose two forms are the same path.
    fn dir_base(d: impl Into<PathBuf>) -> OutputBase {
        let d = d.into();
        OutputBase::Dir {
            canonical: d.clone(),
            shown: d,
            below_anchor: 0,
        }
    }

    /// A loaded `mds.json` in `/project` with the given `build.output_dir`, reached as `.`.
    fn project_config(output_dir: &str) -> Option<ProjectConfig> {
        use crate::build::{BuildConfig, MdsConfig};
        Some(ProjectConfig {
            config: MdsConfig {
                build: BuildConfig {
                    output_dir: Some(output_dir.to_string()),
                    ..Default::default()
                },
                ..Default::default()
            },
            dir: PathBuf::from("/project"),
            shown_dir: PathBuf::from("."),
        })
    }

    // Mirroring: subtree preserved.
    #[test]
    fn output_path_for_mirrors_subtree() {
        let root = PathBuf::from("/root");
        let source = PathBuf::from("/root/a/b/foo.mds");
        let base = dir_base("/out");
        let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "md");
        assert_eq!(result.path, PathBuf::from("/out/a/b/foo.md"));
    }

    // No stem collision: two files with the same stem in different subdirs.
    #[test]
    fn output_path_for_no_stem_collision() {
        let root = PathBuf::from("/root");
        let a = PathBuf::from("/root/a/x.mds");
        let b = PathBuf::from("/root/b/x.mds");
        let base = dir_base("/out");
        assert_ne!(
            output_path_for(&a, RootPaths::as_typed(&root), &base, "md"),
            output_path_for(&b, RootPaths::as_typed(&root), &base, "md"),
            "two files with the same stem in different subdirs must not collide"
        );
        assert_eq!(
            output_path_for(&a, RootPaths::as_typed(&root), &base, "md").path,
            PathBuf::from("/out/a/x.md")
        );
        assert_eq!(
            output_path_for(&b, RootPaths::as_typed(&root), &base, "md").path,
            PathBuf::from("/out/b/x.md")
        );
    }

    // NextToSource: default mode places .md next to source.
    #[test]
    fn output_path_for_next_to_source() {
        let root = PathBuf::from("/root");
        let source = PathBuf::from("/root/a/b/foo.mds");
        let result = output_path_for(
            &source,
            RootPaths::as_typed(&root),
            &OutputBase::NextToSource,
            "md",
        );
        assert_eq!(result.path, PathBuf::from("/root/a/b/foo.md"));
    }

    // Compound extension and extensionless stem.
    #[test]
    fn output_path_for_compound_extension() {
        let root = PathBuf::from("/root");
        let source = PathBuf::from("/root/foo.bar.mds");
        let base = dir_base("/out");
        let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "md");
        assert_eq!(result.path, PathBuf::from("/out/foo.bar.md"));
    }

    // Path-escape guard: a source outside the root stays inside the out-dir.
    #[test]
    fn output_path_for_source_outside_root_stays_contained() {
        let root = PathBuf::from("/root");
        // Source is completely outside root — strip_prefix will fail.
        let source = PathBuf::from("/elsewhere/a/b/foo.mds");
        let base = dir_base("/out");
        let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "md");
        // Must be inside /out, not escape to /elsewhere.
        assert!(
            result.path.starts_with("/out"),
            "output must stay inside out-dir even when source is outside root; got {result:?}"
        );
        // Must not join an absolute path that escapes out-dir.
        assert_eq!(result.path, PathBuf::from("/out/foo.md"));
    }

    // resolve_output_base: --out-dir takes precedence over mds.json's build.output_dir.
    // The out-dir is absolute on every host (a rooted `/my/out` is not, on Windows) and
    // does not exist, so it resolves to itself and is shown as typed.
    #[test]
    fn resolve_output_base_outdir_wins() {
        let tmp = tempfile::tempdir().unwrap();
        let d = tmp.path().join("out");
        let result = resolve_output_base(Some(&d), &project_config("dist")).unwrap();
        assert!(
            matches!(result, OutputBase::Dir { ref canonical, ref shown, below_anchor: 0 }
                if canonical == &d && shown == &d),
            "expected Dir({d:?}), got {result:?}"
        );
    }

    // resolve_output_base: mds.json config used when no --out-dir.
    #[test]
    fn resolve_output_base_config_used_when_no_outdir() {
        let result = resolve_output_base(None, &project_config("dist")).unwrap();
        assert!(
            matches!(result, OutputBase::Dir { ref canonical, .. }
                if canonical == &PathBuf::from("/project/dist")),
            "expected Dir(/project/dist), got {result:?}"
        );
    }

    // resolve_output_base: `..` in output_dir rejected at startup.
    #[test]
    fn resolve_output_base_rejects_dotdot() {
        let result = resolve_output_base(None, &project_config("../bad"));
        assert!(
            result.is_err(),
            "resolve_output_base must reject output_dir with '..' components"
        );
    }

    // resolve_output_base: default → NextToSource.
    #[test]
    fn resolve_output_base_default_next_to_source() {
        let result = resolve_output_base(None, &None).unwrap();
        assert!(matches!(result, OutputBase::NextToSource));
    }

    // is_partial: _ prefix detection.
    #[test]
    fn is_partial_detects_underscore_prefix() {
        assert!(is_partial(Path::new("/some/dir/_partial.mds")));
        assert!(!is_partial(Path::new("/some/dir/normal.mds")));
        assert!(!is_partial(Path::new("/some/dir/a_b.mds")));
    }

    // affected_sources: chain A→B→C, edit C updates A, B, C.
    #[test]
    fn affected_sources_chain() {
        let a = PathBuf::from("/root/a.mds");
        let b = PathBuf::from("/root/b.mds");
        let c = PathBuf::from("/root/c.mds");

        let mut forward_deps = HashMap::new();
        // A imports B, B imports C.
        forward_deps.insert(a.clone(), vec![b.clone()]);
        forward_deps.insert(b.clone(), vec![c.clone()]);
        forward_deps.insert(c.clone(), vec![]);

        let mut seeds = BTreeSet::new();
        seeds.insert(c.clone());

        let affected = affected_sources(&forward_deps, &seeds);
        let affected_set: HashSet<PathBuf> = affected.into_iter().collect();

        assert!(affected_set.contains(&a), "A should be affected");
        assert!(affected_set.contains(&b), "B should be affected");
        assert!(affected_set.contains(&c), "C (seed) should be in result");
    }

    // affected_sources: shared partial → multiple importers.
    #[test]
    fn affected_sources_shared_partial() {
        let partial = PathBuf::from("/root/_p.mds");
        let a = PathBuf::from("/root/a.mds");
        let b = PathBuf::from("/root/b.mds");

        let mut forward_deps = HashMap::new();
        forward_deps.insert(a.clone(), vec![partial.clone()]);
        forward_deps.insert(b.clone(), vec![partial.clone()]);
        forward_deps.insert(partial.clone(), vec![]);

        let mut seeds = BTreeSet::new();
        seeds.insert(partial.clone());

        let affected = affected_sources(&forward_deps, &seeds);
        let affected_set: HashSet<PathBuf> = affected.into_iter().collect();

        assert!(affected_set.contains(&a));
        assert!(affected_set.contains(&b));
        assert!(affected_set.contains(&partial));
    }

    // affected_sources: cycle terminates (bounded).
    #[test]
    fn affected_sources_cycle_terminates() {
        let a = PathBuf::from("/root/a.mds");
        let b = PathBuf::from("/root/b.mds");

        let mut forward_deps = HashMap::new();
        // A → B → A (cycle)
        forward_deps.insert(a.clone(), vec![b.clone()]);
        forward_deps.insert(b.clone(), vec![a.clone()]);

        let mut seeds = BTreeSet::new();
        seeds.insert(a.clone());

        // Must terminate and return both.
        let affected = affected_sources(&forward_deps, &seeds);
        let affected_set: HashSet<PathBuf> = affected.into_iter().collect();
        assert!(affected_set.contains(&a));
        assert!(affected_set.contains(&b));
    }

    // affected_sources: leaf-only (seed not in graph → just seed returned).
    #[test]
    fn affected_sources_seed_not_in_graph() {
        let forward_deps: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();
        let lone = PathBuf::from("/root/lone.mds");
        let mut seeds = BTreeSet::new();
        seeds.insert(lone.clone());
        let affected = affected_sources(&forward_deps, &seeds);
        assert_eq!(affected, vec![lone]);
    }

    // affected_sources: dual-role node visited once (AC-R6).
    #[test]
    fn affected_sources_dual_role_visited_once() {
        // B is both an importer of C and imported by A.
        let a = PathBuf::from("/root/a.mds");
        let b = PathBuf::from("/root/b.mds");
        let c = PathBuf::from("/root/c.mds");

        let mut forward_deps = HashMap::new();
        forward_deps.insert(a.clone(), vec![b.clone()]);
        forward_deps.insert(b.clone(), vec![c.clone()]);
        forward_deps.insert(c.clone(), vec![]);

        let mut seeds = BTreeSet::new();
        seeds.insert(c.clone());

        let affected = affected_sources(&forward_deps, &seeds);
        // B should appear exactly once.
        let b_count = affected.iter().filter(|p| *p == &b).count();
        assert_eq!(b_count, 1, "dual-role node B should appear exactly once");
    }

    // external_recovery_decision: a dir that STAYS missing across ticks does NOT
    // trigger recovery (reconcile rule / AC-P1 — no per-tick full-tree walk).
    #[test]
    fn external_recovery_missing_stays_missing_no_recovery() {
        let gone = PathBuf::from("/elsewhere/shared");
        let prev_missing: BTreeSet<PathBuf> = std::iter::once(gone.clone()).collect();
        // Still missing this tick.
        let statuses = vec![(gone.clone(), false, false)];
        let (recovery, now_missing) = external_recovery_decision(&prev_missing, &statuses);
        assert!(
            !recovery,
            "a permanently-missing external dir must NOT trigger a reconcile"
        );
        assert!(
            now_missing.contains(&gone),
            "still-missing dir stays tracked"
        );
    }

    // external_recovery_decision: a previously-missing dir that REAPPEARS triggers
    // recovery (vanish→reappear edge).
    #[test]
    fn external_recovery_reappear_triggers_recovery() {
        let dir = PathBuf::from("/elsewhere/shared");
        let prev_missing: BTreeSet<PathBuf> = std::iter::once(dir.clone()).collect();
        // Now exists and re-armed OK.
        let statuses = vec![(dir.clone(), true, true)];
        let (recovery, now_missing) = external_recovery_decision(&prev_missing, &statuses);
        assert!(
            recovery,
            "a reappeared external dir must trigger a reconcile"
        );
        assert!(
            now_missing.is_empty(),
            "reappeared dir no longer tracked as missing"
        );
    }

    // external_recovery_decision: re-arming an EXISTING dir failed → genuine watch
    // loss → recovery.
    #[test]
    fn external_recovery_rearm_failure_triggers_recovery() {
        let dir = PathBuf::from("/elsewhere/shared");
        let prev_missing = BTreeSet::new();
        // Exists but re-arm failed.
        let statuses = vec![(dir.clone(), true, false)];
        let (recovery, now_missing) = external_recovery_decision(&prev_missing, &statuses);
        assert!(
            recovery,
            "a failed re-arm of an existing dir must trigger a reconcile"
        );
        assert!(now_missing.is_empty());
    }

    // external_recovery_decision: all dirs present and stable → no recovery, no walk.
    #[test]
    fn external_recovery_stable_no_recovery() {
        let a = PathBuf::from("/ext/a");
        let b = PathBuf::from("/ext/b");
        let prev_missing = BTreeSet::new();
        let statuses = vec![(a, true, true), (b, true, true)];
        let (recovery, now_missing) = external_recovery_decision(&prev_missing, &statuses);
        assert!(
            !recovery,
            "stable existing external dirs must not trigger a reconcile"
        );
        assert!(now_missing.is_empty());
    }

    // snapshot_state / state_differs: the size leg of the (mtime, size) stamp.
    //
    // The rewrite changes the length, so the change is visible however coarse the
    // filesystem's mtime clock is. Two back-to-back writes of equal length can share
    // one mtime tick (NTFS, FAT, jiffy-granular ext4) — the mtime leg is pinned
    // deterministically by `snapshot_and_diff_detect_same_size_mtime_change`.
    #[test]
    fn snapshot_and_diff_detect_change() {
        let dir = tempfile::tempdir().unwrap();
        let f = dir.path().join("test.mds");
        std::fs::write(&f, "v1").unwrap();

        let paths: HashSet<PathBuf> = std::iter::once(f.clone()).collect();
        let snap = snapshot_state(&paths);
        // No change yet.
        assert!(!state_differs(&paths, &snap));

        // Modify the file.
        std::fs::write(&f, "v2 — longer").unwrap();
        assert!(state_differs(&paths, &snap), "should detect content change");
    }

    // snapshot_state / state_differs: the mtime leg of the (mtime, size) stamp.
    //
    // A same-size rewrite is detectable only through mtime, so the test sets the
    // mtime explicitly instead of relying on the clock ticking between two writes.
    #[test]
    fn snapshot_and_diff_detect_same_size_mtime_change() {
        let dir = tempfile::tempdir().unwrap();
        let f = dir.path().join("test.mds");
        std::fs::write(&f, "v1").unwrap();

        let paths: HashSet<PathBuf> = std::iter::once(f.clone()).collect();
        let snap = snapshot_state(&paths);
        let (t0, size0) = snap[&f];
        let t0 = t0.expect("mtime must be readable on the test filesystem");

        std::fs::write(&f, "v2").unwrap();
        let set_mtime = |t: std::time::SystemTime| {
            std::fs::OpenOptions::new()
                .write(true)
                .open(&f)
                .unwrap()
                .set_modified(t)
                .unwrap();
        };
        assert_eq!(
            std::fs::metadata(&f).unwrap().len(),
            size0.unwrap(),
            "precondition: the rewrite keeps the size, so only mtime can differ"
        );

        // Control: with the mtime restored to the snapshot's, the stamp is identical —
        // this is the coarse-clock case, and it proves the setter controls the stamp.
        set_mtime(t0);
        assert!(
            !state_differs(&paths, &snap),
            "control: same size and same mtime must compare equal"
        );

        set_mtime(t0 + Duration::from_secs(2));
        assert!(
            state_differs(&paths, &snap),
            "should detect an mtime-only change"
        );
    }

    // snapshot_state: disappearing file detected.
    #[test]
    fn snapshot_detects_disappearing_file() {
        let dir = tempfile::tempdir().unwrap();
        let f = dir.path().join("gone.mds");
        std::fs::write(&f, "initial").unwrap();

        let paths: HashSet<PathBuf> = std::iter::once(f.clone()).collect();
        let snap = snapshot_state(&paths);
        // File existed in snap.
        std::fs::remove_file(&f).unwrap();
        assert!(
            state_differs(&paths, &snap),
            "should detect deleted file as changed"
        );
    }

    // AC-C: clamp_poll_interval contract — 0 disables liveness probe; nonzero values ≥50ms
    // are passed through; values below 50ms are clamped up to the floor.
    #[test]
    fn clamp_poll_interval_zero_disables_probe() {
        assert_eq!(
            clamp_poll_interval(0),
            None,
            "poll_interval=0 must disable the liveness probe (blocking recv)"
        );
    }

    #[test]
    fn clamp_poll_interval_one_clamped_to_50ms() {
        assert_eq!(
            clamp_poll_interval(1),
            Some(Duration::from_millis(50)),
            "poll_interval=1 must be clamped to the 50ms floor"
        );
    }

    #[test]
    fn clamp_poll_interval_exactly_50_unchanged() {
        assert_eq!(
            clamp_poll_interval(50),
            Some(Duration::from_millis(50)),
            "poll_interval=50 (at the floor) must pass through unchanged"
        );
    }

    #[test]
    fn clamp_poll_interval_above_floor_unchanged() {
        assert_eq!(
            clamp_poll_interval(1000),
            Some(Duration::from_millis(1000)),
            "poll_interval=1000 (above floor) must pass through unchanged"
        );
    }

    #[test]
    fn clamp_poll_interval_75ms_unchanged() {
        assert_eq!(
            clamp_poll_interval(75),
            Some(Duration::from_millis(75)),
            "poll_interval=75 (above floor) must pass through unchanged"
        );
    }

    // ── Idle-tick schedule (#319, #397) ──────────────────────────────────────
    //
    // The probe-starvation defect. These assert the two properties that make the idle
    // tick a usable backstop rather than a best-effort one: it fires under load, and
    // it does not fire more often than its interval. They run on synthetic instants:
    // `Instant::now()` is read once per test as an arbitrary origin, and every other
    // instant is an exact offset from it, so no assertion depends on how fast the
    // runner is.

    fn ms(n: u64) -> Duration {
        Duration::from_millis(n)
    }

    /// Runs `driver` on a worker thread and waits at most 5s for its result, so a driver
    /// that lost its bound fails the test by name rather than hanging the test binary.
    ///
    /// The worker is deliberately not joined on the timeout path: it is stuck because
    /// its bound is gone, and joining it would bring the hang back. A worker waiting on
    /// the watch channel ends once the test unwinds and drops the channel's sender.
    fn within_5s<T: Send + 'static>(what: &str, driver: impl FnOnce() -> T + Send + 'static) -> T {
        let (done_tx, done_rx) = mpsc::channel();
        std::thread::spawn(move || {
            // The test may already have given up; the send failing is fine.
            let _ = done_tx.send(driver());
        });
        done_rx
            .recv_timeout(Duration::from_secs(5))
            .unwrap_or_else(|e| panic!("{what} did not return within 5s ({e:?})"))
    }

    /// Replays [`TickClock::recv_next`] on a channel that is never empty: every poll
    /// that is not `Due` takes a message, and handling one moves the clock on by
    /// `per_message`. Returns when each tick came due before `until`, as offsets.
    fn ticks_under_saturation(
        interval: Duration,
        per_message: Duration,
        until: Duration,
    ) -> Vec<Duration> {
        let t0 = Instant::now();
        let mut schedule = TickSchedule::start(Some(interval), t0);
        let mut now = t0;
        let mut ticks = Vec::new();
        // Bounded: one step per message or tick.
        for _ in 0..10_000 {
            if now >= t0 + until {
                return ticks;
            }
            match schedule.poll(now) {
                TickPoll::Due => ticks.push(now - t0),
                TickPoll::Wait(_) | TickPoll::Never => now += per_message,
            }
        }
        panic!("the replay did not reach {until:?} within 10 000 steps; ticks so far: {ticks:?}");
    }

    /// The tick comes due one interval after the session starts, and re-arms from the
    /// instant it fired — whether a poll found it due or the driver's wait ran out.
    #[test]
    fn tick_schedule_comes_due_one_interval_after_it_starts() {
        let t0 = Instant::now();
        let mut schedule = TickSchedule::start(Some(ms(50)), t0);
        assert_eq!(schedule.poll(t0), TickPoll::Wait(ms(50)));
        assert_eq!(schedule.poll(t0 + ms(49)), TickPoll::Wait(ms(1)));
        assert_eq!(
            schedule.poll(t0 + ms(50)),
            TickPoll::Due,
            "an idle channel must produce a tick one interval in"
        );
        assert_eq!(
            schedule.poll(t0 + ms(50)),
            TickPoll::Wait(ms(50)),
            "a due tick re-arms one interval after it fired"
        );

        // The driver's wait for a message ran out at the deadline: it re-arms from there.
        schedule.rearm(t0 + ms(100));
        assert_eq!(schedule.poll(t0 + ms(100)), TickPoll::Wait(ms(50)));
        assert_eq!(schedule.poll(t0 + ms(150)), TickPoll::Due);
    }

    /// A due tick is reported before the next message is taken, so a channel that is
    /// never empty cannot postpone it (#319).
    ///
    /// The starvation bug handed `recv_timeout` a fresh interval per message, so a
    /// sender faster than the tick rate postponed the probe forever. Here a message is
    /// always waiting: each tick still comes due on the first poll at or after its
    /// deadline — on time when the message cadence divides the interval, otherwise at
    /// most one message late — and each next one a full interval after it.
    #[test]
    fn tick_schedule_is_due_first_under_saturation() {
        assert_eq!(
            ticks_under_saturation(ms(50), ms(5), ms(210)),
            [ms(50), ms(100), ms(150), ms(200)],
            "a saturated channel must not postpone a tick past its deadline"
        );
        assert_eq!(
            ticks_under_saturation(ms(50), ms(7), ms(230)),
            [ms(56), ms(112), ms(168), ms(224)],
            "a tick is due at the first poll at or after its deadline, under saturation too"
        );
    }

    /// Two ticks are never closer together than one interval, however loaded the loop.
    ///
    /// The counterpart to the test above: making the tick non-starvable must not make
    /// it free-running. A deadline that advanced from the *previous* deadline rather
    /// than from the moment the tick was observed would fire a catch-up burst after
    /// any slow probe.
    #[test]
    fn tick_schedule_rearms_from_the_tick_it_observed() {
        let t0 = Instant::now();
        let interval = ms(50);
        let mut schedule = TickSchedule::start(Some(interval), t0);
        assert_eq!(schedule.poll(t0 + ms(50)), TickPoll::Due, "first tick");

        // A probe that overran its own interval: the next poll comes 120ms later.
        assert_eq!(
            schedule.poll(t0 + ms(170)),
            TickPoll::Due,
            "an overdue tick must fire immediately, not wait another interval"
        );
        assert_eq!(
            schedule.poll(t0 + ms(170)),
            TickPoll::Wait(interval),
            "the tick following an overdue one must wait a full interval, not fire a \
             catch-up burst"
        );
        assert_eq!(schedule.poll(t0 + ms(219)), TickPoll::Wait(ms(1)));
        assert_eq!(schedule.poll(t0 + ms(220)), TickPoll::Due);
    }

    /// `--poll-interval 0`: no tick ever comes due, however long the session runs.
    #[test]
    fn tick_schedule_without_interval_never_comes_due() {
        let t0 = Instant::now();
        let mut off = TickSchedule::start(None, t0);
        let mut on = TickSchedule::start(Some(ms(50)), t0);
        for later in [Duration::ZERO, ms(50), Duration::from_secs(3_600)] {
            assert_eq!(off.poll(t0 + later), TickPoll::Never, "at {later:?}");
        }
        assert_eq!(
            on.poll(t0 + ms(50)),
            TickPoll::Due,
            "positive control: with an interval the same instant is due"
        );
    }

    /// `--poll-interval 0` with no rebuild held: `recv_next` blocks for a message.
    #[test]
    fn tick_clock_without_interval_never_ticks() {
        let (tx, rx) = mpsc::channel::<Msg>();
        let mut clock = TickClock::new(None);
        tx.send(Msg::Interrupt).expect("send failed");
        assert!(
            matches!(
                clock.recv_next(&rx, None),
                Ok(Wake::Message(Msg::Interrupt))
            ),
            "with no poll interval the clock must deliver the message, never a tick"
        );
        drop(tx);
        assert!(
            matches!(clock.recv_next(&rx, None), Err(mpsc::RecvError)),
            "a closed channel must report Disconnected rather than tick forever"
        );
    }

    /// The driver serves a due tick before it takes a waiting message (#319). The
    /// schedule has already re-armed when it reports the tick due, so a driver that took
    /// the message first would lose that tick, and a channel that is never empty would
    /// starve the probe again.
    ///
    /// The schedule is built already due, with an interval of an hour: the second call
    /// cannot find another tick due however slow the runner is.
    #[test]
    fn tick_clock_serves_a_due_tick_before_a_waiting_message() {
        let (tx, rx) = mpsc::channel::<Msg>();
        tx.send(Msg::Interrupt).expect("send failed");
        let mut clock = TickClock {
            schedule: TickSchedule::Every {
                interval: Duration::from_secs(3_600),
                next: Instant::now(),
            },
        };

        assert!(
            matches!(clock.recv_next(&rx, None), Ok(Wake::Tick)),
            "a due tick must be served before the message waiting in the channel"
        );
        assert!(
            matches!(
                clock.recv_next(&rx, None),
                Ok(Wake::Message(Msg::Interrupt))
            ),
            "positive control: the waiting message is delivered next, not lost"
        );
        drop(tx);
    }

    /// When the driver's wait for a message runs out, it serves the tick and re-arms one
    /// interval from that instant. Without the re-arm the deadline stays in the past,
    /// and the next call reports a second tick at once.
    ///
    /// A lower bound only: `t1` is read before the clock starts, the wait cannot run out
    /// before the first deadline (`t1 + interval` at the earliest), and the re-arm adds
    /// one interval to the instant it ran out. The sender stays alive, so the driver
    /// runs under [`within_5s`]: one whose wait never ran out fails by name.
    #[test]
    fn tick_clock_rearms_when_its_wait_runs_out() {
        let interval = ms(50);
        let (tx, rx) = mpsc::channel::<Msg>();
        let t1 = Instant::now();
        let (wake, clock, _rx) = within_5s("an idle tick", move || {
            let mut clock = TickClock::new(Some(interval));
            (clock.recv_next(&rx, None), clock, rx)
        });

        assert!(
            matches!(wake, Ok(Wake::Tick)),
            "an idle channel's wait runs out at the tick"
        );
        let TickSchedule::Every { next, .. } = clock.schedule else {
            panic!("a clock started with an interval keeps it");
        };
        assert!(
            next >= t1 + interval * 2,
            "the next tick must come due one interval after the wait ran out, not at the \
             deadline that has just passed: due {:?} after the clock started, expected at \
             least {:?}",
            next - t1,
            interval * 2
        );
        drop(tx);
    }

    // ── Empty-file hold (#380) ───────────────────────────────────────────────
    //
    // A rebuild held while a watched file is empty runs at a deadline fixed by the first
    // rebuild that found the file emptied. These run on synthetic instants, as the tick
    // tests above do.

    /// A file the baseline saw with bytes and finds with none went empty; nothing else
    /// did.
    #[test]
    fn went_empty_is_a_file_with_bytes_found_with_none() {
        let stamp = |size: Option<u64>| -> FileStamp { (Some(std::time::UNIX_EPOCH), size) };
        assert!(
            went_empty(Some(&stamp(Some(5))), &stamp(Some(0))),
            "bytes, then none"
        );
        assert!(
            !went_empty(Some(&stamp(Some(0))), &stamp(Some(0))),
            "a file empty from the start, or compiled since it was emptied"
        );
        assert!(
            !went_empty(None, &stamp(Some(0))),
            "a file the baseline never saw"
        );
        assert!(
            !went_empty(Some(&stamp(None)), &stamp(Some(0))),
            "a file the baseline saw missing"
        );
        assert!(
            !went_empty(Some(&stamp(Some(5))), &stamp(None)),
            "a file that is gone"
        );
        assert!(
            !went_empty(Some(&stamp(Some(5))), &stamp(Some(3))),
            "a file that still has bytes"
        );
    }

    /// The held rebuild's deadline is set by the first rebuild that finds a watched file
    /// emptied, and no later one moves it: each finds the hold running until the deadline,
    /// and the first at it compiles and ends the hold.
    #[test]
    fn empty_hold_deadline_is_fixed_at_the_first_empty_observation() {
        let t0 = Instant::now();
        let mut hold = EmptyHold::default();
        assert_eq!(
            hold.deadline(),
            None,
            "nothing is held before a file is emptied"
        );
        assert_eq!(hold.on_rebuild(true, t0), HoldVerdict::Hold);
        assert_eq!(hold.deadline(), Some(t0 + EMPTY_HOLD_DEADLINE));
        for k in 1..10u64 {
            let now = t0 + ms(100 * k);
            assert_eq!(hold.on_rebuild(true, now), HoldVerdict::Hold, "at {now:?}");
            assert_eq!(
                hold.deadline(),
                Some(t0 + EMPTY_HOLD_DEADLINE),
                "a rebuild {}ms in must not move the deadline",
                100 * k
            );
        }
        let just_before = t0 + EMPTY_HOLD_DEADLINE - Duration::from_nanos(1);
        assert_eq!(hold.on_rebuild(true, just_before), HoldVerdict::Hold);
        assert_eq!(
            hold.on_rebuild(true, t0 + EMPTY_HOLD_DEADLINE),
            HoldVerdict::Compile,
            "at the deadline the files are compiled as they are"
        );
        assert_eq!(
            hold.deadline(),
            None,
            "the rebuild at the deadline ends the hold"
        );
    }

    /// An endless stream of rebuilds that each find the file still emptied — a truncation
    /// every 2ms, every 100ms, every 999ms — compiles at the first rebuild at or past the
    /// deadline the stream's first rebuild set: no stream moves it.
    #[test]
    fn empty_hold_compiles_an_endless_stream_at_its_first_deadline() {
        for (every, compiled_at) in [
            (ms(2), ms(1_000)),
            (ms(100), ms(1_000)),
            (ms(999), ms(1_998)),
        ] {
            let t0 = Instant::now();
            let mut hold = EmptyHold::default();
            // Endless, bounded only by the first compile (and a step cap).
            let compiled = (0u32..)
                .take(10_000)
                .map(|k| t0 + every * k)
                .find(|&now| hold.on_rebuild(true, now) == HoldVerdict::Compile);
            assert_eq!(
                compiled.map(|at| at - t0),
                Some(compiled_at),
                "a stream of rebuilds every {every:?} must compile at its first deadline"
            );
        }
    }

    /// A rebuild that finds no watched file emptied — the content written — compiles at once
    /// and ends the hold; a later truncation then sets a deadline of its own.
    #[test]
    fn empty_hold_ends_when_no_watched_file_is_emptied() {
        let t0 = Instant::now();
        let mut hold = EmptyHold::default();
        assert_eq!(
            hold.on_rebuild(false, t0),
            HoldVerdict::Compile,
            "nothing emptied, nothing held"
        );
        assert_eq!(hold.deadline(), None);
        assert_eq!(hold.on_rebuild(true, t0 + ms(10)), HoldVerdict::Hold);
        assert_eq!(
            hold.on_rebuild(false, t0 + ms(500)),
            HoldVerdict::Compile,
            "written: compiled at once, not at the deadline"
        );
        assert_eq!(hold.deadline(), None, "the write ends the hold");
        assert_eq!(hold.on_rebuild(true, t0 + ms(600)), HoldVerdict::Hold);
        assert_eq!(
            hold.deadline(),
            Some(t0 + ms(600) + EMPTY_HOLD_DEADLINE),
            "a new truncation sets its own deadline"
        );
    }

    /// What woke the loop in a [`wakes_under_saturation`] replay.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum Woke {
        Hold,
        Tick,
    }

    /// Replays [`TickClock::recv_next`] with a rebuild held until `hold` (an offset) on a
    /// channel that is never empty: every poll with nothing due takes a message, and
    /// handling one moves the clock on by `per_message`. The held rebuild ends its hold
    /// when it runs, as a session's `on_hold_due` does. Returns each wake before `until`,
    /// as offsets.
    fn wakes_under_saturation(
        interval: Option<Duration>,
        hold: Duration,
        per_message: Duration,
        until: Duration,
    ) -> Vec<(Duration, Woke)> {
        let t0 = Instant::now();
        let mut schedule = TickSchedule::start(interval, t0);
        let mut held = Some(t0 + hold);
        let mut now = t0;
        let mut wakes = Vec::new();
        // Bounded: one step per message or wake.
        for _ in 0..10_000 {
            if now >= t0 + until {
                return wakes;
            }
            match poll_wake(&mut schedule, held, now) {
                WakePoll::HoldDue => {
                    wakes.push((now - t0, Woke::Hold));
                    held = None;
                }
                WakePoll::TickDue => wakes.push((now - t0, Woke::Tick)),
                WakePoll::Wait { .. } | WakePoll::Never => now += per_message,
            }
        }
        panic!("the replay did not reach {until:?} within 10 000 steps; wakes so far: {wakes:?}");
    }

    /// A held rebuild's deadline is served before the next message and before a tick due at
    /// the same instant, the tick right after it; a channel that is never empty postpones
    /// neither — under `--poll-interval 0` as well, where only the hold's own deadline can
    /// wake the loop.
    #[test]
    fn wake_schedule_serves_a_held_rebuild_first_under_saturation() {
        use Woke::{Hold, Tick};
        assert_eq!(
            wakes_under_saturation(Some(ms(50)), ms(120), ms(5), ms(210)),
            [
                (ms(50), Tick),
                (ms(100), Tick),
                (ms(120), Hold),
                (ms(150), Tick),
                (ms(200), Tick)
            ],
            "a saturated channel must postpone neither the tick nor the held rebuild"
        );
        assert_eq!(
            wakes_under_saturation(Some(ms(50)), ms(100), ms(5), ms(160)),
            [
                (ms(50), Tick),
                (ms(100), Hold),
                (ms(100), Tick),
                (ms(150), Tick)
            ],
            "a held rebuild due with a tick runs first, the tick straight after it"
        );
        assert_eq!(
            wakes_under_saturation(None, ms(1_000), ms(7), ms(2_000)),
            [(ms(1_001), Hold)],
            "with no tick the held rebuild still runs at the first poll at or after its \
             deadline"
        );
    }

    /// With no message waiting the loop waits for whichever deadline comes first — the held
    /// rebuild's even under `--poll-interval 0`, where nothing else would wake it — and
    /// blocks with no deadline only when no rebuild is held and no tick runs.
    #[test]
    fn wake_schedule_waits_for_the_earlier_deadline() {
        let t0 = Instant::now();
        let held = Some(t0 + ms(1_000));
        let mut off = TickSchedule::start(None, t0);
        assert_eq!(
            poll_wake(&mut off, held, t0),
            WakePoll::Wait {
                wait: ms(1_000),
                hold: true
            },
            "--poll-interval 0 must still wait for the held rebuild"
        );
        assert_eq!(
            poll_wake(&mut off, held, t0 + ms(999)),
            WakePoll::Wait {
                wait: ms(1),
                hold: true
            }
        );
        assert_eq!(poll_wake(&mut off, held, t0 + ms(1_000)), WakePoll::HoldDue);
        assert_eq!(
            poll_wake(&mut off, None, t0 + ms(1_000)),
            WakePoll::Never,
            "positive control: nothing held and no tick — a message, however long it takes"
        );

        let mut every = TickSchedule::start(Some(ms(50)), t0);
        assert_eq!(
            poll_wake(&mut every, Some(t0 + ms(30)), t0),
            WakePoll::Wait {
                wait: ms(30),
                hold: true
            },
            "the held rebuild's deadline comes first"
        );
        assert_eq!(
            poll_wake(&mut every, Some(t0 + ms(80)), t0),
            WakePoll::Wait {
                wait: ms(50),
                hold: false
            },
            "the tick comes first"
        );
        assert_eq!(
            poll_wake(&mut every, Some(t0 + ms(50)), t0),
            WakePoll::Wait {
                wait: ms(50),
                hold: true
            },
            "a tie waits for the held rebuild, which is served first"
        );
        assert_eq!(
            poll_wake(&mut every, None, t0),
            WakePoll::Wait {
                wait: ms(50),
                hold: false
            }
        );
    }

    /// A directory-mode hold keeps every batch it holds back, and the batch that ends it
    /// rebuilds them all with its own — a vars-file change among them makes it a full
    /// rebuild — leaving nothing held. Of the paths held, the sources below the root are kept
    /// as such, the ones the look stamps (#380); a path outside it that no source imports is
    /// rebuilt all the same, but is none.
    #[test]
    fn held_batches_are_rebuilt_with_the_batch_that_ends_the_hold() {
        let paths =
            |names: &[&str]| -> BTreeSet<PathBuf> { names.iter().map(PathBuf::from).collect() };
        let root = Path::new("/w");
        let batch = |names: &[&str], vars_changed: bool| Batch {
            paths: paths(names),
            vars_changed,
        };
        let mut held = HeldBatch::default();
        held.hold(&batch(&["/w/b.mds", "/x/unread.mds"], false), root);
        held.hold(&batch(&["/w/a.mds", "/w/b.mds"], true), root);
        assert_eq!(held.sources, paths(&["/w/a.mds", "/w/b.mds"]));
        assert_eq!(
            held.release(batch(&["/w/a.mds", "/w/c.mds"], false)),
            batch(&["/w/a.mds", "/w/b.mds", "/w/c.mds", "/x/unread.mds"], true)
        );
        assert_eq!(held, HeldBatch::default(), "nothing stays held");
        assert_eq!(
            held.release(batch(&["/w/c.mds"], false)),
            batch(&["/w/c.mds"], false),
            "positive control: with nothing held, a batch is its own"
        );
    }

    /// A file a held compile read empty — a dependency outside the root that the source
    /// imports for the first time, no source and no dependency the session tracks — is in
    /// the baseline's domain while the source is held, so the look of a batch that names it
    /// stamps it; the batch that ends the hold rebuilds the source, and the file leaves the
    /// domain with the hold (#380).
    #[test]
    fn a_file_a_held_compile_read_empty_is_in_the_baseline_until_the_hold_ends() {
        let (_root_dir, root) = canonical_tempdir();
        let mut state = empty_dir_state();
        let page = root.join("page.mds");
        let dependency = PathBuf::from("/outside/_y.mds");
        let in_domain = |state: &DirWatchState| state.baselined_paths().any(|p| *p == dependency);
        assert!(
            !in_domain(&state),
            "control: the session tracks no such file"
        );

        state
            .held
            .hold_read_empty(&page, BTreeSet::from([dependency.clone()]), &root);
        assert!(
            state.held.paths.contains(&page) && state.held.sources.contains(&page),
            "the source is held; {:?}",
            state.held
        );
        assert!(in_domain(&state), "the file is in the baseline's domain");

        assert_eq!(
            state.held.release(Batch {
                paths: BTreeSet::new(),
                vars_changed: false
            }),
            Batch {
                paths: BTreeSet::from([page]),
                vars_changed: false
            },
            "the batch that ends the hold rebuilds the source"
        );
        assert!(
            !in_domain(&state),
            "the file leaves the domain with the hold"
        );
        assert_eq!(state.held, HeldBatch::default(), "nothing stays held");
    }

    /// An output the session wrote with bytes, written with none, is emptied; nothing else
    /// is.
    #[test]
    fn empties_output_is_an_output_with_bytes_written_with_none() {
        assert!(empties_output(Some("Page\n"), ""), "bytes, then none");
        assert!(!empties_output(Some(""), ""), "an output already empty");
        assert!(
            !empties_output(None, ""),
            "an output the session never wrote there"
        );
        assert!(
            !empties_output(Some("Page\n"), "Other\n"),
            "an output still with bytes"
        );
    }

    // ── Debounce window domain (#379) ────────────────────────────────────────

    /// A minimal content event on `path`, shaped like the ones notify delivers.
    fn content_event(path: &str) -> notify::Event {
        notify::Event {
            kind: notify::EventKind::Modify(notify::event::ModifyKind::Any),
            paths: vec![PathBuf::from(path)],
            attrs: Default::default(),
        }
    }

    /// A read event — the kind `is_content_event` drops.
    fn read_event(path: &str) -> notify::Event {
        notify::Event {
            kind: notify::EventKind::Access(notify::event::AccessKind::Read),
            paths: vec![PathBuf::from(path)],
            attrs: Default::default(),
        }
    }

    /// A content event on `path` as the watch channel carries it.
    fn modify_event(path: &str) -> Msg {
        Msg::Fs(Ok(content_event(path)))
    }

    /// Upper bound on the steps of one [`replay`]: the message limit, twice over.
    const REPLAY_STEPS: usize = 2 * MAX_DEBOUNCE_MESSAGES;

    /// How [`drain_debounce`] drives a window, replayed on synthetic instants.
    ///
    /// `events` arrive at their instants, in order. One that arrives before the
    /// window's deadline is drained at its own instant (at once if it was already
    /// queued); otherwise the wait for it runs out at the deadline. Returns the instant
    /// the window closed at, why, and the window as it closed. `events` may be endless:
    /// only as many are taken as the window drains.
    fn replay(
        window: Duration,
        start: Instant,
        events: impl IntoIterator<Item = (Instant, notify::Event)>,
    ) -> (Instant, WindowEnd, DebounceWindow) {
        let mut open = DebounceWindow::open(window, start);
        let mut events = events.into_iter().peekable();
        let mut now = start;
        // Bounded: one step per drained event or ran-out wait.
        for _ in 0..REPLAY_STEPS {
            if let Some(end) = open.classify(now) {
                return (now, end, open);
            }
            let deadline = open.deadline();
            match events.next_if(|(at, _)| *at < deadline) {
                Some((at, event)) => {
                    now = now.max(at);
                    open.on_event(event, now);
                }
                None => now = deadline,
            }
        }
        panic!("the window was still open after {REPLAY_STEPS} steps");
    }

    /// An event that says events were lost, drained inside a window, reaches the window's
    /// result: the flag is not dropped with the paths the event does not have (#257).
    #[test]
    fn a_debounce_window_keeps_that_an_event_said_events_were_lost() {
        let t0 = Instant::now();
        let rescan =
            notify::Event::new(notify::EventKind::Other).set_flag(notify::event::Flag::Rescan);
        let (_, _, closed) = replay(ms(100), t0, [(t0 + ms(10), rescan)]);
        assert!(closed.rescan, "the window says events were lost");

        let (_, _, closed) = replay(ms(100), t0, [(t0 + ms(10), content_event("/w/a.mds"))]);
        assert!(
            !closed.rescan,
            "control: a window of ordinary events does not"
        );
    }

    /// Every content event restarts the window: a burst longer than the window
    /// coalesces into ONE result, which closes one window after the burst's last event.
    ///
    /// A window that expired at a fixed offset from the FIRST event splits any burst
    /// longer than `debounce_ms`; each piece rebuilds separately, against a different
    /// intermediate state of the file.
    #[test]
    fn debounce_window_quiet_end_is_one_window_after_the_last_content_event() {
        let t0 = Instant::now();
        let (closed_at, end, _) = replay(ms(100), t0, std::iter::empty());
        assert_eq!(
            (closed_at, end),
            (t0 + ms(100), WindowEnd::Quiet),
            "with no further event the window closes one window after it opened"
        );

        // 40 events, 5ms apart: a 195ms burst under a 100ms window.
        let burst = (0..40u32).map(|i| (t0 + ms(5) * i, content_event(&format!("/w/f{i}.mds"))));
        let (closed_at, end, closed) = replay(ms(100), t0, burst);
        assert_eq!(
            end,
            WindowEnd::Quiet,
            "a 195ms burst under a 100ms window must end quiet, not capped"
        );
        assert_eq!(
            closed_at,
            t0 + ms(295),
            "the window closes one window after the burst's last event (195ms)"
        );
        assert_eq!(
            closed.classify(t0 + ms(294)),
            None,
            "one millisecond earlier the window is still open"
        );
        assert_eq!(
            closed.paths.len(),
            40,
            "every path in the burst must be collected into the one window; got {:?}",
            closed.paths
        );
    }

    /// The cap ends a stream that never goes quiet, exactly `debounce_cap(window)`
    /// after the window opened.
    ///
    /// Without it an extendable window is unbounded: a file written to continuously
    /// postpones its own rebuild — and the idle-tick backstop behind it — for as long
    /// as the writing lasts.
    #[test]
    fn debounce_window_cap_ends_an_endless_stream_exactly_at_start_plus_cap() {
        // (window, one content event every .., cap): every gap is shorter than the
        // window, so the window never goes quiet; the stream never ends.
        let streams = [
            (ms(50), ms(2), ms(1_000)),
            (ms(10), ms(9), ms(1_000)),
            (ms(250), ms(100), ms(2_500)),
            (ms(1_000), ms(999), ms(10_000)),
        ];
        for (window, every, cap) in streams {
            let t0 = Instant::now();
            let endless = (1u32..).map(|i| (t0 + every * i, content_event("/w/hot.mds")));
            let (closed_at, end, closed) = replay(window, t0, endless);
            assert_eq!(
                end,
                WindowEnd::Cap,
                "a {window:?} window under an event every {every:?} must end at the cap"
            );
            assert_eq!(
                closed_at,
                t0 + cap,
                "a {window:?} window must close exactly at its cap, max(10 x window, 1s)"
            );
            assert_eq!(closed.paths.len(), 1, "every event names the same path");
        }
    }

    /// `--debounce 0` opens no window and consumes nothing.
    #[test]
    fn debounce_zero_is_disabled_and_leaves_the_channel_untouched() {
        let (tx, rx) = mpsc::channel::<Msg>();
        tx.send(modify_event("/w/a.mds")).expect("send failed");

        let outcome = drain_debounce(&rx, 0);

        assert_eq!(outcome.end, DebounceEnd::Disabled);
        assert!(
            outcome.paths.is_empty(),
            "a disabled window must collect nothing"
        );
        assert!(
            matches!(rx.try_recv(), Ok(Msg::Fs(Ok(_)))),
            "the queued event must still be in the channel: with coalescing off the \
             loop delivers it as its own batch"
        );
    }

    /// Ctrl+C ends the window when it is drained, however long the window had left:
    /// a 5s window that waited itself out would end `Quiet`, not `Interrupted`.
    #[test]
    fn debounce_interrupt_returns_immediately() {
        let (tx, rx) = mpsc::channel::<Msg>();
        tx.send(modify_event("/w/a.mds")).expect("send failed");
        tx.send(Msg::Interrupt).expect("send failed");

        let outcome = drain_debounce(&rx, 5_000);
        drop(tx);

        assert_eq!(outcome.end, DebounceEnd::Interrupted);
        assert!(
            outcome.interrupted(),
            "interrupted() must agree with the end reason"
        );
        assert_eq!(
            outcome.paths.len(),
            1,
            "positive control: the window was open and draining when Ctrl+C arrived"
        );
    }

    /// Reads do not extend the window.
    ///
    /// The compile reads its own sources, so an extending `Access` event would let the
    /// watcher hold its own window open.
    #[test]
    fn debounce_window_reads_count_but_neither_extend_nor_collect() {
        let t0 = Instant::now();
        // One content event, then 300ms of reads, one every 5ms.
        let reads = std::iter::once((t0, content_event("/w/a.mds")))
            .chain((1..=60u32).map(|i| (t0 + ms(5) * i, read_event("/w/a.mds"))));
        let (closed_at, end, closed) = replay(ms(100), t0, reads);
        assert_eq!(
            (closed_at, end),
            (t0 + ms(100), WindowEnd::Quiet),
            "300ms of reads must not extend a 100ms window"
        );
        assert_eq!(
            closed.paths.len(),
            1,
            "only the one content event contributes a path; got {:?}",
            closed.paths
        );
        assert_eq!(
            closed.messages, 20,
            "the content event and the 19 reads drained before the deadline all count"
        );

        // Positive control: content events at the same instants do extend.
        let writes = (0..=60u32).map(|i| (t0 + ms(5) * i, content_event(&format!("/w/f{i}.mds"))));
        let (closed_at, end, closed) = replay(ms(100), t0, writes);
        assert_eq!((closed_at, end), (t0 + ms(400), WindowEnd::Quiet));
        assert_eq!(closed.paths.len(), 61);
    }

    /// One window drains a bounded number of messages, of every kind.
    ///
    /// The cap bounds the window's duration; this bounds its work and its memory. A
    /// sender faster than the drain would otherwise grow `paths` without limit inside
    /// a single window.
    #[test]
    fn debounce_window_closes_at_the_message_limit() {
        let t0 = Instant::now();
        let mut open = DebounceWindow::open(ms(100), t0);
        for _ in 2..MAX_DEBOUNCE_MESSAGES {
            open.on_event(content_event("/w/same.mds"), t0);
        }
        open.on_event(read_event("/w/same.mds"), t0);
        assert_eq!(
            open.classify(t0),
            None,
            "one message short of the limit, the window is still open"
        );
        open.on_watch_error();
        assert_eq!(
            open.classify(t0),
            Some(WindowEnd::MessageLimit),
            "contents, reads and watch errors all count toward the limit"
        );

        // 12 000 events already queued when the window opens.
        let queued = (0..12_000u32).map(|_| (t0, content_event("/w/same.mds")));
        let (closed_at, end, closed) = replay(ms(100), t0, queued);
        assert_eq!(
            (closed_at, end),
            (t0, WindowEnd::MessageLimit),
            "12 000 queued events must hit the message bound, not the quiet period"
        );
        assert_eq!(closed.messages, MAX_DEBOUNCE_MESSAGES);
        assert_eq!(
            closed.paths.len(),
            1,
            "all 12 000 events name the same path; got {:?}",
            closed.paths
        );
    }

    /// The driver stops at the message limit: it asks the window after every message,
    /// so a flood queued faster than the window can close ends the window at the limit,
    /// and the rest of the flood stays queued for the next one.
    ///
    /// No timing: the 60s window and its 600s cap cannot close during the test, and the
    /// sender is dropped before the drain, so a driver that did not stop at the limit
    /// would drain the whole flood and end `Disconnected` rather than wait the window
    /// out. A read and a watch error sit inside the first 10 000 messages: exactly 2 000
    /// stay queued only if the driver counts both of them.
    #[test]
    fn debounce_driver_stops_at_the_message_limit_with_the_rest_still_queued() {
        let (tx, rx) = mpsc::channel::<Msg>();
        for _ in 2..MAX_DEBOUNCE_MESSAGES {
            tx.send(modify_event("/w/same.mds")).expect("send failed");
        }
        tx.send(Msg::Fs(Ok(read_event("/w/read.mds"))))
            .expect("send failed");
        let watch_error = notify::Error::generic("a planted watch error");
        tx.send(Msg::Fs(Err(watch_error))).expect("send failed");
        for _ in 0..2_000 {
            tx.send(modify_event("/w/later.mds")).expect("send failed");
        }
        drop(tx);

        let outcome = drain_debounce(&rx, 60_000);

        assert_eq!(
            outcome.end,
            DebounceEnd::Closed(WindowEnd::MessageLimit),
            "{} queued messages must end the window at the message limit",
            MAX_DEBOUNCE_MESSAGES + 2_000
        );
        assert_eq!(
            outcome.paths,
            BTreeSet::from([PathBuf::from("/w/same.mds")]),
            "only the content events drained before the limit contribute a path"
        );
        let left: Vec<Msg> = rx.try_iter().collect();
        assert_eq!(
            left.len(),
            2_000,
            "the content events, the read and the watch error all count toward the \
             limit, and every message after it stays queued"
        );
        assert!(
            left.iter().all(|msg| matches!(
                msg,
                Msg::Fs(Ok(event)) if event.paths == [PathBuf::from("/w/later.mds")]
            )),
            "positive control: the messages still queued are the flood after the limit"
        );
    }

    /// A dropped sender ends the window at once rather than waiting it out.
    ///
    /// The sender lives as long as the watcher, so a disconnect means the watcher is
    /// gone. Sitting out the remaining window there would delay shutdown by up to the
    /// cap for no possible gain: no further event can ever arrive.
    #[test]
    fn debounce_disconnected_ends_the_window_immediately() {
        let (tx, rx) = mpsc::channel::<Msg>();
        // One event already queued, so the drain has something to collect before it
        // reaches the disconnect — the exit must not discard it.
        tx.send(modify_event("/w/a.mds")).expect("send failed");
        drop(tx);

        let outcome = drain_debounce(&rx, 5_000);

        assert_eq!(
            outcome.end,
            DebounceEnd::Disconnected,
            "a 5s window that waited itself out would end Quiet, not Disconnected"
        );
        assert_eq!(
            outcome.paths.len(),
            1,
            "messages queued before the disconnect must still be collected; got {:?}",
            outcome.paths
        );
    }

    /// The one real-clock test: both drivers read `Instant::now()` and wait on a real
    /// channel. Lower bounds only — a slow runner can make a wait longer, never shorter
    /// — and the synthetic tests above pin every exact instant. Each driver call runs
    /// under [`within_5s`], and the sender stays alive throughout, so a driver that lost
    /// its bound fails here instead of hanging.
    #[test]
    fn debounce_and_tick_drivers_run_on_the_real_clock() {
        let (tx, rx) = mpsc::channel::<Msg>();
        tx.send(modify_event("/w/a.mds")).expect("send failed");

        let t0 = Instant::now();
        let (outcome, rx) = within_5s("drain_debounce", move || (drain_debounce(&rx, 20), rx));
        assert!(
            t0.elapsed() >= ms(20),
            "a 20ms window must wait at least 20ms; got {:?}",
            t0.elapsed()
        );
        // Quiet unless the runner stalled for the better part of the 1s cap between
        // opening the window and draining the event.
        assert!(
            matches!(
                outcome.end,
                DebounceEnd::Closed(WindowEnd::Quiet | WindowEnd::Cap)
            ),
            "the window must close on its own; got {:?}",
            outcome.end
        );
        assert_eq!(outcome.paths.len(), 1, "the queued event is drained");

        let t1 = Instant::now();
        let (wake, rx) = within_5s("an idle tick", move || {
            (TickClock::new(Some(ms(50))).recv_next(&rx, None), rx)
        });
        assert!(
            matches!(wake, Ok(Wake::Tick)),
            "an idle channel must produce a tick"
        );
        assert!(
            t1.elapsed() >= ms(50),
            "the tick must not come due before its interval; got {:?}",
            t1.elapsed()
        );

        // `--poll-interval 0`: no tick, yet a held rebuild's deadline still wakes the loop
        // (#380) — and not before it. A driver that blocked for a message instead fails
        // here by name.
        let t2 = Instant::now();
        let (wake, _rx) = within_5s("a held rebuild's deadline", move || {
            (TickClock::new(None).recv_next(&rx, Some(t2 + ms(30))), rx)
        });
        assert!(
            matches!(wake, Ok(Wake::HoldDue)),
            "a held rebuild's deadline must wake an idle loop with no tick"
        );
        assert!(
            t2.elapsed() >= ms(30),
            "the held rebuild must not run before its deadline; got {:?}",
            t2.elapsed()
        );
        drop(tx);
    }

    /// The clamp contract, verifiable without the watch loop.
    #[test]
    fn clamp_debounce_contract() {
        assert_eq!(
            clamp_debounce(0),
            None,
            "0 disables coalescing; it does not mean a 0ms window"
        );
        assert_eq!(clamp_debounce(100), Some(Duration::from_millis(100)));
        assert_eq!(
            clamp_debounce(u64::MAX),
            Some(Duration::from_secs(60)),
            "an unclamped u64::MAX window does not overflow on a monotonic clock — it \
             lands ~585 million years out, so the watcher silently never rebuilds"
        );
    }

    /// The cap contract: `max(10 x window, 1s)`.
    #[test]
    fn debounce_cap_contract() {
        assert_eq!(
            debounce_cap(Duration::from_millis(10)),
            Duration::from_secs(1),
            "the floor binds for small windows"
        );
        assert_eq!(
            debounce_cap(Duration::from_millis(250)),
            Duration::from_millis(2_500)
        );
        assert_eq!(
            debounce_cap(Duration::from_millis(1_000)),
            Duration::from_secs(10)
        );
    }

    // ── Content backstop domain (#321) ───────────────────────────────────────

    /// `tracked_set` covers cross-root dependencies, which `known_files` never can.
    ///
    /// `known_files` holds exactly what `collect_mds_files(root)` returns, so a
    /// dependency outside the root is absent from it by construction. Baselining only
    /// that set is what left `last_mtimes` write-only in directory mode.
    #[test]
    fn tracked_set_includes_cross_root_dependencies() {
        let root = PathBuf::from("/w/root");
        let importer = root.join("importer.mds");
        let external = PathBuf::from("/w/shared/_x.mds");

        let mut state = DirWatchState {
            forward_deps: HashMap::new(),
            errored: HashSet::new(),
            known_files: BTreeSet::new(),
            last_written: HashMap::new(),
            outputs: HashMap::new(),
            kept: HashMap::new(),
            out_dir: None,
            reads: Vec::new(),
            external_dep_dirs: BTreeSet::new(),
            vars_file: None,
            last_mtimes: HashMap::new(),
            hold: EmptyHold::Off,
            held: HeldBatch::default(),
        };
        state.known_files.insert(importer.clone());
        state
            .forward_deps
            .insert(importer.clone(), vec![external.clone()]);

        let tracked = state.tracked_set();
        assert!(
            tracked.contains(&importer),
            "in-root source must be tracked"
        );
        assert!(
            tracked.contains(&external),
            "a cross-root dependency must be tracked; it is exactly the path no \
             collect_mds_files(root) walk can report"
        );
    }

    /// A failed compile keeps the dep set the last successful one recorded (#321).
    ///
    /// Clearing it dropped the external directory the deps lived in, after which every
    /// further event for that directory was filtered out as unknown — one compile
    /// against a half-written file blinded the watcher for the session.
    #[test]
    fn record_error_preserves_last_known_deps() {
        let root = PathBuf::from("/w/root");
        let importer = root.join("importer.mds");
        let external = PathBuf::from("/w/shared/_x.mds");

        let mut state = DirWatchState {
            forward_deps: HashMap::new(),
            errored: HashSet::new(),
            known_files: BTreeSet::new(),
            last_written: HashMap::new(),
            outputs: HashMap::new(),
            kept: HashMap::new(),
            out_dir: None,
            reads: Vec::new(),
            external_dep_dirs: BTreeSet::new(),
            vars_file: None,
            last_mtimes: HashMap::new(),
            hold: EmptyHold::Off,
            held: HeldBatch::default(),
        };
        state.record_success(&importer, vec![external.clone()], &root, None, None);
        assert!(state.external_dep_dirs.contains(Path::new("/w/shared")));

        state.record_error(&importer);

        assert!(state.errored.contains(&importer), "error must be recorded");
        assert_eq!(
            state.forward_deps.get(&importer),
            Some(&vec![external.clone()]),
            "a failed compile must keep the last known dep set, or the external dep \
             dir is pruned and its events are filtered out from then on"
        );
        assert!(
            state.tracked_set().contains(&external),
            "the backstop must still cover a dependency whose importer is broken — \
             that is precisely when it needs to notice the dependency being fixed"
        );
    }

    /// #217: pruning a ghost EXTERNAL dep must not forget an in-root source's output.
    ///
    /// A dependency outside the watched root never had an output of its own, so there is
    /// none to forget. A probe for one from its path took the out-of-root flatten arm and
    /// yielded `<out-dir>/<file name>`, which is exactly the path an IN-ROOT source with
    /// the same file name owns. The prune then dropped that source's `last_written` entry
    /// and its next rebuild rewrote identical bytes.
    ///
    /// Reachable: an importer whose cross-root `@import` target is deleted leaves the
    /// vanished dep in `errored`, and every later real-change batch re-seeds `errored`.
    #[test]
    fn ghost_external_dep_prune_keeps_in_root_last_written() {
        let root_dir = tempfile::tempdir().unwrap();
        let out_dir = tempfile::tempdir().unwrap();
        let shared_dir = tempfile::tempdir().unwrap();
        let root = root_dir.path().to_path_buf();
        let out = out_dir.path().to_path_buf();

        // The in-root source that carries the batch's real change.
        let other = root.join("other.mds");
        std::fs::write(&other, "Hello.\n").unwrap();

        // The in-root source whose bookkeeping is at risk. It is not in this batch, so
        // nothing recompiles it — only its `last_written` entry can change.
        let victim = root.join("x.mds");
        std::fs::write(&victim, "Victim.\n").unwrap();
        let victim_out = out.join("x.md");

        // A cross-root dependency with the same file name that no longer exists.
        let ghost = shared_dir.path().join("x.mds");
        assert!(!ghost.exists(), "the ghost dep must not exist on disk");

        let mut state = DirWatchState {
            forward_deps: HashMap::new(),
            errored: HashSet::new(),
            known_files: BTreeSet::new(),
            last_written: HashMap::new(),
            outputs: HashMap::new(),
            kept: HashMap::new(),
            out_dir: None,
            reads: Vec::new(),
            external_dep_dirs: BTreeSet::new(),
            vars_file: None,
            last_mtimes: HashMap::new(),
            hold: EmptyHold::Off,
            held: HeldBatch::default(),
        };
        state.known_files.insert(victim.clone());
        state.last_written.insert(
            victim_out.clone(),
            WrittenOutput {
                source: victim.clone(),
                content: "Victim.\n".to_string(),
            },
        );
        state.errored.insert(ghost.clone());
        state
            .external_dep_dirs
            .insert(shared_dir.path().to_path_buf());

        let changed: BTreeSet<PathBuf> = std::iter::once(other).collect();
        process_dir_batch_incremental(
            &changed,
            &mut BatchCtx {
                watch_root: &WatchedPath {
                    typed: root.clone(),
                    canonical: root,
                    what: Watched::Root,
                },
                output_base: &dir_base(out.clone()),
                vars: BatchVars::map_only(&None),
                quiet: true,
            },
            &mut state,
        );

        assert!(
            !state.errored.contains(&ghost),
            "control: the ghost prune must actually have run — without it the assertion \
             below would pass on a batch that never reached the branch"
        );
        assert!(
            state.last_written.contains_key(&victim_out),
            "#217: forgetting a ghost external dep must not drop an in-root source's \
             last_written entry; keys: {:?}",
            state.last_written.keys().collect::<Vec<_>>()
        );
    }

    /// #380: a batch whose `--vars` file changed recompiles every known source, and also
    /// compiles the sources it names that no walk has found — one created in the same
    /// batch, or held with it — which are then known, and in the baseline. A path the
    /// batch names that is no source below the root is not compiled as one.
    #[test]
    fn a_vars_changed_batch_compiles_the_sources_created_in_it() {
        let root_dir = tempfile::tempdir().unwrap();
        let out_dir = tempfile::tempdir().unwrap();
        let elsewhere = tempfile::tempdir().unwrap();
        // Canonical, as every path a batch carries is (macOS tempdirs are below a symlink).
        let canonical = |dir: &tempfile::TempDir| std::fs::canonicalize(dir.path()).unwrap();
        let (root, out) = (canonical(&root_dir), canonical(&out_dir));
        let known = root.join("known.mds");
        let created = root.join("created.mds");
        // An in-root MDS module a source could import: it compiles, but is no source.
        let not_a_source = root.join("notes.md");
        let excluded = root.join("node_modules").join("dep.mds");
        let outside = canonical(&elsewhere).join("outside.mds");
        std::fs::create_dir(root.join("node_modules")).unwrap();
        for (path, text) in [
            (&known, "Known.\n"),
            (&created, "Created.\n"),
            (&not_a_source, "---\ntype: mds\nname: notes\n---\nNotes.\n"),
            (&excluded, "Excluded.\n"),
            (&outside, "Outside.\n"),
        ] {
            std::fs::write(path, text).unwrap();
        }
        let mut state = empty_dir_state();
        state.known_files.insert(known.clone());

        let changed: BTreeSet<PathBuf> = [&created, &not_a_source, &excluded, &outside]
            .into_iter()
            .cloned()
            .collect();
        process_dir_batch(
            &changed,
            true,
            &mut BatchCtx {
                watch_root: &WatchedPath {
                    typed: root.clone(),
                    canonical: root.clone(),
                    what: Watched::Root,
                },
                output_base: &dir_base(out.clone()),
                vars: BatchVars::map_only(&None),
                quiet: true,
            },
            &mut state,
        );

        let read = |rel: &Path| std::fs::read_to_string(out.join(rel)).ok();
        assert!(
            read(Path::new("known.md")).is_some_and(|text| text.contains("Known.")),
            "positive control: a known source is recompiled; out/known.md: {:?}",
            read(Path::new("known.md"))
        );
        assert!(
            read(Path::new("created.md")).is_some_and(|text| text.contains("Created.")),
            "a source created in the batch is compiled with it; out/created.md: {:?}",
            read(Path::new("created.md"))
        );
        assert!(
            state.known_files.contains(&created) && state.last_mtimes.contains_key(&created),
            "and is known and in the baseline, so a later edit or the idle tick finds it; \
             known: {:?}",
            state.known_files
        );
        // Where each would be written had it been compiled as a source.
        for rel in [
            PathBuf::from("notes.md"),
            Path::new("node_modules").join("dep.md"),
            PathBuf::from("outside.md"),
        ] {
            assert_eq!(
                read(&rel),
                None,
                "{}: a path that is no source below the root is not compiled as one",
                rel.display()
            );
        }
        for path in [&not_a_source, &excluded, &outside] {
            assert!(
                !state.known_files.contains(path) && !state.errored.contains(path),
                "{}: neither known nor errored; known: {:?}, errored: {:?}",
                path.display(),
                state.known_files,
                state.errored
            );
        }
    }

    /// #265: a source under the root is compiled by the root as typed plus its path
    /// below the canonical root; an out-of-root dependency keeps its canonical path.
    #[test]
    fn watch_root_walked_keeps_the_typed_prefix() {
        let root = WatchedPath {
            typed: PathBuf::from("src"),
            canonical: PathBuf::from("/abs/project/src"),
            what: Watched::Root,
        };
        assert_eq!(
            root.walked(Path::new("/abs/project/src/sub/a.mds")),
            Path::new("src").join("sub").join("a.mds")
        );
        assert_eq!(
            root.walked(Path::new("/abs/shared/b.mds")),
            Path::new("/abs/shared/b.mds"),
            "an out-of-root dependency has no walked form"
        );
    }

    /// A source that has never compiled successfully gets an empty dep set, not a panic.
    #[test]
    fn record_error_on_unknown_source_inserts_empty_deps() {
        let mut state = DirWatchState {
            forward_deps: HashMap::new(),
            errored: HashSet::new(),
            known_files: BTreeSet::new(),
            last_written: HashMap::new(),
            outputs: HashMap::new(),
            kept: HashMap::new(),
            out_dir: None,
            reads: Vec::new(),
            external_dep_dirs: BTreeSet::new(),
            vars_file: None,
            last_mtimes: HashMap::new(),
            hold: EmptyHold::Off,
            held: HeldBatch::default(),
        };
        let src = PathBuf::from("/w/root/broken.mds");
        state.record_error(&src);
        assert_eq!(state.forward_deps.get(&src), Some(&vec![]));
    }

    /// `baseline_path` keeps the older entry — the merge direction the backstop needs.
    #[test]
    fn baseline_path_keeps_existing_entry() {
        let dir = tempfile::tempdir().unwrap();
        let f = dir.path().join("a.mds");
        std::fs::write(&f, "one").unwrap();

        let mut snap = HashMap::new();
        baseline_path(&f, &mut snap);
        let first = snap.get(&f).copied();

        std::fs::write(&f, "a much longer second revision").unwrap();
        baseline_path(&f, &mut snap);

        assert_eq!(
            snap.get(&f).copied(),
            first,
            "baseline_path must not overwrite an existing entry: only the older pair \
             predates the read whose output was published"
        );
        assert!(
            path_state_differs(&f, &snap),
            "the retained older baseline must therefore report the file as changed"
        );
    }

    /// A path absent from the baseline counts as changed.
    #[test]
    fn path_state_differs_reports_unknown_path() {
        let dir = tempfile::tempdir().unwrap();
        let f = dir.path().join("a.mds");
        std::fs::write(&f, "one").unwrap();
        let snap = HashMap::new();
        assert!(
            path_state_differs(&f, &snap),
            "a path the baseline has never seen cannot be claimed as accounted for"
        );
    }

    // T-U5 (renamed): output_path_for does NOT create directories.
    #[test]
    fn output_path_for_no_create() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().to_path_buf();
        let new_subdir = dir.path().join("new_out");
        assert!(!new_subdir.exists(), "precondition: subdir does not exist");

        let source = root.join("template.mds");
        let base = dir_base(new_subdir.clone());
        let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "md");
        assert_eq!(result.path, new_subdir.join("template.md"));
        assert!(
            !new_subdir.exists(),
            "output_path_for must not create directories"
        );
    }

    // T-U6: compile_and_write returns deps for an importing template.
    //
    // Uses @define/@export/@import/@include pattern to create a verifiable
    // transitive dependency.
    #[test]
    fn compile_and_write_returns_deps_for_importing_template() {
        let dir = tempfile::tempdir().unwrap();
        // Create a helper module that exports a function.
        let helper = dir.path().join("helper.mds");
        std::fs::write(
            &helper,
            "@define greet(name):\nHello {name}!\n@end\n\n@export greet\n",
        )
        .unwrap();
        // Create an entry that imports and includes the helper.
        let entry = dir.path().join("entry.mds");
        std::fs::write(
            &entry,
            "@import \"./helper.mds\" as h\n\n{h.greet(\"World\")}\n",
        )
        .unwrap();
        // Use -o <out> style to direct output to a specific path.
        let out = dir.path().join("entry.md");
        let out_str = out.display().to_string();
        // The canonical form `run_watch` derives, which the compile checks the typed path
        // against (on macOS the temporary directory is not canonical).
        let watched = WatchedPath {
            canonical: mds::NativeFs::check_symlink(&entry).unwrap(),
            typed: entry,
            what: Watched::Entry,
        };
        let (_written_path, deps, _content) =
            match compile_and_write(&watched, &Some(out_str), &None, &None, &[], None, true)
                .unwrap()
            {
                CompileWriteOutcome::Written(result) => result,
                CompileWriteOutcome::CompileFailed(e) => panic!("the compile failed: {e:?}"),
                CompileWriteOutcome::WriteFailed { failure, .. } => {
                    panic!("the write failed: {failure:?}")
                }
                CompileWriteOutcome::StdoutClosed => {
                    panic!("compile_and_write writes a file here, never stdout")
                }
            };
        // The entry's compile output should list helper as a dependency.
        assert!(out.exists(), "output file should be created");
        assert!(
            !deps.is_empty(),
            "compile_and_write should return the imported helper as a dep"
        );
        let dep_names: Vec<_> = deps
            .iter()
            .filter_map(|d| {
                PathBuf::from(d)
                    .file_name()
                    .and_then(|n| n.to_str())
                    .map(str::to_owned)
            })
            .collect();
        assert!(
            dep_names.iter().any(|n| n == "helper.mds"),
            "deps should contain helper.mds, got: {dep_names:?}"
        );
    }

    /// #257: a write that fails after the compile succeeded keeps the dependencies the
    /// compile reported, and reports the failure naming the output of the compiled kind —
    /// `.json` for a messages template. Only a compile that fails leaves the kind unknown.
    #[test]
    fn compile_and_write_tells_a_failed_write_from_a_failed_compile() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("part.mds"),
            "@define who():\nWorld\n@end\n\n@export who\n",
        )
        .unwrap();
        let entry = dir.path().join("chat.mds");
        std::fs::write(
            &entry,
            "@import \"./part.mds\" as p\n@message user:\nHello {{p.who()}}\n@end\n",
        )
        .unwrap();
        // A directory at the output path: no write replaces it.
        std::fs::create_dir(dir.path().join("chat.json")).unwrap();
        let watched = WatchedPath {
            canonical: mds::NativeFs::check_symlink(&entry).unwrap(),
            typed: entry.clone(),
            what: Watched::Entry,
        };
        let name = |path: &Path| path.file_name().and_then(|n| n.to_str()).map(str::to_owned);

        match compile_and_write(&watched, &None, &None, &None, &[], None, true).unwrap() {
            CompileWriteOutcome::WriteFailed { deps, failure } => {
                let dep_names: Vec<_> = deps.iter().filter_map(|d| name(d)).collect();
                assert!(
                    dep_names.iter().any(|n| n == "part.mds"),
                    "the dependencies the compile reported: {dep_names:?}"
                );
                let failure = failure.expect("a failed write is reported").to_string();
                assert!(
                    failure.contains("chat.json"),
                    "the failure names the output: {failure}"
                );
            }
            CompileWriteOutcome::CompileFailed(e) => panic!("the compile failed: {e:?}"),
            CompileWriteOutcome::Written(_) => panic!("a directory is never written over"),
            CompileWriteOutcome::StdoutClosed => panic!("the output is a file, never stdout"),
        }
        assert!(
            !dir.path().join("chat.md").exists(),
            "nothing is written on the Markdown route"
        );

        // Control: a compile that fails.
        std::fs::write(&entry, "Hello {{name\n").unwrap();
        assert!(
            matches!(
                compile_and_write(&watched, &None, &None, &None, &[], None, true).unwrap(),
                CompileWriteOutcome::CompileFailed(Some(_))
            ),
            "a failed compile is reported as one"
        );
    }

    /// #257, #160: without `-o` every output takes the route of its own kind — after a
    /// failed startup compile, and after a change of kind — and leaves the other kind's
    /// behind; the route an explicit `-o` names is every kind's, and leaves none.
    #[test]
    fn output_route_is_each_kinds_own_unless_one_is_named() {
        let target = |name: &str| Some(WriteTarget::as_typed(PathBuf::from(name)));
        let (md, json, named) = (target("chat.md"), target("chat.json"), target("out.md"));
        let by_kind = OutputRoute::ByKind {
            markdown: md.clone(),
            messages: json.clone(),
        };
        assert_eq!(by_kind.of(OutputKind::Messages), &json);
        assert_eq!(by_kind.of(OutputKind::Markdown), &md);
        assert_eq!(by_kind.other_than(OutputKind::Messages), md.as_ref());
        assert_eq!(by_kind.other_than(OutputKind::Markdown), json.as_ref());

        let route = OutputRoute::Named(named.clone());
        for kind in [OutputKind::Markdown, OutputKind::Messages] {
            assert_eq!(route.of(kind), &named, "-o is the route of every kind");
            assert_eq!(route.other_than(kind), None, "-o leaves nothing behind");
        }
    }

    /// The watched entry uses its typed path within its canonical directory.
    /// A different canonical parent is refused with the typed path.
    /// A missing entry is refused with the lookup's own error and the typed path.
    #[test]
    fn watched_entry_refuses_a_typed_path_that_leads_elsewhere() {
        let dir = tempfile::TempDir::new().unwrap();
        for name in ["a", "b"] {
            std::fs::create_dir(dir.path().join(name)).unwrap();
            std::fs::write(
                dir.path().join(name).join("page.mds"),
                format!("Hi {name}\n"),
            )
            .unwrap();
        }
        let typed = dir.path().join("a").join("page.mds");
        let compile = |canonical: &Path| {
            WatchedPath {
                typed: typed.clone(),
                canonical: canonical.to_path_buf(),
                what: Watched::Entry,
            }
            .compile(None, true, &Arc::new(mds::ReadLog::new()))
            .map(|compiled| compiled.content)
            .map_err(|failure| {
                failure
                    .into_report()
                    .map_or_else(|| "a panic".to_string(), |e| e.to_string())
            })
        };

        let here = mds::NativeFs::check_symlink(&typed).unwrap();
        assert_eq!(compile(&here), Ok("Hi a\n".to_string()), "control");

        let elsewhere =
            mds::NativeFs::check_symlink(&dir.path().join("b").join("page.mds")).unwrap();
        let refused = compile(&elsewhere).unwrap_err();
        assert_eq!(
            refused,
            format!(
                "watched entry now resolves to a different file: \"{}\"; \
                 restart mds watch to follow it",
                typed.display()
            )
        );
        assert!(
            !refused.contains(&*elsewhere.to_string_lossy()),
            "{refused}"
        );

        std::fs::remove_file(&typed).unwrap();
        let missing = compile(&here).unwrap_err();
        assert_eq!(
            missing,
            format!("file not found: {}", typed.display()),
            "the check refuses a missing entry with the lookup's own error and typed path"
        );
    }

    /// The root and each source use the entry's directory rule and their own typed path.
    /// Controls keep each typed path at its canonical form.
    /// A path that no longer resolves is refused with its own not-found error and typed path.
    #[test]
    fn watched_root_and_source_share_the_entry_rule() {
        let dir = tempfile::TempDir::new().unwrap();
        for name in ["a", "b"] {
            std::fs::create_dir(dir.path().join(name)).unwrap();
            std::fs::write(dir.path().join(name).join("page.mds"), "Hi\n").unwrap();
        }
        let canonical = |p: PathBuf| p.canonicalize().unwrap();
        let check = |typed: PathBuf, canonical: PathBuf, what: Watched| {
            WatchedPath {
                typed,
                canonical,
                what,
            }
            .ensure_unmoved()
            .map_err(|e| e.to_string())
        };
        let moved = |kind: &str, now: &str, typed: &Path| {
            Err(format!(
                "watched {kind} now resolves to a different {now}: \"{}\"; \
                 restart mds watch to follow it",
                typed.display()
            ))
        };

        let root = dir.path().join("a");
        let source = root.join("page.mds");
        let root_b = canonical(dir.path().join("b"));
        let source_b = canonical(dir.path().join("b").join("page.mds"));

        let mut mismatches = Vec::new();
        let rows = [
            (
                "root, unmoved",
                check(root.clone(), canonical(root.clone()), Watched::Root),
                Ok(()),
            ),
            (
                "root, moved",
                check(root.clone(), root_b.clone(), Watched::Root),
                moved("directory", "directory", &root),
            ),
            (
                "source, unmoved",
                check(source.clone(), canonical(source.clone()), Watched::Source),
                Ok(()),
            ),
            (
                "source, moved",
                check(source.clone(), source_b.clone(), Watched::Source),
                moved("file", "file", &source),
            ),
            (
                "root, gone",
                check(dir.path().join("gone"), root_b, Watched::Root),
                Err(format!(
                    "file not found: {}",
                    dir.path().join("gone").display()
                )),
            ),
            (
                "source, gone",
                check(root.join("gone.mds"), source_b, Watched::Source),
                Err(format!(
                    "file not found: {}",
                    root.join("gone.mds").display()
                )),
            ),
        ];
        for (label, got, want) in rows {
            if got != want {
                mismatches.push(format!("{label}: got {got:?}, want {want:?}"));
            }
        }
        assert!(mismatches.is_empty(), "{mismatches:#?}");
    }

    #[test]
    fn watched_paths_return_the_lookup_error_before_a_compile() {
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("page.mds");
        std::fs::write(&file, "Hi\n").unwrap();
        let canonical = file.canonicalize().unwrap();
        let blocked = file.join("blocked.mds");
        for what in [Watched::Root, Watched::Entry, Watched::Source] {
            let path = WatchedPath {
                typed: blocked.clone(),
                canonical: canonical.clone(),
                what,
            };
            let expected = match what {
                Watched::Root => {
                    // A path through a file is not a directory on Unix, and not found on
                    // Windows: each kind keeps its own refusal.
                    let cause = blocked.canonicalize().unwrap_err();
                    let shown =
                        mds::escape_path_for_message(&blocked.to_string_lossy()).into_owned();
                    if cause.kind() == std::io::ErrorKind::NotFound {
                        MdsError::FileNotFound {
                            path: shown,
                            span: None,
                            src: None,
                        }
                    } else {
                        MdsError::Io {
                            message: format!(
                                "cannot resolve path {shown}: {}",
                                crate::output::safe_inline(crate::output::io_cause(&cause))
                            ),
                        }
                    }
                }
                Watched::Entry | Watched::Source => {
                    mds::NativeFs::check_symlink(&blocked).unwrap_err()
                }
            };
            assert_eq!(
                path.ensure_unmoved().map_err(|error| error.to_string()),
                Err(expected.to_string()),
                "the lookup error must not become a moved error"
            );
            let control = WatchedPath {
                typed: file.clone(),
                canonical: canonical.clone(),
                what,
            };
            assert!(control.ensure_unmoved().is_ok());
        }
    }

    /// A session reads each `-o -` outcome itself (#157): a closed pipe stops it, a new
    /// failure for another reason is reported as `mds::io` naming stdout, and a repeat of
    /// it is not written and not reported — where a batch run takes both a closed pipe
    /// and a repeat for success.
    #[test]
    fn a_session_reads_each_stdout_outcome_for_itself() {
        assert!(matches!(
            OutputWrite::from_stdout(StdoutOutcome::Written),
            OutputWrite::Written
        ));
        assert!(matches!(
            OutputWrite::from_stdout(StdoutOutcome::Closed),
            OutputWrite::StdoutClosed
        ));
        assert!(matches!(
            OutputWrite::from_stdout(StdoutOutcome::FailedAgain),
            OutputWrite::Failed(None)
        ));
        let failed = std::io::Error::new(std::io::ErrorKind::StorageFull, "no space left");
        match OutputWrite::from_stdout(StdoutOutcome::Failed(failed)) {
            OutputWrite::Failed(Some(report)) => {
                assert_eq!(
                    report.to_string(),
                    format!(
                        "cannot write to stdout: {}",
                        std::io::ErrorKind::StorageFull
                    ),
                    "the error's kind, not the text it carries (#390)"
                );
                assert_eq!(
                    report.code().map(|c| c.to_string()).as_deref(),
                    Some("mds::io")
                );
            }
            other => panic!("want Failed(Some(mds::io)); got {other:?}"),
        }
    }

    /// Directory mode's state, empty.
    fn empty_dir_state() -> DirWatchState {
        DirWatchState {
            forward_deps: HashMap::new(),
            errored: HashSet::new(),
            known_files: BTreeSet::new(),
            last_written: HashMap::new(),
            outputs: HashMap::new(),
            kept: HashMap::new(),
            out_dir: None,
            reads: Vec::new(),
            external_dep_dirs: BTreeSet::new(),
            vars_file: None,
            last_mtimes: HashMap::new(),
            hold: EmptyHold::Off,
            held: HeldBatch::default(),
        }
    }

    /// File mode's state watching `foi`, with no baseline taken.
    fn file_state(foi: HashSet<PathBuf>) -> FileWatchState {
        FileWatchState {
            watched_dirs: BTreeSet::new(),
            armed_dirs: BTreeSet::new(),
            foi,
            last_mtimes: HashMap::new(),
            hold: EmptyHold::Off,
            last_written: HashMap::new(),
            written_to: None,
            kept: None,
            output: OutputRoute::Named(None),
            out_dir: None,
            entry_was_missing: false,
            first_tick: false,
            missing_watched_dirs: BTreeSet::new(),
        }
    }

    /// A source and its dependency on disk, for the settle tests: `(dir, source, dependency)`.
    fn source_and_dependency() -> (tempfile::TempDir, PathBuf, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("page.mds");
        let dep = dir.path().join("_dep.mds");
        std::fs::write(&src, "Page.\n").unwrap();
        std::fs::write(&dep, "Dep.\n").unwrap();
        (dir, src, dep)
    }

    /// `Settle::Rebaseline` takes the `(mtime, size)` baseline again in a rebuild, over what
    /// the mode watches, and records nothing else. There is no startup variant to apply it
    /// to: the startup baseline is still to come, so `SettleInto` holds only the two
    /// rebuild states (#257).
    #[test]
    fn settle_rebaseline_takes_the_baseline_again_in_a_rebuild_only() {
        let (dir, src, dep) = source_and_dependency();

        // File mode: over the files of interest.
        let foi: HashSet<PathBuf> = [src.clone(), dep.clone()].into_iter().collect();
        let mut file = file_state(foi.clone());
        settle(SettleInto::File(&mut file), None, Settle::Rebaseline);
        assert_eq!(file.last_mtimes, snapshot_state(&foi));
        assert!(
            file.last_mtimes
                .get(&src)
                .is_some_and(|stamp| stamp.0.is_some()),
            "the baseline holds the source as it is on disk: {:?}",
            file.last_mtimes
        );

        // Directory mode: over the watched set — the sources, their dependencies and the
        // `--vars` file (#380).
        let vars = dir.path().join("vars.json");
        std::fs::write(&vars, r#"{"v": 1}"#).unwrap();
        let mut rebuild = empty_dir_state();
        rebuild.known_files.insert(src.clone());
        rebuild.forward_deps.insert(src.clone(), vec![dep.clone()]);
        rebuild.vars_file = Some(vars.clone());
        settle(SettleInto::Dir(&mut rebuild), None, Settle::Rebaseline);
        assert_eq!(rebuild.last_mtimes, snapshot_state(&rebuild.watched_set()));
        assert!(
            rebuild.last_mtimes.contains_key(&dep) && rebuild.last_mtimes.contains_key(&vars),
            "the dependency and the vars file are in the baseline: {:?}",
            rebuild.last_mtimes
        );
        assert!(
            !rebuild.tracked_set().contains(&vars),
            "the vars file is outside the tracked set: no source and no dependency"
        );
        assert!(rebuild.errored.is_empty(), "nothing is marked errored");
    }

    /// `Settle::Defer` — a rebuild held while a watched file is empty — reports nothing,
    /// records nothing and leaves the baseline as it was in both modes, so the next event
    /// or tick finds the emptied file again; `Settle::Rebaseline` on the same state, after a
    /// look that saw the file empty, takes the empty file in (positive control) (#380).
    #[test]
    fn settle_defer_leaves_the_baseline_and_records_nothing() {
        let (_dir, src, dep) = source_and_dependency();
        let foi: HashSet<PathBuf> = [src.clone(), dep.clone()].into_iter().collect();
        let before = snapshot_state(&foi);
        std::fs::write(&dep, "").unwrap();
        let report = |e: miette::Report| panic!("a deferral reports nothing; got {e:?}");

        // File mode.
        let mut file = file_state(foi.clone());
        file.last_mtimes = before.clone();
        settle_reporting(SettleInto::File(&mut file), None, Settle::Defer, report);
        assert_eq!(file.last_mtimes, before, "the baseline is left as it was");
        assert!(
            any_went_empty(&file.foi, &file.last_mtimes),
            "the next rebuild finds the dependency emptied again"
        );
        file.last_mtimes.extend(snapshot_state(&foi));
        settle(SettleInto::File(&mut file), None, Settle::Rebaseline);
        assert!(
            !any_went_empty(&file.foi, &file.last_mtimes),
            "positive control: a rebaseline after a look that saw it empty takes it in"
        );

        // Directory mode.
        let mut rebuild = empty_dir_state();
        rebuild.known_files.insert(src.clone());
        rebuild.forward_deps.insert(src.clone(), vec![dep.clone()]);
        rebuild.last_mtimes = before.clone();
        settle_reporting(SettleInto::Dir(&mut rebuild), None, Settle::Defer, report);
        assert_eq!(
            rebuild.last_mtimes, before,
            "the baseline is left as it was"
        );
        assert!(rebuild.errored.is_empty(), "nothing is marked errored");
        assert!(
            any_went_empty(&rebuild.watched_set(), &rebuild.last_mtimes),
            "the next batch finds the dependency emptied again"
        );
        rebuild
            .last_mtimes
            .extend(snapshot_state(&rebuild.watched_set()));
        settle(SettleInto::Dir(&mut rebuild), None, Settle::Rebaseline);
        assert!(
            !any_went_empty(&rebuild.watched_set(), &rebuild.last_mtimes),
            "positive control: a rebaseline after a look that saw it empty takes it in"
        );
    }

    /// #380: a rebuild that settles by taking the baseline again takes the stamps its look
    /// took before it read anything — never the files as they are once it has read them. A
    /// file truncated since keeps the stamp that saw its bytes, so the next look finds it
    /// emptied: in file mode through `Settle::Rebaseline` (a `--vars` file that failed to
    /// load) and `Settle::MarkErrored` (a failed compile), in directory mode through
    /// `Settle::Rebaseline` (a batch whose `--vars` file failed to load). A file no look
    /// stamped is stamped then (positive control), and one the mode no longer watches is
    /// dropped.
    #[test]
    fn settle_rebaseline_keeps_the_stamps_the_look_took() {
        let (dir, src, dep) = source_and_dependency();
        let gone = dir.path().join("gone.mds");
        // What the look stamped, before the rebuild read anything: the dependency, with
        // its bytes, and a file the mode no longer watches.
        let mut look = snapshot_state(&HashSet::from([dep.clone()]));
        look.insert(gone.clone(), (None, Some(4)));
        // Truncated once the rebuild had read it.
        std::fs::write(&dep, "").unwrap();
        let kept = |baseline: &StampMap, what: &str| {
            assert_eq!(
                baseline.get(&dep),
                look.get(&dep),
                "{what}: the look's stamp, not the emptied file's"
            );
            assert!(
                baseline.contains_key(&src),
                "{what}: positive control: a file no look stamped is stamped; {baseline:?}"
            );
            assert!(
                !baseline.contains_key(&gone),
                "{what}: a file the mode no longer watches is dropped; {baseline:?}"
            );
        };

        // File mode.
        let foi: HashSet<PathBuf> = [src.clone(), dep.clone()].into_iter().collect();
        for (how, what) in [
            (Settle::Rebaseline, "file mode, a rebaseline"),
            (Settle::MarkErrored(&src), "file mode, a failed compile"),
        ] {
            let mut file = file_state(foi.clone());
            file.last_mtimes = look.clone();
            settle(SettleInto::File(&mut file), None, how);
            kept(&file.last_mtimes, what);
            assert!(
                any_went_empty(&file.foi, &file.last_mtimes),
                "{what}: the next rebuild finds the dependency emptied"
            );
        }

        // Directory mode: over the watched set, the `--vars` file included.
        let vars = dir.path().join("vars.json");
        std::fs::write(&vars, r#"{"v": 1}"#).unwrap();
        let mut rebuild = empty_dir_state();
        rebuild.known_files.insert(src.clone());
        rebuild.forward_deps.insert(src.clone(), vec![dep.clone()]);
        rebuild.vars_file = Some(vars.clone());
        rebuild.last_mtimes = look.clone();
        settle(SettleInto::Dir(&mut rebuild), None, Settle::Rebaseline);
        kept(&rebuild.last_mtimes, "directory mode, a rebaseline");
        assert!(
            rebuild.last_mtimes.contains_key(&vars),
            "the vars file is stamped: {:?}",
            rebuild.last_mtimes
        );
        assert!(
            any_went_empty(&rebuild.watched_set(), &rebuild.last_mtimes),
            "the next batch finds the dependency emptied"
        );
    }

    /// A canonical temporary directory: every path a rebuild carries is canonical, and
    /// macOS tempdirs are below a symlink.
    fn canonical_tempdir() -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let path = std::fs::canonicalize(dir.path()).unwrap();
        (dir, path)
    }

    /// Directory mode's rebuild context: `root` watched, outputs below `out`, no `--vars`,
    /// quiet.
    fn dir_ctx(root: &Path, out: &Path) -> DirWatchCtx {
        DirWatchCtx {
            root: WatchedPath {
                typed: root.to_path_buf(),
                canonical: root.to_path_buf(),
                what: Watched::Root,
            },
            working_dir: WorkingDir { canonical: None },
            vars_path: None,
            vars_path_typed: None,
            static_set_vars: Vec::new(),
            static_set_string_vars: Vec::new(),
            output_base: dir_base(out.to_path_buf()),
            exclude_prefix: None,
            vars_dir_extra: None,
            clear: false,
            debounce_ms: 0,
            quiet: true,
        }
    }

    /// #380: a watched file found emptied while its own event was lost joins the held
    /// batch, so the batch that ends the hold rebuilds it — its write's event lost too —
    /// rather than taking its new content into the baseline unseen.
    #[test]
    fn a_file_found_emptied_without_its_event_is_rebuilt_when_the_hold_ends() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (a, x) = (root.join("a.mds"), root.join("x.mds"));
        std::fs::write(&a, "A one\n").unwrap();
        std::fs::write(&x, "X one\n").unwrap();
        let ctx = dir_ctx(&root, &out);
        let mut state = empty_dir_state();
        state.known_files.extend([a.clone(), x.clone()]);
        state.last_mtimes = snapshot_state(&state.watched_set());

        // x emptied, its event lost: a batch for a finds it so.
        std::fs::write(&x, "").unwrap();
        rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
        assert!(
            state.hold.deadline().is_some(),
            "control: the batch is held while x is empty"
        );
        // x written, that event lost as well: the next batch finds nothing emptied.
        std::fs::write(&x, "X two\n").unwrap();
        rebuild_dir_batch(&ctx, &BTreeSet::new(), false, &mut state, None);

        let read = |name: &str| std::fs::read_to_string(out.join(name)).ok();
        assert!(
            read("a.md").is_some_and(|text| text.contains("A one")),
            "positive control: the held batch is rebuilt; out/a.md: {:?}",
            read("a.md")
        );
        assert!(
            read("x.md").is_some_and(|text| text.contains("X two")),
            "the file found emptied is rebuilt with it; out/x.md: {:?}",
            read("x.md")
        );
    }

    /// #380: a directory batch the `--vars` file cannot be read for is reported, and what
    /// it carried is rebuilt with the next batch: a source created while the file is
    /// broken is compiled by the batch that reads it again — which carries only the vars
    /// change — and is then known; a source deleted meanwhile is retired by it.
    #[test]
    fn a_batch_the_vars_file_could_not_be_read_for_is_rebuilt_with_the_next() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (_vars_dir, vars_dir) = canonical_tempdir();
        let vars = vars_dir.join("vars.json");
        let known = root.join("known.mds");
        let gone = root.join("gone.mds");
        let created = root.join("created.mds");
        std::fs::write(&known, "Known {{v}}\n").unwrap();
        std::fs::write(&gone, "Gone {{v}}\n").unwrap();
        std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
        let ctx = DirWatchCtx {
            vars_path: Some(vars.clone()),
            vars_path_typed: Some(vars.clone()),
            ..dir_ctx(&root, &out)
        };
        let mut state = empty_dir_state();
        state.vars_file = Some(vars.clone());
        state.known_files.extend([known.clone(), gone.clone()]);
        rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
        let read = |name: &str| std::fs::read_to_string(out.join(name)).ok();
        assert!(
            read("gone.md").is_some_and(|text| text.contains("Gone one")),
            "control: the session wrote out/gone.md; {:?}",
            read("gone.md")
        );

        // The vars file broken: neither the batch that broke it nor the next one can read
        // it — the next one creates a source and deletes another.
        std::fs::write(&vars, r#"{"v": "#).unwrap();
        rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
        std::fs::write(&created, "Created {{v}}\n").unwrap();
        std::fs::remove_file(&gone).unwrap();
        let batch = BTreeSet::from([created.clone(), gone.clone()]);
        rebuild_dir_batch(&ctx, &batch, false, &mut state, None);
        assert_eq!(
            read("created.md"),
            None,
            "control: nothing is compiled while the vars file cannot be read"
        );

        // The vars file fixed: the batch that reads it again carries only that change.
        std::fs::write(&vars, r#"{"v": "two"}"#).unwrap();
        rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);

        assert!(
            read("known.md").is_some_and(|text| text.contains("Known two")),
            "positive control: the vars fix recompiles the known source; out/known.md: {:?}",
            read("known.md")
        );
        assert!(
            read("created.md").is_some_and(|text| text.contains("Created two")),
            "the source created while the vars file was broken is compiled; \
             out/created.md: {:?}",
            read("created.md")
        );
        assert!(
            state.known_files.contains(&created) && !state.known_files.contains(&gone),
            "the created source is known, the deleted one not; known: {:?}",
            state.known_files
        );
        assert_eq!(
            read("gone.md"),
            None,
            "the source deleted while the vars file was broken is retired"
        );
        assert_eq!(state.held, HeldBatch::default(), "nothing stays held");
    }

    /// #380: a batch the `--vars` file could not be read for keeps that it changed the
    /// file, so the next batch rebuilds as a vars change even when its own events name a
    /// source only — the fixing save's event lost — and every known source is compiled
    /// against the file as it then reads, not only the source edited.
    #[test]
    fn a_vars_change_kept_for_the_next_batch_recompiles_every_known_source() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (_vars_dir, vars_dir) = canonical_tempdir();
        let vars = vars_dir.join("vars.json");
        let (a, b) = (root.join("a.mds"), root.join("b.mds"));
        std::fs::write(&a, "A {{v}}\n").unwrap();
        std::fs::write(&b, "B {{v}}\n").unwrap();
        std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
        let ctx = DirWatchCtx {
            vars_path: Some(vars.clone()),
            vars_path_typed: Some(vars.clone()),
            ..dir_ctx(&root, &out)
        };
        let mut state = empty_dir_state();
        state.vars_file = Some(vars.clone());
        state.known_files.extend([a.clone(), b.clone()]);
        rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
        let read = |name: &str| std::fs::read_to_string(out.join(name)).ok();
        assert!(
            read("b.md").is_some_and(|text| text.contains("B one")),
            "control: out/b.md is compiled against the first vars; {:?}",
            read("b.md")
        );

        std::fs::write(&vars, r#"{"v": "#).unwrap();
        rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
        // The vars file fixed, that event lost; a source edited.
        std::fs::write(&vars, r#"{"v": "two"}"#).unwrap();
        std::fs::write(&a, "A again {{v}}\n").unwrap();
        rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);

        assert!(
            read("a.md").is_some_and(|text| text.contains("A again two")),
            "positive control: the edited source is compiled; out/a.md: {:?}",
            read("a.md")
        );
        assert!(
            read("b.md").is_some_and(|text| text.contains("B two")),
            "the vars change kept from the batch that could not read it recompiles the \
             other known source; out/b.md: {:?}",
            read("b.md")
        );
    }

    /// #380: a batch whose `--vars` file changed recompiles the sources whose last compile
    /// failed as well as the known ones: a source created by a batch whose compile failed
    /// is known to no walk, only as errored, and the vars change that fixes it compiles it
    /// and makes it known. A source still failing stays errored. A path errored that is no
    /// source below the root — a dependency outside it, or one in a directory the walk
    /// skips — is not compiled as one.
    #[test]
    fn a_vars_changed_batch_recompiles_the_sources_whose_last_compile_failed() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (_vars_dir, vars_dir) = canonical_tempdir();
        let (_elsewhere_dir, elsewhere) = canonical_tempdir();
        let vars = vars_dir.join("vars.json");
        let known = root.join("known.mds");
        let created = root.join("created.mds");
        let failing = root.join("failing.mds");
        let excluded = root.join("node_modules").join("dep.mds");
        let outside = elsewhere.join("outside.mds");
        std::fs::create_dir(root.join("node_modules")).unwrap();
        std::fs::write(&known, "Known {{v}}\n").unwrap();
        std::fs::write(&excluded, "Excluded {{x}}\n").unwrap();
        std::fs::write(&outside, "Outside {{x}}\n").unwrap();
        std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
        let ctx = DirWatchCtx {
            vars_path: Some(vars.clone()),
            vars_path_typed: Some(vars.clone()),
            ..dir_ctx(&root, &out)
        };
        let mut state = empty_dir_state();
        state.vars_file = Some(vars.clone());
        state.known_files.insert(known.clone());
        rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
        let read = |rel: &Path| std::fs::read_to_string(out.join(rel)).ok();
        assert!(
            read(Path::new("known.md")).is_some_and(|text| text.contains("Known one")),
            "control: out/known.md is compiled against the first vars; {:?}",
            read(Path::new("known.md"))
        );

        // Two sources created, each reading a variable the vars file does not define.
        std::fs::write(&created, "Created {{x}}\n").unwrap();
        std::fs::write(&failing, "Failing {{missing}}\n").unwrap();
        let batch = BTreeSet::from([created.clone(), failing.clone()]);
        rebuild_dir_batch(&ctx, &batch, false, &mut state, None);
        assert!(
            read(Path::new("created.md")).is_none()
                && state.errored.contains(&created)
                && !state.known_files.contains(&created),
            "control: the created source's compile failed, and it is errored, not known; \
             errored: {:?}, known: {:?}",
            state.errored,
            state.known_files
        );
        // Errored paths that are no sources below the root, as a dependency's failed
        // refresh leaves them.
        state.errored.extend([excluded.clone(), outside.clone()]);

        // The vars file defines the variable: a batch that carries only that change.
        std::fs::write(&vars, r#"{"v": "two", "x": "World"}"#).unwrap();
        rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);

        assert!(
            read(Path::new("known.md")).is_some_and(|text| text.contains("Known two")),
            "positive control: the vars change recompiles the known source; \
             out/known.md: {:?}",
            read(Path::new("known.md"))
        );
        assert!(
            read(Path::new("created.md")).is_some_and(|text| text.contains("Created World")),
            "the source whose last compile failed is recompiled; out/created.md: {:?}",
            read(Path::new("created.md"))
        );
        assert!(
            state.known_files.contains(&created) && !state.errored.contains(&created),
            "and is known, no longer errored; known: {:?}, errored: {:?}",
            state.known_files,
            state.errored
        );
        assert!(
            read(Path::new("failing.md")).is_none() && state.errored.contains(&failing),
            "a source still failing stays errored; errored: {:?}",
            state.errored
        );
        // Where each would be written had it been compiled as a source.
        for rel in [
            Path::new("node_modules").join("dep.md"),
            PathBuf::from("outside.md"),
        ] {
            assert_eq!(
                read(&rel),
                None,
                "{}: an errored path that is no source below the root is not compiled as one",
                rel.display()
            );
        }
        for path in [&excluded, &outside] {
            assert!(
                !state.known_files.contains(path) && !state.errored.contains(path),
                "{}: neither known nor errored; known: {:?}, errored: {:?}",
                path.display(),
                state.known_files,
                state.errored
            );
        }
    }

    /// A liveness state past its first tick, with the root armed: an idle tick that runs
    /// only the content check.
    fn idle_liveness() -> LivenessState {
        LivenessState {
            first_tick: false,
            root_was_missing: false,
            root_armed: true,
            missing_external_dirs: BTreeSet::new(),
            armed_dirs: BTreeSet::new(),
            failing_dirs: BTreeSet::new(),
        }
    }

    /// What a liveness tick or a rebuild asked of the watcher.
    #[derive(Debug, PartialEq, Eq)]
    enum WatchCall {
        Watch(PathBuf),
        Unwatch(PathBuf),
    }

    /// A watcher that holds nothing and records every call made of it ([`WatchCall`]).
    #[derive(Default)]
    struct RecordingWatcher {
        calls: Vec<WatchCall>,
    }

    impl Watcher for RecordingWatcher {
        fn new<F: notify::EventHandler>(_: F, _: notify::Config) -> notify::Result<Self> {
            Ok(Self::default())
        }

        fn watch(&mut self, path: &Path, _: RecursiveMode) -> notify::Result<()> {
            self.calls.push(WatchCall::Watch(path.to_path_buf()));
            Ok(())
        }

        fn unwatch(&mut self, path: &Path) -> notify::Result<()> {
            self.calls.push(WatchCall::Unwatch(path.to_path_buf()));
            Ok(())
        }

        fn kind() -> notify::WatcherKind {
            notify::WatcherKind::NullWatcher
        }
    }

    /// Directory mode with a `--vars` file whose directory is outside the root: the
    /// context, and a state whose baseline is taken over that file.
    fn dir_ctx_with_vars(root: &Path, out: &Path, vars: &Path) -> (DirWatchCtx, DirWatchState) {
        let ctx = DirWatchCtx {
            vars_path: Some(vars.to_path_buf()),
            vars_path_typed: Some(vars.to_path_buf()),
            vars_dir_extra: vars.parent().map(Path::to_path_buf),
            ..dir_ctx(root, out)
        };
        let mut state = empty_dir_state();
        state.vars_file = Some(vars.to_path_buf());
        state.last_mtimes = snapshot_state(&state.watched_set());
        (ctx, state)
    }

    /// #257: a directory watch's idle tick watches a directory only when the watcher does
    /// not hold it — not the root again on the first tick, which the startup armed, and not
    /// the `--vars` file's directory on every tick. A repeat watch of a held path is no
    /// no-op: macOS restarts its event stream, dropping the events that land meanwhile, and
    /// Windows opens another handle, which delivers every event once more. A directory the
    /// watcher does not hold is watched once.
    #[test]
    fn a_tick_watches_a_directory_only_when_the_watcher_does_not_hold_it() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (_vars_parent, vars_parent) = canonical_tempdir();
        let (_ext_dir, ext) = canonical_tempdir();
        let vars_dir = vars_parent.join("cfg");
        let vars = vars_dir.join("vars.json");
        std::fs::create_dir(&vars_dir).unwrap();
        std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
        let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
        state.external_dep_dirs.insert(ext.clone());
        // The first tick of a session whose startup armed the root, and neither directory
        // outside it: their watches failed.
        let mut liveness = LivenessState {
            first_tick: true,
            ..idle_liveness()
        };
        let mut watcher = RecordingWatcher::default();

        for _ in 0..6 {
            liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
        }
        assert_eq!(
            watcher.calls,
            [
                WatchCall::Watch(ext.clone()),
                WatchCall::Watch(vars_dir.clone())
            ],
            "six ticks watch each directory the watcher did not hold once — the positive \
             control — and nothing else"
        );
    }

    /// #257: the `--vars` file's directory outside the root that vanishes is no longer
    /// held, its watch gone with it, and the first tick that finds it back watches it once
    /// more; the ticks after that leave it alone.
    #[test]
    fn a_vars_directory_back_from_vanishing_is_watched_once_more() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (_vars_parent, vars_parent) = canonical_tempdir();
        let vars_dir = vars_parent.join("cfg");
        let vars = vars_dir.join("vars.json");
        std::fs::create_dir(&vars_dir).unwrap();
        std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
        let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
        let mut liveness = LivenessState {
            armed_dirs: BTreeSet::from([vars_dir.clone()]),
            ..idle_liveness()
        };
        let mut watcher = RecordingWatcher::default();
        liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
        assert_eq!(
            watcher.calls,
            [],
            "control: the held directory is not watched"
        );

        // The directory vanishes, then comes back.
        std::fs::remove_dir_all(&vars_dir).unwrap();
        liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
        assert_eq!(watcher.calls, [], "a directory that is gone is not watched");
        std::fs::create_dir(&vars_dir).unwrap();
        std::fs::write(&vars, r#"{"v": "two"}"#).unwrap();
        for _ in 0..3 {
            liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
        }
        assert_eq!(
            watcher.calls,
            [WatchCall::Watch(vars_dir.clone())],
            "the directory back is watched once, by the first tick that finds it"
        );
    }

    /// #257: the `--vars` file's directory outside the root that a dependency shares is
    /// one watch, held once: the tick watches it no more than any directory the watcher
    /// holds, and when no source imports from it any more it stays watched — only a
    /// directory nothing needs is unwatched.
    #[test]
    fn a_vars_directory_a_dependency_shares_stays_watched_once_the_import_goes() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (_shared_dir, shared) = canonical_tempdir();
        let (_other_dir, other) = canonical_tempdir();
        let vars = shared.join("vars.json");
        std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
        let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
        state
            .external_dep_dirs
            .extend([shared.clone(), other.clone()]);
        // The startup armed the shared directory as the vars file's, and the dependency's
        // arm found it held.
        let mut liveness = LivenessState {
            armed_dirs: BTreeSet::from([shared.clone(), other.clone()]),
            ..idle_liveness()
        };
        let mut watcher = RecordingWatcher::default();

        liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
        assert_eq!(
            watcher.calls,
            [],
            "every directory is held: nothing is watched"
        );

        // The imports from both directories edited away.
        state.external_dep_dirs.clear();
        for _ in 0..3 {
            liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
        }
        assert_eq!(
            watcher.calls,
            [WatchCall::Unwatch(other.clone())],
            "the directory nothing needs is unwatched — the positive control — and the vars \
             file's is left as it is"
        );
        assert_eq!(liveness.armed_dirs, BTreeSet::from([shared]));
    }

    /// #257: the rebuild after which no source imports from a directory outside the root
    /// any more unwatches it at once — the watches follow what the session imports under
    /// `--poll-interval 0` too, where no idle tick runs — and leaves the `--vars` file's
    /// directory and a directory still imported as they are.
    #[test]
    fn a_rebuild_unwatches_a_directory_no_source_imports_any_more() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (_vars_dir, vars_dir) = canonical_tempdir();
        let (_kept_dir, kept) = canonical_tempdir();
        let (_gone_dir, gone) = canonical_tempdir();
        let vars = vars_dir.join("vars.json");
        std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
        let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
        // The rebuild left one directory imported: the import from the other was edited
        // away.
        state.external_dep_dirs.insert(kept.clone());
        let mut liveness = LivenessState {
            armed_dirs: BTreeSet::from([vars_dir.clone(), kept.clone(), gone.clone()]),
            ..idle_liveness()
        };
        let mut watcher = RecordingWatcher::default();

        arm_external_dirs_after_rebuild(&ctx, &mut watcher, &mut liveness, &state);

        assert_eq!(
            watcher.calls,
            [WatchCall::Unwatch(gone.clone())],
            "the directory no source imports is unwatched — the positive control — and \
             nothing else is unwatched or watched"
        );
        assert_eq!(liveness.armed_dirs, BTreeSet::from([vars_dir, kept]));
    }

    /// A directory watch of `<base>/root`, whose `page.mds` imports `<base>/shared/_x.mds`
    /// from beside the root and reads `v` from `--vars <base>/vars.json`, after a first
    /// batch compiled it ([`cross_root_page`]).
    struct CrossRootPage {
        /// The temporary base and out-dir, removed when dropped.
        dirs: (tempfile::TempDir, tempfile::TempDir),
        base: PathBuf,
        out: PathBuf,
        page: PathBuf,
        module: PathBuf,
        shared: PathBuf,
        vars: PathBuf,
        ctx: DirWatchCtx,
        state: DirWatchState,
    }

    /// A [`CrossRootPage`], its first batch run: control — it tracks the dependency outside
    /// the root, and knows the directory that dependency is in.
    fn cross_root_page() -> CrossRootPage {
        let (base_dir, base) = canonical_tempdir();
        let (out_dir, out) = canonical_tempdir();
        let (root, shared) = (base.join("root"), base.join("shared"));
        std::fs::create_dir(&root).unwrap();
        std::fs::create_dir(&shared).unwrap();
        // The project's root marker, so the source may import from beside the root.
        std::fs::write(base.join(".mdsroot"), "").unwrap();
        let (page, module) = (root.join("page.mds"), shared.join("_x.mds"));
        std::fs::write(
            &page,
            "@import \"../shared/_x.mds\" as x\n{{x.greet()}} {{v}}\n",
        )
        .unwrap();
        std::fs::write(&module, "@define greet():\nX\n@end\n\n@export greet\n").unwrap();
        let vars = base.join("vars.json");
        std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
        let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
        state.known_files.insert(page.clone());
        rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
        assert!(
            state.tracked_set().contains(&module) && state.external_dep_dirs.contains(&shared),
            "control: the first batch tracks the dependency outside the root; out/page.md: {:?}",
            std::fs::read_to_string(out.join("page.md")).ok()
        );
        CrossRootPage {
            dirs: (base_dir, out_dir),
            base,
            out,
            page,
            module,
            shared,
            vars,
            ctx,
            state,
        }
    }

    /// #257: a batch after which no source imports from a directory outside the root forgets
    /// that directory, and the rebuild unwatches it — a batch of the source's edit, and one
    /// whose `--vars` file changed with it. The vars file's directory, held for that file,
    /// stays watched.
    #[test]
    fn a_batch_forgets_a_directory_no_source_imports_any_more() {
        for vars_changed in [false, true] {
            let CrossRootPage {
                dirs: _dirs,
                base,
                out,
                page,
                module,
                shared,
                vars,
                ctx,
                mut state,
            } = cross_root_page();

            // The import edited away, and the vars file with it or not.
            std::fs::write(&page, "Page {{v}}\n").unwrap();
            if vars_changed {
                std::fs::write(&vars, r#"{"v": "two"}"#).unwrap();
            }
            let batch = BTreeSet::from([page.clone()]);
            rebuild_dir_batch(&ctx, &batch, vars_changed, &mut state, None);
            let written = std::fs::read_to_string(out.join("page.md")).ok();
            assert!(
                written
                    .as_deref()
                    .is_some_and(|text| text.starts_with("Page ")),
                "vars changed: {vars_changed}: control: the source compiled without the \
                 import; out/page.md: {written:?}"
            );
            assert!(
                !state.tracked_set().contains(&module)
                    && !state.external_dep_dirs.contains(&shared),
                "vars changed: {vars_changed}: the directory no source imports from is \
                 forgotten; known: {:?}",
                state.external_dep_dirs
            );

            let mut liveness = LivenessState {
                armed_dirs: BTreeSet::from([base.clone(), shared.clone()]),
                ..idle_liveness()
            };
            let mut watcher = RecordingWatcher::default();
            arm_external_dirs_after_rebuild(&ctx, &mut watcher, &mut liveness, &state);
            assert_eq!(
                watcher.calls,
                [WatchCall::Unwatch(shared)],
                "vars changed: {vars_changed}: the rebuild unwatches it, and leaves the vars \
                 file's directory watched"
            );
        }
    }

    /// #380: a batch whose `--vars` file changed keeps the dependencies the last compile of
    /// a source reported when the source's compile fails, or when it is held because a file
    /// it read was emptied since the batch looked — neither reports dependencies of its own.
    /// The dependency outside the root stays tracked and its directory known, so the
    /// rebuild leaves it watched and the edit that fixes the source still reaches a batch;
    /// and a failed compile's look for a file emptied since the batch looked takes that
    /// dependency in, so a compile that failed on it emptied is held, not reported. The
    /// files are emptied after the batch's look: the batch is run from past it, as
    /// `rebuild_dir_batch` runs it once the look lets it.
    #[test]
    fn a_vars_change_keeps_the_dependencies_of_a_source_that_failed_or_was_held() {
        // The case, the vars file the batch reads, and whether the source or its
        // dependency is emptied since the batch looked.
        let cases = [
            ("a failed compile", r#"{"w": "two"}"#, false, false),
            (
                "a compile held on its source",
                r#"{"v": "two"}"#,
                true,
                false,
            ),
            (
                "a compile failed on its dependency",
                r#"{"v": "two"}"#,
                false,
                true,
            ),
        ];
        for (label, vars_text, empties_source, empties_dependency) in cases {
            let (_gone_dir, gone) = canonical_tempdir();
            let CrossRootPage {
                dirs: _dirs,
                base,
                out: _,
                page,
                module,
                shared,
                vars,
                ctx,
                mut state,
            } = cross_root_page();

            std::fs::write(&vars, vars_text).unwrap();
            if empties_source {
                std::fs::write(&page, "").unwrap();
            }
            if empties_dependency {
                std::fs::write(&module, "").unwrap();
            }
            let runtime_vars = crate::build::build_runtime_vars(RuntimeVarArgs {
                vars: Some(vars.clone()),
                set_vars: Vec::new(),
                set_string_vars: Vec::new(),
            })
            .unwrap()
            .vars;
            process_dir_batch(
                &BTreeSet::new(),
                true,
                &mut BatchCtx {
                    watch_root: &ctx.root,
                    output_base: &ctx.output_base,
                    vars: BatchVars::map_only(&runtime_vars),
                    quiet: true,
                },
                &mut state,
            );

            let (held, errored) = (
                state.held.paths.contains(&page),
                state.errored.contains(&page),
            );
            if empties_source || empties_dependency {
                assert!(
                    held && !errored,
                    "{label}: the source is held, not reported; held: {:?}, errored: {:?}",
                    state.held,
                    state.errored
                );
            } else {
                assert!(
                    errored && !held,
                    "{label}: control: the compile failed; errored: {:?}",
                    state.errored
                );
            }
            assert!(
                state.tracked_set().contains(&module),
                "{label}: the dependency outside the root is still tracked; tracked: {:?}",
                state.tracked_set()
            );
            assert!(
                state.external_dep_dirs.contains(&shared),
                "{label}: its directory is still known; {:?}",
                state.external_dep_dirs
            );

            // The rebuild's arming: the watcher holds the vars file's directory, the
            // dependency's, and one no source imports.
            let mut liveness = LivenessState {
                armed_dirs: BTreeSet::from([base.clone(), shared.clone(), gone.clone()]),
                ..idle_liveness()
            };
            let mut watcher = RecordingWatcher::default();
            arm_external_dirs_after_rebuild(&ctx, &mut watcher, &mut liveness, &state);
            assert_eq!(
                watcher.calls,
                [WatchCall::Unwatch(gone.clone())],
                "{label}: the directory nothing imports is unwatched — the positive control — \
                 and the dependency's stays watched"
            );
        }
    }

    /// #160: a retired output that is not there — its name missing, or a file where a
    /// directory on its way should be — is gone, and the session's record of it goes too;
    /// with no record, it is gone with no `Kept` notice, which is told only of a file kept.
    #[test]
    fn a_retired_output_that_is_not_there_is_gone_with_its_record() {
        let (_dir, root) = canonical_tempdir();
        let src = root.join("page.mds");
        std::fs::write(root.join("file"), "a file, no directory\n").unwrap();
        for (label, out) in [
            ("a missing name", root.join("page.md")),
            ("a file on its way", root.join("file").join("page.md")),
        ] {
            let target = WriteTarget::as_typed(out.clone());
            assert!(
                retire_output(
                    &target,
                    None,
                    OutDirNow::Unchanged,
                    Record::Unwritten,
                    Retirement::SourceDeleted,
                    true,
                ),
                "{label}: with no record, the output is gone — not kept, with a notice"
            );
            let mut state = empty_dir_state();
            state.wrote(&src, &target, "Page.\n".to_owned());
            state.retire(
                &src,
                &target,
                OutDirNow::Unchanged,
                Retirement::SourceDeleted,
                true,
            );
            assert_eq!(
                state.record(&out, &src),
                Record::Unwritten,
                "{label}: the output is gone, and its record with it"
            );
        }
    }

    /// #160: a retired output the session wrote that cannot be looked at — in a directory
    /// it may no longer search — is no output gone: its removal is reported as failed, and
    /// the session keeps its record of it, so the file stays the session's. Positive
    /// control: the directory searchable again, the same retirement removes it and its
    /// record. `#[cfg(unix)]`: the look is refused through a directory's mode bits, which
    /// Windows does not use to refuse it; skipped with a reason where the mode does not
    /// refuse it (running as root).
    #[cfg(unix)]
    #[test]
    fn a_retired_output_that_cannot_be_looked_at_keeps_its_record() {
        use std::os::unix::fs::PermissionsExt as _;

        let (_dir, root) = canonical_tempdir();
        let (src, sub) = (root.join("page.mds"), root.join("sub"));
        std::fs::create_dir(&sub).unwrap();
        let out = sub.join("page.md");
        std::fs::write(&out, "Page.\n").unwrap();
        let target = WriteTarget::as_typed(out.clone());
        let mut state = empty_dir_state();
        state.wrote(&src, &target, "Page.\n".to_owned());

        std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o000)).unwrap();
        if std::fs::symlink_metadata(&out).is_ok() {
            std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o755)).unwrap();
            crate::output::ewriteln!("running as root; mode 0o000 does not stop a look");
            return;
        }
        state.retire(
            &src,
            &target,
            OutDirNow::Unchanged,
            Retirement::SourceDeleted,
            true,
        );
        let kept = state.record(&out, &src) == Record::Own("Page.\n");
        // Restored before asserting, so the temporary directory can be removed.
        std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o755)).unwrap();
        assert!(
            kept,
            "an output that cannot be looked at keeps the session's record of it"
        );
        assert_eq!(
            std::fs::read_to_string(&out).ok().as_deref(),
            Some("Page.\n"),
            "and is left as it is"
        );

        state.retire(
            &src,
            &target,
            OutDirNow::Unchanged,
            Retirement::SourceDeleted,
            true,
        );
        assert!(
            !out.exists() && state.record(&out, &src) == Record::Unwritten,
            "positive control: the directory searchable again, the output is removed and \
             its record goes"
        );
    }

    /// #380: a file-mode event's rebuild asks for `--clear`'s clear only under `--clear`,
    /// and an event that starts no rebuild asks for none.
    #[test]
    fn a_file_event_s_rebuild_asks_for_the_clear_only_under_clear() {
        const NAME: &str =
            "watch::tests::a_file_event_s_rebuild_asks_for_the_clear_only_under_clear";
        if child_process::is_child(NAME) {
            let (_dir, root) = canonical_tempdir();
            let (entry, other) = (root.join("page.mds"), root.join("other.txt"));
            let foi: HashSet<PathBuf> = std::iter::once(entry.clone()).collect();
            let (_tx, rx) = mpsc::channel::<Msg>();
            for clear in [false, true] {
                crate::output::cancel_clear();
                let skipped = handle_fs_event_file(
                    modify_event(other.to_str().unwrap()),
                    &foi,
                    &rx,
                    0,
                    clear,
                );
                assert!(
                    matches!(skipped, FileEventAction::Skip) && !child_process::clear_is_asked(),
                    "--clear: {clear}: control: an event that rebuilds nothing asks for nothing"
                );
                let action = handle_fs_event_file(
                    modify_event(entry.to_str().unwrap()),
                    &foi,
                    &rx,
                    0,
                    clear,
                );
                assert!(
                    matches!(action, FileEventAction::Rebuild),
                    "--clear: {clear}: control: the event rebuilds"
                );
                assert_eq!(
                    child_process::clear_is_asked(),
                    clear,
                    "--clear: {clear}: the event's rebuild asks for the clear"
                );
            }
            return;
        }
        let _ = stderr_of_a_child_on_a_terminal(NAME);
    }

    /// What a clear of the terminal writes, pinned here apart from the constant that makes it.
    const CLEAR: &str = "\x1b[2J\x1b[3J\x1b[H";

    /// Run the test `name` again in a child whose stderr counts as a terminal, and return
    /// what the child wrote to stderr. The child must pass, and must really have run the
    /// test: a name that matches no test passes with none run.
    fn stderr_of_a_child_on_a_terminal(name: &str) -> String {
        let child = child_process::run_on_a_terminal(name);
        let report = String::from_utf8_lossy(&child.stdout).into_owned();
        let printed = String::from_utf8_lossy(&child.stderr).into_owned();
        assert!(
            report.contains("running 1 test"),
            "control: the child ran the test; stdout:\n{report}"
        );
        assert!(
            child.status.success(),
            "the child's test passes; stdout:\n{report}\nstderr:\n{printed}"
        );
        printed
    }

    /// A source that compiles with a warning — it includes a module with no body — and the
    /// module it imports, written under `root`; the source's path.
    fn page_with_a_warning(root: &Path, name: &str) -> PathBuf {
        std::fs::write(
            root.join("_fns.mds"),
            "@define greet(who):\nHello {{who}}!\n@end\n\n@export greet\n",
        )
        .unwrap();
        let page = root.join(name);
        std::fs::write(
            &page,
            "@import \"./_fns.mds\" as fns\nBefore\n@include fns\nAfter\n",
        )
        .unwrap();
        page
    }

    /// A watcher no event reaches.
    fn idle_watcher() -> RecommendedWatcher {
        RecommendedWatcher::new(|_: notify::Result<Event>| {}, notify::Config::default()).unwrap()
    }

    /// File mode's state for `entry`, written to `out` (`None`: stdout), with a baseline.
    fn file_state_writing(entry: &Path, out: Option<&Path>) -> FileWatchState {
        let mut state = file_state(std::iter::once(entry.to_path_buf()).collect());
        state.output = OutputRoute::Named(out.map(|out| WriteTarget::as_typed(out.to_path_buf())));
        state.last_mtimes = snapshot_state(&state.foi);
        state
    }

    /// #380: the clear `--clear` asked for comes before the first thing a file rebuild
    /// prints — a compile warning included, which the compile prints before the rebuild
    /// knows anything else — and is made once.
    #[test]
    fn a_file_rebuild_prints_its_compile_warning_after_the_clear() {
        const NAME: &str =
            "watch::tests::a_file_rebuild_prints_its_compile_warning_after_the_clear";
        if child_process::is_child(NAME) {
            let (_dir, root) = canonical_tempdir();
            let entry = page_with_a_warning(&root, "page.mds");
            let ctx = FileCompileCtx {
                quiet: false,
                ..file_ctx(&entry)
            };
            let mut state = file_state_writing(&entry, Some(&root.join("page.md")));
            crate::output::ask_clear();
            let _ = rebuild_file(&ctx, &mut idle_watcher(), &mut state, None);
            return;
        }
        let printed = stderr_of_a_child_on_a_terminal(NAME);
        assert!(
            printed.starts_with(CLEAR),
            "the clear is the first thing the rebuild prints:\n{printed:?}"
        );
        assert_eq!(printed.matches(CLEAR).count(), 1, "made once:\n{printed:?}");
        let (warning, recompiled) = (printed.find("warning:"), printed.find("Recompiled"));
        assert!(
            warning.is_some() && warning < recompiled,
            "control: the warning is printed, before the Recompiled line:\n{printed:?}"
        );
    }

    /// #380: a file-mode rebuild held while a file is empty — found so by its look, or by its
    /// compile after the look — leaves the clear `--clear` asked for to the rebuild that
    /// ends the hold, which makes it — the hold's deadline, or the first rebuild that finds
    /// the file written — as long as it printed nothing. (The module the compile reads
    /// emptied is one the look does not stat, so its hold ends when it is written; and the
    /// compile warns of an empty module before the hold is found, so that warning makes the
    /// clear and the rebuild that ends the hold makes none.)
    #[test]
    fn a_held_file_rebuild_leaves_the_clear_to_the_rebuild_that_ends_the_hold() {
        const NAME: &str =
            "watch::tests::a_held_file_rebuild_leaves_the_clear_to_the_rebuild_that_ends_the_hold";
        if child_process::is_child(NAME) {
            let (_dir, root) = canonical_tempdir();
            let (entry, module, out) = (
                root.join("page.mds"),
                root.join("_inc.mds"),
                root.join("page.md"),
            );
            let mut watcher = idle_watcher();
            let ctx = FileCompileCtx {
                quiet: false,
                ..file_ctx(&entry)
            };
            for held_by in ["its look", "its compile"] {
                std::fs::write(
                    &entry,
                    "@import \"./_inc.mds\" as inc\nPage.\n@include inc\n",
                )
                .unwrap();
                std::fs::write(&module, "Inc.\n").unwrap();
                let mut state = file_state_writing(&entry, Some(&out));
                if held_by == "its look" {
                    std::fs::write(&entry, "").unwrap();
                } else {
                    // The included module, which the look does not stat, read emptied.
                    std::fs::write(&module, "").unwrap();
                    state.last_mtimes.insert(module.clone(), (None, Some(5)));
                }
                crate::output::ask_clear();
                let _ = rebuild_file(&ctx, &mut watcher, &mut state, None);
                assert!(
                    state.hold.deadline().is_some(),
                    "{held_by}: control: the rebuild is held"
                );
                // The look holds before anything is read, so nothing is printed. A hold by
                // the compile comes after the compile's own warning for the emptied module,
                // which was printed, and made the clear, before the hold was found.
                assert_eq!(
                    child_process::clear_is_asked(),
                    held_by == "its look",
                    "{held_by}: a rebuild held before it prints leaves the clear asked for"
                );

                let due = if held_by == "its look" {
                    state.hold.deadline()
                } else {
                    std::fs::write(&module, "Inc.\n").unwrap();
                    None
                };
                let _ = rebuild_file(&ctx, &mut watcher, &mut state, due);
                assert_eq!(
                    state.hold.deadline(),
                    None,
                    "{held_by}: control: the hold ends"
                );
                assert!(
                    !child_process::clear_is_asked(),
                    "{held_by}: the rebuild that ends the hold made the clear"
                );
            }
            return;
        }
        let printed = stderr_of_a_child_on_a_terminal(NAME);
        let shown: Vec<&str> = printed.split(CLEAR).collect();
        assert!(
            shown.len() == 3
                && shown[0].is_empty()
                && shown[1].starts_with("Recompiled")
                && shown[2].starts_with("warning:")
                && shown[2].contains("Recompiled"),
            "held by its look: one clear before the line of the rebuild that ends the hold, \
             none before the held rebuild; held by its compile: one clear before the \
             compile's own warning, none before the line of the rebuild that ends the \
             hold; stderr:\n{printed:?}"
        );
    }

    /// #380: a file rebuild that prints nothing, and is not held, leaves no clear behind:
    /// a line printed after it is not preceded by the clear it asked for.
    #[test]
    fn a_file_rebuild_that_prints_nothing_leaves_no_clear_behind() {
        const NAME: &str =
            "watch::tests::a_file_rebuild_that_prints_nothing_leaves_no_clear_behind";
        if child_process::is_child(NAME) {
            let (_dir, root) = canonical_tempdir();
            let (entry, out) = (root.join("page.mds"), root.join("page.md"));
            std::fs::write(&entry, "Page.\n").unwrap();
            let ctx = FileCompileCtx {
                quiet: false,
                ..file_ctx(&entry)
            };
            let mut state = file_state_writing(&entry, Some(&out));
            let mut watcher = idle_watcher();
            crate::output::ask_clear();
            let _ = rebuild_file(&ctx, &mut watcher, &mut state, None);
            assert!(
                !child_process::clear_is_asked(),
                "control: the first rebuild printed"
            );

            // The same output again: written nowhere, shown nothing.
            crate::output::ask_clear();
            let _ = rebuild_file(&ctx, &mut watcher, &mut state, None);
            assert!(
                !child_process::clear_is_asked(),
                "a rebuild that printed nothing leaves no clear behind"
            );
            eprint_warning("a later line");
            return;
        }
        let printed = stderr_of_a_child_on_a_terminal(NAME);
        assert_eq!(printed.matches(CLEAR).count(), 1, "one clear:\n{printed:?}");
        assert!(
            printed.starts_with(CLEAR) && printed.ends_with("a later line\n"),
            "only the first rebuild's line is preceded by it:\n{printed:?}"
        );
    }

    /// #380: under `-o -` the compiled output on stdout is the rebuild's first output, also
    /// under `--quiet`: the clear is made before it, on stderr, and the rebuild prints
    /// nothing else.
    #[test]
    fn a_stdout_rebuild_clears_before_its_output() {
        const NAME: &str = "watch::tests::a_stdout_rebuild_clears_before_its_output";
        if child_process::is_child(NAME) {
            let (_dir, root) = canonical_tempdir();
            let entry = root.join("page.mds");
            std::fs::write(&entry, "Page body.\n").unwrap();
            let mut state = file_state_writing(&entry, None);
            crate::output::ask_clear();
            let _ = rebuild_file(&file_ctx(&entry), &mut idle_watcher(), &mut state, None);
            return;
        }
        let child = child_process::run_on_a_terminal(NAME);
        let (report, printed) = (
            String::from_utf8_lossy(&child.stdout),
            String::from_utf8_lossy(&child.stderr),
        );
        assert!(
            report.contains("running 1 test") && child.status.success(),
            "control: the child ran the test and it passed; stdout:\n{report}\nstderr:\n{printed}"
        );
        assert!(
            report.contains("Page body."),
            "control: the compiled output reached stdout:\n{report}"
        );
        assert_eq!(printed, CLEAR, "the clear, and nothing else, on stderr");
    }

    /// #380: a rebuild no hold holds back that reports a failure — a `--vars` file it cannot
    /// read, in either mode, or a compile that fails — makes the clear `--clear` asked for
    /// before its report: the report is never wiped.
    #[test]
    fn a_rebuild_that_reports_a_failure_makes_the_clear_first() {
        const NAME: &str = "watch::tests::a_rebuild_that_reports_a_failure_makes_the_clear_first";
        if child_process::is_child(NAME) {
            let (_dir, root) = canonical_tempdir();
            let (_out_dir, out) = canonical_tempdir();
            let (entry, vars) = (root.join("page.mds"), root.join("vars.json"));
            let mut watcher = idle_watcher();
            for failure in ["the --vars file", "the compile"] {
                std::fs::write(&entry, "Page {{v}}\n").unwrap();
                let vars_text = if failure == "the --vars file" {
                    r#"{"v": "#
                } else {
                    r#"{"w": "one"}"#
                };
                std::fs::write(&vars, vars_text).unwrap();
                let ctx = FileCompileCtx {
                    vars_path: Some(vars.clone()),
                    vars_path_typed: Some(vars.clone()),
                    quiet: false,
                    ..file_ctx(&entry)
                };
                let mut state = file_state([entry.clone(), vars.clone()].into_iter().collect());
                state.last_mtimes = snapshot_state(&state.foi);
                crate::output::ask_clear();
                let _ = rebuild_file(&ctx, &mut watcher, &mut state, None);
                assert!(
                    state.hold.deadline().is_none(),
                    "file mode, {failure}: control: nothing is held"
                );
                assert!(
                    !child_process::clear_is_asked(),
                    "file mode, {failure}: the rebuild that reports it made the clear"
                );
            }

            std::fs::write(&vars, r#"{"v": "#).unwrap();
            let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
            let ctx = DirWatchCtx {
                quiet: false,
                ..ctx
            };
            state.known_files.insert(entry.clone());
            crate::output::ask_clear();
            rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
            assert!(
                state.hold.deadline().is_none() && state.held.vars_changed,
                "directory mode: control: the batch is kept for the next, not held"
            );
            assert!(
                !child_process::clear_is_asked(),
                "directory mode, the --vars file: the batch that reports it made the clear"
            );
            return;
        }
        let printed = stderr_of_a_child_on_a_terminal(NAME);
        let shown: Vec<&str> = printed.split(CLEAR).collect();
        assert!(
            shown.len() == 4 && shown[0].is_empty() && shown[1..].iter().all(|r| !r.is_empty()),
            "each of the three failures is reported after a clear of its own:\n{printed:?}"
        );
    }

    /// A directory with the sources `a.mds` and `x.mds` written and known, and a baseline:
    /// `(root, out, context, state)`, the context printing (not quiet) and `--clear` as
    /// asked.
    fn dir_session_of_two_sources(
        clear: bool,
    ) -> (
        (tempfile::TempDir, tempfile::TempDir),
        PathBuf,
        DirWatchCtx,
        DirWatchState,
    ) {
        let (root_dir, root) = canonical_tempdir();
        let (out_dir, out) = canonical_tempdir();
        std::fs::write(root.join("a.mds"), "A one\n").unwrap();
        std::fs::write(root.join("x.mds"), "X one\n").unwrap();
        let ctx = DirWatchCtx {
            clear,
            quiet: false,
            ..dir_ctx(&root, &out)
        };
        let mut state = empty_dir_state();
        state
            .known_files
            .extend([root.join("a.mds"), root.join("x.mds")]);
        state.last_mtimes = snapshot_state(&state.watched_set());
        ((root_dir, out_dir), root, ctx, state)
    }

    /// #380: the clear `--clear` asked for comes before the first thing a directory batch
    /// prints — a compile warning included — and is made once, whichever source prints.
    #[test]
    fn a_directory_batch_prints_its_compile_warning_after_the_clear() {
        const NAME: &str =
            "watch::tests::a_directory_batch_prints_its_compile_warning_after_the_clear";
        if child_process::is_child(NAME) {
            let (_dirs, root, ctx, mut state) = dir_session_of_two_sources(true);
            let a = page_with_a_warning(&root, "a.mds");
            let (_tx, rx) = mpsc::channel::<Msg>();
            let outcome =
                handle_fs_event_dir(modify_event(a.to_str().unwrap()), &ctx, &rx, &mut state);
            assert!(
                matches!(outcome, DirEventOutcome::Done),
                "control: it rebuilds"
            );
            return;
        }
        let printed = stderr_of_a_child_on_a_terminal(NAME);
        assert!(
            printed.starts_with(CLEAR),
            "the clear is the first thing the batch prints:\n{printed:?}"
        );
        assert_eq!(printed.matches(CLEAR).count(), 1, "made once:\n{printed:?}");
        let (warning, recompiled) = (printed.find("warning:"), printed.find("Recompiled"));
        assert!(
            warning.is_some() && warning < recompiled,
            "control: the warning is printed, before the Recompiled line:\n{printed:?}"
        );
    }

    /// #380: a directory batch held while a watched file is empty prints nothing, the clear
    /// its event asked for under `--clear` included: it leaves that clear to the batch that
    /// ends the hold, which makes it before its first line.
    #[test]
    fn a_held_directory_batch_leaves_the_clear_to_the_batch_that_ends_the_hold() {
        const NAME: &str =
            "watch::tests::a_held_directory_batch_leaves_the_clear_to_the_batch_that_ends_the_hold";
        if child_process::is_child(NAME) {
            let (_dirs, root, ctx, mut state) = dir_session_of_two_sources(true);
            let (a, x) = (root.join("a.mds"), root.join("x.mds"));

            // x emptied: the batch of a's event is held.
            std::fs::write(&x, "").unwrap();
            let (_tx, rx) = mpsc::channel::<Msg>();
            let outcome =
                handle_fs_event_dir(modify_event(a.to_str().unwrap()), &ctx, &rx, &mut state);
            assert!(
                matches!(outcome, DirEventOutcome::Done) && state.hold.deadline().is_some(),
                "control: the event's batch is held"
            );
            assert!(
                child_process::clear_is_asked(),
                "the held batch printed nothing and leaves the clear its event asked for"
            );

            // x written: the next batch ends the hold.
            std::fs::write(&x, "X two\n").unwrap();
            rebuild_dir_batch(&ctx, &BTreeSet::new(), false, &mut state, None);
            assert_eq!(state.hold.deadline(), None, "control: the hold ends");
            assert!(
                !child_process::clear_is_asked(),
                "the batch that ends the hold made the clear"
            );
            return;
        }
        let printed = stderr_of_a_child_on_a_terminal(NAME);
        assert!(
            printed.starts_with(CLEAR) && printed.matches(CLEAR).count() == 1,
            "one clear, before the first line of the batch that ends the hold:\n{printed:?}"
        );
        assert!(
            printed.contains("Recompiled"),
            "control: that batch printed:\n{printed:?}"
        );
    }

    /// #380: a directory batch that prints nothing, and is not held, leaves no clear
    /// behind: a line printed after it is not preceded by the clear it asked for.
    #[test]
    fn a_directory_batch_that_prints_nothing_leaves_no_clear_behind() {
        const NAME: &str =
            "watch::tests::a_directory_batch_that_prints_nothing_leaves_no_clear_behind";
        if child_process::is_child(NAME) {
            let (_dirs, root, ctx, mut state) = dir_session_of_two_sources(true);
            let a = root.join("a.mds");
            let batch = BTreeSet::from([a]);
            crate::output::ask_clear();
            rebuild_dir_batch(&ctx, &batch, false, &mut state, None);
            assert!(
                !child_process::clear_is_asked(),
                "control: the first batch printed"
            );

            // The same outputs again: written nowhere, shown nothing.
            crate::output::ask_clear();
            rebuild_dir_batch(&ctx, &batch, false, &mut state, None);
            assert!(
                !child_process::clear_is_asked(),
                "a batch that printed nothing leaves no clear behind"
            );
            eprint_warning("a later line");
            return;
        }
        let printed = stderr_of_a_child_on_a_terminal(NAME);
        assert_eq!(printed.matches(CLEAR).count(), 1, "one clear:\n{printed:?}");
        assert!(
            printed.starts_with(CLEAR) && printed.ends_with("a later line\n"),
            "only the first batch's line is preceded by it:\n{printed:?}"
        );
    }

    /// #380: a directory event's batch asks for `--clear`'s clear only under `--clear`, and
    /// an event that rebuilds nothing asks for none: of two events that rebuild, the one
    /// without `--clear` prints its line with no clear before it, the one with `--clear`
    /// with one.
    #[test]
    fn a_directory_event_asks_for_the_clear_only_under_clear() {
        const NAME: &str = "watch::tests::a_directory_event_asks_for_the_clear_only_under_clear";
        if child_process::is_child(NAME) {
            let (_dirs, root, _ctx, _state) = dir_session_of_two_sources(false);
            let (a, other) = (root.join("a.mds"), root.join("other.txt"));
            for clear in [false, true] {
                let (_out_dir, out) = canonical_tempdir();
                let ctx = DirWatchCtx {
                    clear,
                    quiet: false,
                    ..dir_ctx(&root, &out)
                };
                let mut state = empty_dir_state();
                state.known_files.insert(a.clone());
                let (_tx, rx) = mpsc::channel::<Msg>();
                let skipped = handle_fs_event_dir(
                    modify_event(other.to_str().unwrap()),
                    &ctx,
                    &rx,
                    &mut state,
                );
                assert!(
                    matches!(skipped, DirEventOutcome::Skip) && !child_process::clear_is_asked(),
                    "--clear: {clear}: control: an event that rebuilds nothing asks for nothing"
                );
                let done =
                    handle_fs_event_dir(modify_event(a.to_str().unwrap()), &ctx, &rx, &mut state);
                assert!(
                    matches!(done, DirEventOutcome::Done),
                    "--clear: {clear}: control: the event rebuilds"
                );
            }
            return;
        }
        let printed = stderr_of_a_child_on_a_terminal(NAME);
        let shown: Vec<&str> = printed.split(CLEAR).collect();
        assert!(
            shown.len() == 2
                && shown[0].starts_with("Recompiled")
                && shown[1].starts_with("Recompiled"),
            "without --clear the line comes alone; with it, after one clear:\n{printed:?}"
        );
    }

    /// A watch that fails, as notify reports one the OS refused.
    fn refuse(_: &Path) -> notify::Result<()> {
        Err(notify::Error::generic("refused"))
    }

    /// #257: a directory whose watch keeps failing is reported once for as long as the
    /// failures last — the first is [`DirArm::Failed`], each after it with no watch of it
    /// succeeding in between [`DirArm::FailedAgain`] — and a watch that succeeds ends the
    /// run, so a failure after it is reported again. A directory held is not watched.
    #[test]
    fn a_directory_whose_watch_keeps_failing_is_reported_once_until_a_watch_succeeds() {
        let dir = Path::new("/elsewhere/lib");
        let (mut armed, mut failing) = (BTreeSet::new(), BTreeSet::new());

        let outcomes: Vec<DirArm> = (0..3)
            .map(|_| arm_dir(dir, &mut armed, &mut failing, refuse))
            .collect();
        assert!(
            matches!(
                outcomes.as_slice(),
                [DirArm::Failed(_), DirArm::FailedAgain, DirArm::FailedAgain]
            ),
            "the first failure is reported, the two after it are not: {outcomes:?}"
        );

        let armed_now = arm_dir(dir, &mut armed, &mut failing, |_| Ok(()));
        assert!(
            matches!(armed_now, DirArm::Armed),
            "control: a watch that succeeds: {armed_now:?}"
        );
        let mut asked = false;
        let held = arm_dir(dir, &mut armed, &mut failing, |_| {
            asked = true;
            Ok(())
        });
        assert!(
            matches!(held, DirArm::Held) && !asked,
            "a directory held is not watched: {held:?}"
        );

        // It vanished — the tick holds it no more — and its watch fails once more.
        armed.remove(dir);
        let again = arm_dir(dir, &mut armed, &mut failing, refuse);
        assert!(
            matches!(again, DirArm::Failed(_)),
            "a failure after a watch that succeeded is reported again: {again:?}"
        );
    }

    /// #257: a directory no source imports any more leaves its run of failed watches with
    /// it, so the import that brings it back reports its first failed watch again; while it
    /// stays imported, another failure is not reported.
    #[test]
    fn a_directory_imported_again_reports_its_failed_watch_again() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let ctx = dir_ctx(&root, &out);
        let dir = Path::new("/elsewhere/lib");
        let imported = BTreeSet::from([dir.to_path_buf()]);
        let mut liveness = idle_liveness();
        let mut watcher = RecordingWatcher::default();
        let arm = |liveness: &mut LivenessState| {
            arm_dir(
                dir,
                &mut liveness.armed_dirs,
                &mut liveness.failing_dirs,
                refuse,
            )
        };

        let first = arm(&mut liveness);
        unwatch_unimported_dirs(&ctx, &mut watcher, &mut liveness, &imported);
        let still = arm(&mut liveness);
        assert!(
            matches!((&first, &still), (DirArm::Failed(_), DirArm::FailedAgain)),
            "control: while it is imported, only the first failure is reported: \
             {first:?}, {still:?}"
        );

        // Its import edited away, then back.
        unwatch_unimported_dirs(&ctx, &mut watcher, &mut liveness, &BTreeSet::new());
        let back = arm(&mut liveness);
        assert!(
            matches!(back, DirArm::Failed(_)),
            "the directory imported again reports its failed watch again: {back:?}"
        );
    }

    /// #257: the idle tick's watch of a directory whose watch kept failing, once it
    /// succeeds, ends that run of failures as a rebuild's does: the next failed watch of
    /// it is reported.
    #[test]
    fn a_tick_that_arms_a_failing_directory_ends_its_run_of_failures() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (_ext_dir, ext) = canonical_tempdir();
        let ctx = dir_ctx(&root, &out);
        let mut state = empty_dir_state();
        state.external_dep_dirs.insert(ext.clone());
        let mut liveness = idle_liveness();
        let first = arm_dir(
            &ext,
            &mut liveness.armed_dirs,
            &mut liveness.failing_dirs,
            refuse,
        );
        assert!(
            matches!(first, DirArm::Failed(_)),
            "control: a rebuild's watch failed: {first:?}"
        );

        let mut watcher = RecordingWatcher::default();
        liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
        assert_eq!(
            watcher.calls,
            [WatchCall::Watch(ext.clone())],
            "control: the tick watches it, and the watch succeeds"
        );

        // It vanished — the tick holds it no more — and a rebuild's watch of it fails.
        liveness.armed_dirs.remove(&ext);
        let again = arm_dir(
            &ext,
            &mut liveness.armed_dirs,
            &mut liveness.failing_dirs,
            refuse,
        );
        assert!(
            matches!(again, DirArm::Failed(_)),
            "a failure after the tick's watch succeeded is reported: {again:?}"
        );
    }

    /// #380: an idle tick rebuilds with a `--vars` edit whose event was lost — to an inotify
    /// queue overflow, or to an FSEvents stream restart — as it does with a source's: its
    /// content check looks at the `--vars` file too, and a change it finds there recompiles
    /// every source against the file as it then reads.
    #[test]
    fn an_idle_tick_rebuilds_with_a_vars_edit_whose_event_was_lost() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (_vars_dir, vars_dir) = canonical_tempdir();
        let vars = vars_dir.join("vars.json");
        let a = root.join("a.mds");
        std::fs::write(&a, "A {{v}}\n").unwrap();
        std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
        let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
        state.known_files.insert(a.clone());
        rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
        let read = || std::fs::read_to_string(out.join("a.md")).ok();
        assert!(
            read().is_some_and(|text| text.contains("A one")),
            "control: the source is compiled with the vars file; out/a.md: {:?}",
            read()
        );

        // The vars file edited, to a new size, and no event delivered.
        std::fs::write(&vars, r#"{"v": "two, longer"}"#).unwrap();
        let mut watcher = RecordingWatcher::default();
        liveness_probe_dir(&ctx, &mut watcher, &mut idle_liveness(), &mut state);

        assert!(
            read().is_some_and(|text| text.contains("A two, longer")),
            "the tick rebuilds with the vars file as it now reads; out/a.md: {:?}",
            read()
        );
    }

    /// #380: the `--vars` file's event rebuilds wherever the file is — in a hidden directory
    /// or `node_modules/` below the root, or below the out-dir — though every other path's
    /// event there is dropped: every compile reads the file all the same.
    #[test]
    fn a_vars_file_s_event_rebuilds_where_other_paths_events_are_dropped() {
        for place in [".config", "node_modules", "the out-dir"] {
            let (_root_dir, root) = canonical_tempdir();
            let (_out_dir, out) = canonical_tempdir();
            let (vars_dir, inside_root) = match place {
                "the out-dir" => (out.clone(), false),
                hidden => (root.join(hidden), true),
            };
            std::fs::create_dir_all(&vars_dir).unwrap();
            let vars = vars_dir.join("vars.json");
            let a = root.join("a.mds");
            std::fs::write(&a, "A {{v}}\n").unwrap();
            std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
            let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
            let ctx = DirWatchCtx {
                vars_dir_extra: (!inside_root).then(|| vars_dir.clone()),
                ..ctx
            };
            state.known_files.insert(a.clone());
            rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
            let read = || std::fs::read_to_string(out.join("a.md")).ok();
            assert!(
                read().is_some_and(|text| text.contains("A one")),
                "{place}: control: the source is compiled; out/a.md: {:?}",
                read()
            );
            let (_tx, rx) = mpsc::channel::<Msg>();
            let beside = vars_dir.join("beside.mds");
            std::fs::write(&beside, "Beside.\n").unwrap();
            let outcome = handle_fs_event_dir(
                modify_event(beside.to_str().unwrap()),
                &ctx,
                &rx,
                &mut state,
            );
            assert!(
                matches!(outcome, DirEventOutcome::Skip),
                "{place}: positive control: a source's event there is dropped"
            );

            std::fs::write(&vars, r#"{"v": "two"}"#).unwrap();
            let outcome =
                handle_fs_event_dir(modify_event(vars.to_str().unwrap()), &ctx, &rx, &mut state);

            assert!(
                matches!(outcome, DirEventOutcome::Done),
                "{place}: the vars file's event rebuilds"
            );
            assert!(
                read().is_some_and(|text| text.contains("A two")),
                "{place}: with the vars file as it now reads; out/a.md: {:?}",
                read()
            );
        }
    }

    /// #380: a dependency below the root that is no source — a `type: mds` `.md` module a
    /// source `@include`s, or one whose function a source calls — edited, with no event
    /// delivered, reaches a batch through the idle tick's content check. That batch
    /// rebuilds its importers and never compiles the module as a source: no
    /// output is written for it, and it is neither known nor errored.
    #[test]
    fn an_idle_tick_rebuilds_the_importers_of_a_changed_module_never_the_module() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let notes = root.join("notes");
        std::fs::create_dir(&notes).unwrap();
        let (a, b) = (root.join("a.mds"), root.join("b.mds"));
        let (inc, lib) = (notes.join("inc.md"), notes.join("lib.md"));
        std::fs::write(&a, "@import \"./notes/inc.md\" as inc\nA.\n@include inc\n").unwrap();
        std::fs::write(&b, "@import \"./notes/lib.md\" as lib\nB {{lib.hi()}}\n").unwrap();
        std::fs::write(&inc, "---\ntype: mds\n---\nIncluded one\n").unwrap();
        std::fs::write(&lib, "---\ntype: mds\n---\n@define hi():\nLib one\n@end\n").unwrap();
        let ctx = dir_ctx(&root, &out);
        let mut state = empty_dir_state();
        state.known_files.extend([a.clone(), b.clone()]);
        let sources = BTreeSet::from([a.clone(), b.clone()]);
        rebuild_dir_batch(&ctx, &sources, false, &mut state, None);
        let read = |rel: &Path| std::fs::read_to_string(out.join(rel)).ok();
        let tracked = state.tracked_set();
        assert!(
            read(Path::new("a.md")).is_some_and(|text| text.contains("Included one"))
                && read(Path::new("b.md")).is_some_and(|text| text.contains("B Lib one"))
                && tracked.contains(&inc)
                && tracked.contains(&lib),
            "control: both importers are compiled and both modules are tracked, so the \
             tick's content check looks at them; out/a.md: {:?}, out/b.md: {:?}, \
             tracked: {tracked:?}",
            read(Path::new("a.md")),
            read(Path::new("b.md"))
        );

        // Both modules edited, each to a new size, and no event delivered.
        std::fs::write(&inc, "---\ntype: mds\n---\nIncluded two, longer\n").unwrap();
        std::fs::write(
            &lib,
            "---\ntype: mds\n---\n@define hi():\nLib two, longer\n@end\n",
        )
        .unwrap();
        let mut watcher =
            RecommendedWatcher::new(|_: notify::Result<Event>| {}, notify::Config::default())
                .unwrap();
        liveness_probe_dir(&ctx, &mut watcher, &mut idle_liveness(), &mut state);

        assert!(
            read(Path::new("a.md")).is_some_and(|text| text.contains("Included two, longer")),
            "positive control: the tick rebuilds the module's importer; out/a.md: {:?}",
            read(Path::new("a.md"))
        );
        assert!(
            read(Path::new("b.md")).is_some_and(|text| text.contains("B Lib two, longer")),
            "positive control: the tick rebuilds the importer of the module whose function \
             it calls; out/b.md: {:?}",
            read(Path::new("b.md"))
        );
        for module in [&inc, &lib] {
            // Where its output would be written had it been compiled as a source.
            let rel = module.strip_prefix(&root).unwrap();
            assert_eq!(
                read(rel),
                None,
                "{}: a module that is no source is never compiled as one",
                rel.display()
            );
            assert!(
                !state.known_files.contains(module) && !state.errored.contains(module),
                "{}: neither known nor errored; known: {:?}, errored: {:?}",
                rel.display(),
                state.known_files,
                state.errored
            );
        }
    }

    /// #380: a dependency below the root edited into a plain `.md` — no MDS file at all —
    /// and found by the idle tick's content check is refused through its importer, whose
    /// import now fails, and never compiled as a source of its own: it is not errored.
    #[test]
    fn an_idle_tick_refuses_a_plain_md_dependency_only_through_its_importer() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let notes = root.join("notes");
        std::fs::create_dir(&notes).unwrap();
        let a = root.join("a.mds");
        let inc = notes.join("inc.md");
        std::fs::write(&a, "@import \"./notes/inc.md\" as inc\nA.\n@include inc\n").unwrap();
        std::fs::write(&inc, "---\ntype: mds\n---\nIncluded one\n").unwrap();
        let ctx = dir_ctx(&root, &out);
        let mut state = empty_dir_state();
        state.known_files.insert(a.clone());
        rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
        assert!(
            state.tracked_set().contains(&inc) && state.errored.is_empty(),
            "control: the importer compiled and the module is tracked; errored: {:?}",
            state.errored
        );

        // Its frontmatter dropped, at a new size, and no event delivered.
        std::fs::write(&inc, "Plain text now, with no frontmatter at all\n").unwrap();
        let mut watcher =
            RecommendedWatcher::new(|_: notify::Result<Event>| {}, notify::Config::default())
                .unwrap();
        liveness_probe_dir(&ctx, &mut watcher, &mut idle_liveness(), &mut state);

        assert!(
            state.errored.contains(&a),
            "positive control: the tick rebuilds the importer, whose import is refused; \
             errored: {:?}",
            state.errored
        );
        assert!(
            !state.errored.contains(&inc) && !state.known_files.contains(&inc),
            "the plain `.md` is no source, so it is never compiled as one; errored: {:?}, \
             known: {:?}",
            state.errored,
            state.known_files
        );
    }

    /// #380: an event names a rebuild for a `.md` file only when a source imports it — a
    /// `README.md` beside the sources, or an output written next to its source, rebuilds
    /// nothing — and the rebuild it names is of the importers, never of the module.
    #[test]
    fn an_event_for_an_md_file_rebuilds_only_when_a_source_imports_it() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (a, inc, readme) = (
            root.join("a.mds"),
            root.join("inc.md"),
            root.join("README.md"),
        );
        std::fs::write(&a, "@import \"./inc.md\" as inc\nA.\n@include inc\n").unwrap();
        std::fs::write(&inc, "---\ntype: mds\n---\nIncluded one\n").unwrap();
        std::fs::write(&readme, "Notes\n").unwrap();
        let ctx = dir_ctx(&root, &out);
        let mut state = empty_dir_state();
        state.known_files.insert(a.clone());
        rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
        let (_tx, rx) = mpsc::channel::<Msg>();

        let outcome = handle_fs_event_dir(
            modify_event(readme.to_str().unwrap()),
            &ctx,
            &rx,
            &mut state,
        );
        assert!(
            matches!(outcome, DirEventOutcome::Skip),
            "a file no source imports names no rebuild"
        );

        std::fs::write(&inc, "---\ntype: mds\n---\nIncluded two\n").unwrap();
        let outcome =
            handle_fs_event_dir(modify_event(inc.to_str().unwrap()), &ctx, &rx, &mut state);
        assert!(
            matches!(outcome, DirEventOutcome::Done),
            "positive control: a module a source imports names one"
        );
        let read = |name: &str| std::fs::read_to_string(out.join(name)).ok();
        assert!(
            read("a.md").is_some_and(|text| text.contains("Included two")),
            "its importer is rebuilt; out/a.md: {:?}",
            read("a.md")
        );
        assert_eq!(
            read("inc.md"),
            None,
            "the module is never compiled as a source"
        );
    }

    /// An event that says events were lost: what inotify reports for an overflowed queue
    /// and FSEvents for `MustScanSubDirs`. It names no path.
    fn rescan_event() -> Msg {
        Msg::Fs(Ok(
            notify::Event::new(notify::EventKind::Other).set_flag(notify::event::Flag::Rescan)
        ))
    }

    /// #257: an event that says events were lost makes a directory watch look for what they
    /// would have said, with the idle tick off: a source created meanwhile is compiled, and a
    /// `--vars` edit meanwhile is rebuilt with. It does, whether the event starts the batch
    /// or arrives in its debounce window. An event that names no path and says nothing of
    /// lost events rebuilds nothing.
    #[test]
    fn a_rescan_event_finds_what_the_lost_events_would_have_said() {
        let unflagged = || Msg::Fs(Ok(notify::Event::new(notify::EventKind::Other)));
        for (debounce_ms, place) in [(0, "the event itself"), (20, "an event of the window")] {
            let (_root_dir, root) = canonical_tempdir();
            let (_out_dir, out) = canonical_tempdir();
            let (_vars_dir, vars_dir) = canonical_tempdir();
            let vars = vars_dir.join("vars.json");
            let (a, created) = (root.join("a.mds"), root.join("created.mds"));
            std::fs::write(&a, "A {{v}}\n").unwrap();
            std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
            let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
            let ctx = DirWatchCtx { debounce_ms, ..ctx };
            state.known_files.insert(a.clone());
            rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
            let read = |name: &str| std::fs::read_to_string(out.join(name)).ok();
            assert!(
                read("a.md").is_some_and(|text| text.contains("A one")),
                "{place}: control: the source is compiled; out/a.md: {:?}",
                read("a.md")
            );

            // Both changes made with their events lost: nothing names them.
            std::fs::write(&created, "Created {{v}}\n").unwrap();
            std::fs::write(&vars, r#"{"v": "two, longer"}"#).unwrap();
            let (tx, rx) = mpsc::channel::<Msg>();
            if debounce_ms > 0 {
                tx.send(unflagged()).unwrap();
            }
            let outcome = handle_fs_event_dir(unflagged(), &ctx, &rx, &mut state);
            assert!(
                matches!(outcome, DirEventOutcome::Skip) && read("created.md").is_none(),
                "{place}: control: events that name no path and say nothing of lost events \
                 rebuild nothing; out/created.md: {:?}",
                read("created.md")
            );

            let first = if debounce_ms > 0 {
                tx.send(rescan_event()).unwrap();
                unflagged()
            } else {
                rescan_event()
            };
            let outcome = handle_fs_event_dir(first, &ctx, &rx, &mut state);
            assert!(
                matches!(outcome, DirEventOutcome::Done),
                "{place}: the rescan event rebuilds"
            );
            assert!(
                read("created.md").is_some_and(|text| text.contains("Created two, longer")),
                "{place}: the source created meanwhile is compiled; out/created.md: {:?}",
                read("created.md")
            );
            assert!(
                read("a.md").is_some_and(|text| text.contains("A two, longer")),
                "{place}: the vars edit made meanwhile is rebuilt with; out/a.md: {:?}",
                read("a.md")
            );
            assert!(
                state.known_files.contains(&created),
                "{place}: the source created meanwhile is known: {:?}",
                state.known_files
            );
        }
    }

    /// #380: a file rebuild whose compile read a file of interest emptied after the
    /// rebuild first looked — a truncation that began between the two — is held, not
    /// published, and leaves the baseline as it was. Nothing pauses a file rebuild
    /// between its look and its compile, so the included module is left out of the files
    /// the look stats while the baseline still holds a stamp that saw its bytes.
    /// Positive control: a baseline that saw it empty publishes the same compile.
    #[test]
    fn a_file_rebuild_whose_compile_read_a_file_emptied_since_its_look_is_held() {
        let (_dir, root) = canonical_tempdir();
        let entry = root.join("page.mds");
        let module = root.join("_inc.mds");
        let out = root.join("page.md");
        std::fs::write(
            &entry,
            "@import \"./_inc.mds\" as inc\nPage.\n@include inc\n",
        )
        .unwrap();
        std::fs::write(&module, "").unwrap();
        let ctx = FileCompileCtx {
            entry: WatchedPath {
                typed: entry.clone(),
                canonical: entry.clone(),
                what: Watched::Entry,
            },
            working_dir: WorkingDir { canonical: None },
            vars_path: None,
            vars_path_typed: None,
            reads: Vec::new(),
            static_set_vars: Vec::new(),
            static_set_string_vars: Vec::new(),
            quiet: true,
        };
        let mut watcher =
            RecommendedWatcher::new(|_: notify::Result<Event>| {}, notify::Config::default())
                .unwrap();

        for (seen, held) in [(Some(9), true), (Some(0), false)] {
            let _ = std::fs::remove_file(&out);
            let mut state = file_state(std::iter::once(entry.clone()).collect());
            state.output = OutputRoute::Named(Some(WriteTarget::as_typed(out.clone())));
            state.last_mtimes = snapshot_state(&state.foi);
            state.last_mtimes.insert(module.clone(), (None, seen));
            let before = state.last_mtimes.clone();

            let _ = rebuild_file(&ctx, &mut watcher, &mut state, None);

            let written = std::fs::read_to_string(&out).ok();
            if held {
                assert_eq!(
                    written, None,
                    "a compile that read a file emptied since the look is held, not published"
                );
                assert!(state.hold.deadline().is_some(), "a hold of its own is set");
                assert_eq!(state.last_mtimes, before, "the baseline is left as it was");
            } else {
                assert!(
                    written
                        .as_deref()
                        .is_some_and(|text| text.contains("Page.")),
                    "positive control: a file the baseline saw empty is no file emptied; \
                     page.md: {written:?}"
                );
                assert_eq!(state.hold.deadline(), None, "nothing is held");
            }
        }
    }

    /// File mode's rebuild context for `entry`: no `--vars`, quiet.
    fn file_ctx(entry: &Path) -> FileCompileCtx {
        FileCompileCtx {
            entry: WatchedPath {
                typed: entry.to_path_buf(),
                canonical: entry.to_path_buf(),
                what: Watched::Entry,
            },
            working_dir: WorkingDir { canonical: None },
            vars_path: None,
            vars_path_typed: None,
            reads: Vec::new(),
            static_set_vars: Vec::new(),
            static_set_string_vars: Vec::new(),
            quiet: true,
        }
    }

    /// #380: a rebuild takes the stamps its look took as its baseline, in both modes: a
    /// baseline that saw a watched file otherwise — a change the tick found, or an edit whose
    /// event came — holds what the look saw once the rebuild is done, so the idle tick does
    /// not find the same change again.
    #[test]
    fn a_rebuild_takes_its_look_s_stamps_as_its_baseline() {
        let stale: FileStamp = (None, Some(99));

        // File mode.
        let (_dir, root) = canonical_tempdir();
        let entry = root.join("page.mds");
        let out = root.join("page.md");
        std::fs::write(&entry, "Page.\n").unwrap();
        let mut watcher =
            RecommendedWatcher::new(|_: notify::Result<Event>| {}, notify::Config::default())
                .unwrap();
        let mut state = file_state(std::iter::once(entry.clone()).collect());
        state.output = OutputRoute::Named(Some(WriteTarget::as_typed(out.clone())));
        state.last_mtimes.insert(entry.clone(), stale);
        let _ = rebuild_file(&file_ctx(&entry), &mut watcher, &mut state, None);
        assert!(
            std::fs::read_to_string(&out).is_ok_and(|text| text.contains("Page.")),
            "control: the rebuild ran"
        );
        assert_eq!(
            state.last_mtimes.get(&entry),
            Some(&stamp_now(&entry)),
            "file mode: the look's stamp, not the one the baseline held"
        );

        // Directory mode.
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (ctx, mut state) = two_compiled_sources(&root, &out);
        let a = root.join("a.mds");
        state.last_mtimes.insert(a.clone(), stale);
        rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
        assert_eq!(
            state.last_mtimes.get(&a),
            Some(&stamp_now(&a)),
            "directory mode: the look's stamp, not the one the baseline held"
        );
    }

    /// #380: a directory source whose compile read a file emptied since the batch looked is
    /// held alone — nothing written, the source kept to be rebuilt — and the batch that
    /// ends the hold rebuilds it. Nothing pauses a release build between a batch's look
    /// and its compile (`tests/cli_watch_truncate.rs` uses the debug build's pause), and the
    /// look stamps every source the batch names, so the file is a module the source
    /// includes — one the look does not stat, its compile discovering it — whose baseline
    /// stamp saw bytes.
    #[test]
    fn a_directory_source_whose_compile_read_a_file_emptied_since_the_look_is_held() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (page, module) = (root.join("page.mds"), root.join("_inc.mds"));
        std::fs::write(
            &page,
            "@import \"./_inc.mds\" as inc\nPage.\n@include inc\n",
        )
        .unwrap();
        std::fs::write(&module, "").unwrap();
        let ctx = dir_ctx(&root, &out);
        let mut state = empty_dir_state();
        state.last_mtimes.insert(module.clone(), (None, Some(9)));

        rebuild_dir_batch(
            &ctx,
            &BTreeSet::from([page.clone()]),
            false,
            &mut state,
            None,
        );
        assert_eq!(
            std::fs::read_to_string(out.join("page.md")).ok(),
            None,
            "a compile that read a file emptied since the look is held, not published"
        );
        assert!(state.hold.deadline().is_some(), "a hold of its own is set");
        assert!(state.held.paths.contains(&page), "{:?}", state.held);

        // The module is written whole with the page's save: the file the held compile read
        // empty stays in the baseline until it is, and would hold the next batch itself.
        std::fs::write(&module, "Inc.\n").unwrap();
        std::fs::write(&page, "Page two\n").unwrap();
        rebuild_dir_batch(&ctx, &BTreeSet::new(), false, &mut state, None);
        assert!(
            std::fs::read_to_string(out.join("page.md"))
                .is_ok_and(|text| text.contains("Page two")),
            "the batch that ends the hold rebuilds the source held"
        );
        assert_eq!(state.hold.deadline(), None, "the hold has ended");
    }

    /// #380: a source a directory batch names before any compile of it has succeeded keeps,
    /// while the batch holds it, the stamp the batch's look took: emptied before the hold
    /// ends — its event lost, or not come yet — it is found emptied by the next batch's look,
    /// which holds again at the same deadline, and is never published empty; written, it is
    /// published by the batch that finds it so. Its compile is held by a module it includes,
    /// read emptied, which the look does not stat (as in
    /// `a_directory_source_whose_compile_read_a_file_emptied_since_the_look_is_held`).
    #[test]
    fn a_new_source_held_and_emptied_before_the_hold_ends_is_held_again() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (page, module) = (root.join("page.mds"), root.join("_inc.mds"));
        std::fs::write(
            &page,
            "@import \"./_inc.mds\" as inc\nPage.\n@include inc\n",
        )
        .unwrap();
        std::fs::write(&module, "").unwrap();
        let ctx = dir_ctx(&root, &out);
        let mut state = empty_dir_state();
        state.last_mtimes.insert(module.clone(), (None, Some(9)));
        let read = || std::fs::read_to_string(out.join("page.md")).ok();

        rebuild_dir_batch(
            &ctx,
            &BTreeSet::from([page.clone()]),
            false,
            &mut state,
            None,
        );
        let deadline = state.hold.deadline();
        assert!(
            deadline.is_some() && state.held.paths.contains(&page),
            "control: page's compile is held; {:?}",
            state.held
        );

        // The module is written whole: the file the held compile read empty stays in the
        // baseline until it is, and would hold the next batches itself. Only page is empty
        // from here, so it alone holds them.
        std::fs::write(&module, "Inc.\n").unwrap();

        // page emptied, its event lost: a batch with nothing new.
        std::fs::write(&page, "").unwrap();
        rebuild_dir_batch(&ctx, &BTreeSet::new(), false, &mut state, None);
        assert_eq!(
            read(),
            None,
            "a held source emptied before the hold ends is held, not published empty"
        );
        assert_eq!(
            state.hold.deadline(),
            deadline,
            "it is held again at the same deadline"
        );

        std::fs::write(&page, "Page two\n").unwrap();
        rebuild_dir_batch(&ctx, &BTreeSet::new(), false, &mut state, None);
        assert!(
            read().is_some_and(|text| text.contains("Page two")),
            "positive control: the batch that finds it written publishes it; \
             out/page.md: {:?}",
            read()
        );
        assert_eq!(state.hold.deadline(), None, "the hold has ended");
    }

    /// #380: a directory batch whose `--vars` file cannot be read keeps what it named for the
    /// next batch, with the stamps its look took of the files the run reads. A `.mds` file in
    /// the directory of a dependency outside the root that no source imports is read by
    /// nothing: its event names it, but its emptying holds nothing, and the next batch
    /// compiles at once. A source the failed batch named, which no compile has read yet, is
    /// read by the run: emptied, it holds the next batch (the control).
    #[test]
    fn a_file_nothing_reads_named_by_a_batch_its_vars_file_failed_holds_nothing_when_emptied() {
        for (label, read_by_the_run) in [("a new source", true), ("a file nothing reads", false)] {
            let CrossRootPage {
                dirs: _dirs,
                base: _,
                out,
                page: _,
                module: _,
                shared,
                vars,
                ctx,
                mut state,
            } = cross_root_page();
            let named = if read_by_the_run {
                ctx.root.canonical.join("n.mds")
            } else {
                shared.join("unread.mds")
            };
            let batch = BTreeSet::from([named.clone()]);
            std::fs::write(&named, "Named\n").unwrap();
            std::fs::write(&vars, "{").unwrap();
            rebuild_dir_batch(&ctx, &batch, false, &mut state, None);
            assert!(
                state.held.paths.contains(&named) && state.hold.deadline().is_none(),
                "{label}: control: the batch the vars file could not be read for keeps what it \
                 named, and holds nothing; {:?}",
                state.held
            );

            // Emptied, and the vars file written again with a new value: one batch of both.
            std::fs::write(&named, "").unwrap();
            std::fs::write(&vars, r#"{"v": "two"}"#).unwrap();
            rebuild_dir_batch(&ctx, &batch, true, &mut state, None);
            let page_md = std::fs::read_to_string(out.join("page.md")).ok();
            if read_by_the_run {
                assert!(
                    state.hold.deadline().is_some()
                        && page_md.as_deref().is_some_and(|text| !text.contains("two")),
                    "{label}: positive control: emptied, it holds the batch; out/page.md: \
                     {page_md:?}"
                );
            } else {
                assert_eq!(
                    state.hold.deadline(),
                    None,
                    "{label}: emptied, it holds nothing"
                );
                assert!(
                    page_md.as_deref().is_some_and(|text| text.contains("two")),
                    "{label}: the batch compiles at once; out/page.md: {page_md:?}"
                );
            }
        }
    }

    /// #380: a dependency outside the root that a batch names, and a source of the same
    /// batch imports for the first time, is stamped by the batch's look — whatever the run
    /// reads, a named path included — so a truncation that begins between the look and the
    /// source's read holds the source back as the look would have: the empty read is not
    /// written, and the source is kept for the batch that ends the hold. The debug build's
    /// pause after a batch's look (`MDS_TEST_PAUSE_AFTER_LOOK`) makes the window certain;
    /// the variable is the process's, so the test runs in a child of its own.
    #[cfg(debug_assertions)]
    #[test]
    fn a_dependency_outside_the_root_a_batch_names_is_held_when_truncated_after_the_look() {
        const NAME: &str = "watch::tests::\
            a_dependency_outside_the_root_a_batch_names_is_held_when_truncated_after_the_look";
        if child_process::is_child(NAME) {
            let CrossRootPage {
                dirs: _dirs,
                out,
                page,
                shared,
                ctx,
                mut state,
                ..
            } = cross_root_page();
            let output = out.join("page.md");
            let before = std::fs::read_to_string(&output).unwrap();

            // The source imports a file beside the root it has never imported: both are
            // named by the batch, and the file is full when the batch looks.
            let dependency = shared.join("_y.mds");
            std::fs::write(&page, "@import \"../shared/_y.mds\" as y\n@include y\n").unwrap();
            std::fs::write(&dependency, "Y one\n").unwrap();
            let batch = BTreeSet::from([page.clone(), dependency.clone()]);

            // Outside every watched directory. The batch stops after its look; the file is
            // truncated while it is stopped, and the batch goes on.
            let (_gate_dir, gate) = canonical_tempdir();
            let (go, paused) = (gate.join("go"), gate.join("go.paused"));
            std::env::set_var(batch_pause_trigger::LOOK_VARIABLE, &go);
            let truncating = std::thread::spawn({
                let (dependency, go) = (dependency.clone(), go.clone());
                move || {
                    // Bounded: at most 2000 looks, ten seconds.
                    let stopped = (0..2_000).any(|_| {
                        std::thread::sleep(Duration::from_millis(5));
                        paused.exists()
                    });
                    std::fs::File::create(&dependency).unwrap();
                    std::fs::write(&go, "").unwrap();
                    stopped
                }
            });
            rebuild_dir_batch(&ctx, &batch, false, &mut state, None);
            assert!(
                truncating.join().unwrap(),
                "control: the batch stopped after its look"
            );

            assert_eq!(
                std::fs::read_to_string(&output).unwrap(),
                before,
                "a dependency truncated after the batch's look: the empty read is not written"
            );
            assert!(
                state.held.paths.contains(&page) && state.hold.deadline().is_some(),
                "the source is held for the batch that ends the hold; {:?}",
                state.held
            );

            // The file written again: the next batch compiles what was written.
            std::fs::write(&dependency, "Y two\n").unwrap();
            rebuild_dir_batch(&ctx, &BTreeSet::from([dependency]), false, &mut state, None);
            assert_eq!(
                std::fs::read_to_string(&output).unwrap(),
                "Y two\n",
                "positive control: the batch after the write publishes it"
            );
            assert!(
                state.held.paths.is_empty(),
                "the hold has ended; {:?}",
                state.held
            );
            return;
        }
        let child = child_process::run(NAME);
        let report = String::from_utf8_lossy(&child.stdout).into_owned();
        let printed = String::from_utf8_lossy(&child.stderr).into_owned();
        assert!(
            report.contains("running 1 test"),
            "control: the child ran the test; stdout:\n{report}"
        );
        assert!(
            child.status.success(),
            "the child's test passes; stdout:\n{report}\nstderr:\n{printed}"
        );
    }

    /// #380: a file found emptied after a rebuild looked holds it as the look would have —
    /// at a deadline set by the first such finding and never moved — unless the deadline
    /// ended the hold in this rebuild, which compiles the files as they are. The rebuild
    /// after that decides afresh.
    #[test]
    fn empty_hold_holds_a_late_finding_unless_the_deadline_ended_it() {
        let t0 = Instant::now();
        let mut hold = EmptyHold::default();
        assert_eq!(hold.on_rebuild(false, t0), HoldVerdict::Compile);
        assert_eq!(
            hold.on_late_empty(t0 + ms(1)),
            HoldVerdict::Hold,
            "found after a look that found nothing"
        );
        let deadline = t0 + ms(1) + EMPTY_HOLD_DEADLINE;
        assert_eq!(hold.deadline(), Some(deadline));
        assert_eq!(hold.on_late_empty(t0 + ms(100)), HoldVerdict::Hold);
        assert_eq!(
            hold.deadline(),
            Some(deadline),
            "a later finding must not move the deadline"
        );

        // The deadline's rebuild: compiled as the files are, and never held again.
        assert_eq!(hold.on_rebuild(true, deadline), HoldVerdict::Compile);
        assert_eq!(
            hold.on_late_empty(deadline + ms(1)),
            HoldVerdict::Compile,
            "a rebuild the deadline runs compiles the files as they are"
        );
        assert_eq!(hold.deadline(), None, "and leaves nothing held");

        // The next rebuild decides afresh: a later truncation holds on a deadline of its
        // own, and a rebuild that finds nothing ends it.
        assert_eq!(hold.on_rebuild(true, deadline + ms(10)), HoldVerdict::Hold);
        assert_eq!(
            hold.deadline(),
            Some(deadline + ms(10) + EMPTY_HOLD_DEADLINE)
        );
        assert_eq!(
            hold.on_rebuild(false, deadline + ms(20)),
            HoldVerdict::Compile
        );
        assert_eq!(hold.deadline(), None);
    }

    /// #380: the rebuild a hold's deadline runs decides at an instant no earlier than that
    /// deadline, so it ends the hold even when the clock reads earlier — a clock that steps
    /// back between the wake and the rebuild. An event's or a tick's rebuild takes the
    /// clock as it reads.
    #[test]
    fn a_deadline_rebuild_ends_its_hold_whatever_the_clock_reads() {
        let deadline = Instant::now() + EMPTY_HOLD_DEADLINE;
        let behind = deadline - ms(5);
        assert_eq!(not_before(behind, None), behind);
        assert_eq!(not_before(behind, Some(deadline)), deadline);
        assert_eq!(
            not_before(deadline + ms(5), Some(deadline)),
            deadline + ms(5)
        );

        let mut held = EmptyHold::Until(deadline);
        assert_eq!(
            held.on_rebuild(true, behind),
            HoldVerdict::Hold,
            "control: a rebuild at the clock's earlier reading is held again"
        );
        assert_eq!(
            held.on_rebuild(true, not_before(behind, Some(deadline))),
            HoldVerdict::Compile,
            "the deadline's rebuild ends the hold"
        );
        assert_eq!(held.deadline(), None);
    }

    /// #380: the files a look finds emptied join the batch — the `--vars` file as a change
    /// to it, every other as a path — whether or not their events came.
    #[test]
    fn files_found_emptied_join_the_batch() {
        let path = |name: &str| PathBuf::from("/w").join(name);
        let batch = |vars_changed: bool| Batch {
            paths: BTreeSet::from([path("a.mds")]),
            vars_changed,
        };
        let vars = path("vars.json");
        let emptied: BTreeSet<PathBuf> = BTreeSet::from([path("x.mds"), vars.clone()]);

        assert_eq!(
            join_emptied(batch(false), &emptied, Some(&vars)),
            Batch {
                paths: BTreeSet::from([path("a.mds"), path("x.mds")]),
                vars_changed: true
            },
            "the vars file is a change to it, not a path of the batch"
        );
        assert_eq!(
            join_emptied(batch(false), &BTreeSet::from([path("x.mds")]), Some(&vars)),
            Batch {
                paths: BTreeSet::from([path("a.mds"), path("x.mds")]),
                vars_changed: false
            }
        );
        assert_eq!(
            join_emptied(batch(true), &BTreeSet::new(), Some(&vars)),
            batch(true),
            "nothing emptied: the batch as it came"
        );
    }

    /// A directory state below `root` that has compiled `page.mds`, which imports
    /// `_dep.mds`, with `vars.json` as its `--vars` file: each holds bytes, and the baseline
    /// holds their stamps, as a batch's look leaves them. Returns the state and the three
    /// paths: `[page, dependency, vars file]`.
    fn state_with_a_vars_file(root: &Path) -> (DirWatchState, [PathBuf; 3]) {
        let paths = ["page.mds", "_dep.mds", "vars.json"].map(|name| root.join(name));
        for path in &paths {
            std::fs::write(path, "bytes\n").unwrap();
        }
        let [page, dep, vars] = &paths;
        let mut state = empty_dir_state();
        state.known_files.insert(page.clone());
        state.forward_deps.insert(page.clone(), vec![dep.clone()]);
        state.vars_file = Some(vars.clone());
        state.last_mtimes = snapshot_state(&state.watched_set());
        (state, paths)
    }

    /// #380: a batch whose `--vars` load fails on a file emptied since its look — a
    /// truncation that began between the two — is held with that file joined to it, its own
    /// event lost: the file is a path of the batch the hold ends with.
    #[test]
    fn a_batch_whose_vars_load_failed_on_an_emptied_dependency_is_held_with_it() {
        let (_dir, root) = canonical_tempdir();
        let (mut state, [page, dep, _vars]) = state_with_a_vars_file(&root);
        let batch = Batch {
            paths: BTreeSet::from([page.clone()]),
            vars_changed: false,
        };

        std::fs::write(&dep, "").unwrap();
        assert!(
            state.hold_after_vars_load_failed(&batch, &root, &mds::ReadLog::new()),
            "the batch is held"
        );

        assert_eq!(
            state.held.paths,
            BTreeSet::from([page, dep]),
            "the batch and the file found emptied"
        );
        assert!(!state.held.vars_changed, "no change to the vars file");
        assert!(
            state.hold.deadline().is_some(),
            "the hold runs towards its deadline"
        );
    }

    /// #380: a batch whose `--vars` load fails on the vars file itself, emptied since the
    /// look, is held with that file as a change to it, not as a path of the batch.
    #[test]
    fn a_batch_whose_vars_load_failed_on_an_emptied_vars_file_is_held_as_a_change_to_it() {
        let (_dir, root) = canonical_tempdir();
        let (mut state, [page, _dep, vars]) = state_with_a_vars_file(&root);
        let batch = Batch {
            paths: BTreeSet::from([page.clone()]),
            vars_changed: false,
        };

        std::fs::write(&vars, "").unwrap();
        assert!(
            state.hold_after_vars_load_failed(&batch, &root, &mds::ReadLog::new()),
            "the batch is held"
        );

        assert!(state.held.vars_changed, "a change to the vars file");
        assert_eq!(
            state.held.paths,
            BTreeSet::from([page]),
            "the vars file is no path of the batch"
        );
    }

    /// #380: a batch whose `--vars` load failed is held only while a file is found emptied
    /// and the hold's deadline is still ahead: with none emptied it holds nothing, and the
    /// rebuild the deadline runs compiles the files as they are.
    #[test]
    fn a_batch_whose_vars_load_failed_is_held_only_for_a_file_emptied_before_the_deadline() {
        let (_dir, root) = canonical_tempdir();
        let (mut state, [page, dep, _vars]) = state_with_a_vars_file(&root);
        let batch = Batch {
            paths: BTreeSet::from([page]),
            vars_changed: false,
        };

        assert!(
            !state.hold_after_vars_load_failed(&batch, &root, &mds::ReadLog::new()),
            "no file went empty"
        );
        assert_eq!(state.held, HeldBatch::default(), "nothing is held");
        assert_eq!(state.hold, EmptyHold::Off, "and no hold runs");

        std::fs::write(&dep, "").unwrap();
        state.hold = EmptyHold::Expired;
        assert!(
            !state.hold_after_vars_load_failed(&batch, &root, &mds::ReadLog::new()),
            "the deadline ended the hold in this rebuild"
        );
        assert_eq!(state.held, HeldBatch::default(), "nothing is held");

        state.hold = EmptyHold::Off;
        assert!(
            state.hold_after_vars_load_failed(&batch, &root, &mds::ReadLog::new()),
            "positive control: the same file, with the deadline still ahead, holds the batch"
        );
    }

    /// #380: a batch whose `--vars` load read the vars file empty is held although the save
    /// wrote the file again before the check: the count the load read decides, not a later
    /// `stat` of the file.
    #[test]
    fn a_batch_whose_vars_load_read_the_vars_file_empty_is_held_after_the_file_is_written() {
        let (_dir, root) = canonical_tempdir();
        let (mut state, [page, _dep, vars]) = state_with_a_vars_file(&root);
        let batch = Batch {
            paths: BTreeSet::from([page]),
            vars_changed: false,
        };
        std::fs::write(&vars, "").unwrap();
        let reads = mds::ReadLog::new();
        let loaded = crate::build::build_runtime_vars_logged(
            RuntimeVarArgs {
                vars: Some(vars.clone()),
                set_vars: Vec::new(),
                set_string_vars: Vec::new(),
            },
            &reads,
        );
        assert!(loaded.is_err(), "setup: the load fails on the empty file");
        std::fs::write(&vars, "{\"a\": 1}\n").unwrap();

        assert!(
            emptied_paths(&state.watched_set(), &state.last_mtimes).is_empty(),
            "control: a stat now finds no file emptied"
        );
        assert!(
            state.hold_after_vars_load_failed(&batch, &root, &reads),
            "the batch is held on the empty read"
        );
        assert!(state.held.vars_changed, "a change to the vars file");
    }

    /// #380: after a rename that changed only the case of a name, on a file system that
    /// ignores case, a read names the file as it is spelled on disk now, and the baseline
    /// keeps the spelling it was taken with: the read is matched to the baseline's key. A
    /// key that names another file is never matched. On a file system that keeps case
    /// apart, the two spellings are two files and only the exact key matches.
    #[test]
    fn a_read_after_a_case_only_rename_is_matched_to_the_baseline_s_key() {
        let (_dir, root) = canonical_tempdir();
        let on_disk = root.join("page.mds");
        std::fs::write(&on_disk, "").unwrap();
        let taken_as = root.join("PAGE.mds");
        let other = root.join("other.mds");
        std::fs::write(&other, "x\n").unwrap();
        let baseline: StampMap = [
            (taken_as.clone(), (None, Some(6))),
            (other.clone(), (None, Some(2))),
        ]
        .into_iter()
        .collect();

        let ignores_case = taken_as.exists();
        assert_eq!(
            baseline_key(&on_disk, &baseline),
            ignores_case.then(|| taken_as.clone()),
            "ignores case: {ignores_case}"
        );
        assert_eq!(
            baseline_key(&other, &baseline),
            Some(other.clone()),
            "an exact key matches as it is"
        );
        assert_eq!(
            baseline_key(&root.join("new.mds"), &baseline),
            None,
            "a file the baseline never saw has no key"
        );
    }

    /// #380: a file a compile read empty, which the baseline saw with bytes, is found
    /// emptied although it was written again since — the save ended between the read and
    /// the check. A `stat` now misses it; the count the read gave does not. A file the
    /// baseline saw empty, or never saw, is not found.
    #[test]
    fn a_file_a_compile_read_empty_is_found_although_written_again_since() {
        let (_dir, root) = canonical_tempdir();
        let [entry, was_empty] = ["page.mds", "empty.mds"].map(|name| root.join(name));
        std::fs::write(&entry, "").unwrap();
        std::fs::write(&was_empty, "").unwrap();
        let baseline: StampMap = [
            (entry.clone(), (None, Some(6))),
            (was_empty.clone(), (None, Some(0))),
        ]
        .into_iter()
        .collect();
        let reads = Arc::new(mds::ReadLog::new());
        for path in [&entry, &was_empty] {
            assert!(
                compile_caught(path, path, None, true, &reads).is_ok(),
                "setup: {} compiles",
                path.display()
            );
        }
        std::fs::write(&entry, "Page.\n").unwrap();

        assert!(
            emptied_paths([&entry, &was_empty], &baseline).is_empty(),
            "control: a stat now finds no file emptied"
        );
        assert_eq!(
            read_empty(&reads, &baseline),
            BTreeSet::from([entry]),
            "the read found the entry empty; the file empty in the baseline too is not emptied"
        );
        let mut hold = EmptyHold::Off;
        assert!(
            held_after_look(&mut hold, read_empty(&reads, &baseline)).is_some(),
            "the rebuild is held"
        );
        assert!(
            hold.deadline().is_some(),
            "the hold runs towards its deadline"
        );
    }

    /// #380: a baseline is the stamps taken before the read it describes. Every file keeps
    /// the stamp taken whatever it holds now — one emptied since, one edited since, one taken
    /// empty — only a file none was taken for is stamped now, a file named twice is one
    /// entry, and a file outside the domain is dropped.
    #[test]
    fn a_baseline_keeps_the_stamps_taken_and_stamps_only_the_rest() {
        let (_dir, root) = canonical_tempdir();
        let [emptied, edited, was_empty, new, gone] =
            ["emptied", "edited", "was_empty", "new", "gone"].map(|name| root.join(name));
        for (path, text) in [
            (&emptied, ""),
            (&edited, "edited since\n"),
            (&was_empty, ""),
            (&new, "new\n"),
        ] {
            std::fs::write(path, text).unwrap();
        }
        let taken: StampMap = [
            (emptied.clone(), (None, Some(5))),
            (edited.clone(), (None, Some(3))),
            (was_empty.clone(), (None, Some(0))),
            (gone.clone(), (None, Some(1))),
        ]
        .into_iter()
        .collect();

        let domain = [
            emptied.clone(),
            edited.clone(),
            was_empty.clone(),
            new.clone(),
            edited.clone(),
        ];
        let baseline = baseline_over(taken.clone(), &domain);
        for path in [&emptied, &edited, &was_empty] {
            assert_eq!(baseline.get(path), taken.get(path), "{}", path.display());
        }
        assert_eq!(
            baseline.get(&new),
            Some(&stamp_now(&new)),
            "a file none was taken for is stamped now"
        );
        assert!(!baseline.contains_key(&gone), "{baseline:?}");
        assert_eq!(baseline.len(), 4, "{baseline:?}");
    }

    /// Directory mode's state with `a.mds` (`A one`) and `b.mds` (`B one`) below `root`,
    /// both compiled to `out` by a first batch, as a session's startup leaves them.
    fn two_compiled_sources(root: &Path, out: &Path) -> (DirWatchCtx, DirWatchState) {
        std::fs::write(root.join("a.mds"), "A one\n").unwrap();
        std::fs::write(root.join("b.mds"), "B one\n").unwrap();
        let ctx = dir_ctx(root, out);
        let mut state = empty_dir_state();
        let both = BTreeSet::from([root.join("a.mds"), root.join("b.mds")]);
        rebuild_dir_batch(&ctx, &both, false, &mut state, None);
        (ctx, state)
    }

    /// #380: a directory batch that ends with a watched file emptied since it looked — a
    /// truncation that landed while it ran, whether it had read the file already or does
    /// not read it — keeps the stamp that saw the file's bytes, so the rebuild the file's
    /// own event starts finds it emptied and is held rather than publishing it empty.
    /// `process_dir_batch` is what a batch runs once its look is done.
    #[test]
    fn a_batch_keeps_a_file_emptied_since_its_look_found_emptied() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (ctx, mut state) = two_compiled_sources(&root, &out);
        let (a, b) = (root.join("a.mds"), root.join("b.mds"));
        let read = |name: &str| std::fs::read_to_string(out.join(name)).ok();
        assert!(
            read("a.md").is_some_and(|text| text.contains("A one")),
            "control: a is compiled; out/a.md: {:?}",
            read("a.md")
        );

        // A batch for b, past its look, with a emptied meanwhile.
        std::fs::write(&b, "B two\n").unwrap();
        std::fs::write(&a, "").unwrap();
        process_dir_batch(
            &BTreeSet::from([b.clone()]),
            false,
            &mut BatchCtx {
                watch_root: &ctx.root,
                output_base: &ctx.output_base,
                vars: BatchVars::map_only(&None),
                quiet: true,
            },
            &mut state,
        );
        assert!(
            read("b.md").is_some_and(|text| text.contains("B two")),
            "positive control: the batch rebuilds b; out/b.md: {:?}",
            read("b.md")
        );

        // a's own event.
        rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
        assert!(
            read("a.md").is_some_and(|text| text.contains("A one")),
            "a file emptied while a batch ran is held, not published empty; out/a.md: {:?}",
            read("a.md")
        );
        assert!(state.hold.deadline().is_some(), "{:?}", state.hold);
    }

    /// #380: a directory batch's baseline is the stamps its look took: a source the batch
    /// compiled keeps the look's stamp, not the one it has once the batch has read it, so a
    /// file saved after the look is found changed again by the next look or idle tick.
    /// `process_dir_batch` is what a batch runs once its look is done.
    #[test]
    fn a_batch_s_baseline_is_its_look_s_stamps() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (ctx, mut state) = two_compiled_sources(&root, &out);
        let b = root.join("b.mds");
        let look = state.last_mtimes.clone();

        // b saved after the batch's look, before its compile reads it.
        std::fs::write(&b, "B two, saved after the look\n").unwrap();
        process_dir_batch(
            &BTreeSet::from([b.clone()]),
            false,
            &mut BatchCtx {
                watch_root: &ctx.root,
                output_base: &ctx.output_base,
                vars: BatchVars::map_only(&None),
                quiet: true,
            },
            &mut state,
        );
        let read = std::fs::read_to_string(out.join("b.md")).ok();
        assert!(
            read.as_deref()
                .is_some_and(|text| text.contains("B two, saved after the look")),
            "control: the batch compiled what it read; out/b.md: {read:?}"
        );
        assert_eq!(
            state.last_mtimes, look,
            "the baseline is the look's stamps, b's included"
        );
        assert!(
            path_state_differs(&b, &state.last_mtimes),
            "so the next look finds b changed"
        );
    }

    /// #380: the batch the hold's deadline runs compiles a file found emptied as it is, and
    /// takes it into the baseline so: a later batch is not held for a file left empty.
    #[test]
    fn a_deadline_batch_takes_a_file_it_compiled_empty_into_the_baseline() {
        let (_root_dir, root) = canonical_tempdir();
        let (_out_dir, out) = canonical_tempdir();
        let (ctx, mut state) = two_compiled_sources(&root, &out);
        let (a, b) = (root.join("a.mds"), root.join("b.mds"));
        let read = |name: &str| std::fs::read_to_string(out.join(name)).ok();

        std::fs::write(&a, "").unwrap();
        rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
        let deadline = state.hold.deadline().expect("control: the batch is held");
        rebuild_dir_batch(&ctx, &BTreeSet::new(), false, &mut state, Some(deadline));
        assert_eq!(
            read("a.md").as_deref(),
            Some(""),
            "control: the deadline compiles a as it is"
        );

        std::fs::write(&b, "B two\n").unwrap();
        rebuild_dir_batch(&ctx, &BTreeSet::from([b.clone()]), false, &mut state, None);
        assert!(
            read("b.md").is_some_and(|text| text.contains("B two")),
            "a batch after the deadline is not held for a file left empty; out/b.md: {:?}",
            read("b.md")
        );
        assert_eq!(state.hold.deadline(), None, "{:?}", state.hold);
    }

    /// #380: the paths found emptied since a baseline: those it saw with bytes that have
    /// none now — not one still with bytes, nor one it never saw.
    #[test]
    fn emptied_paths_are_those_found_with_none_after_bytes() {
        let (_dir, root) = canonical_tempdir();
        let [emptied, kept, unseen] = ["emptied", "kept", "unseen"].map(|name| root.join(name));
        std::fs::write(&emptied, "bytes").unwrap();
        std::fs::write(&kept, "bytes").unwrap();
        let paths: HashSet<PathBuf> = [emptied.clone(), kept.clone()].into_iter().collect();
        let baseline = snapshot_state(&paths);
        std::fs::write(&emptied, "").unwrap();
        std::fs::write(&unseen, "").unwrap();

        let all = [emptied.clone(), kept, unseen];
        assert_eq!(emptied_paths(&all, &baseline), BTreeSet::from([emptied]));
    }

    /// `Settle::MarkErrored` records a directory-mode source as errored in a rebuild,
    /// keeping the dependency set its last successful compile recorded, and takes no
    /// baseline: the batch takes it at its end. File mode has no errored set: it takes
    /// the baseline again, as `Settle::Rebaseline` does. A directory-mode startup failure
    /// settles the source the same way, through [`settle_startup_error`] (#257).
    #[test]
    fn settle_mark_errored_records_the_source_in_directory_mode() {
        let (_dir, src, dep) = source_and_dependency();

        // Directory rebuild: errored, the dependency set kept, no baseline.
        let mut rebuild = empty_dir_state();
        rebuild.known_files.insert(src.clone());
        rebuild.forward_deps.insert(src.clone(), vec![dep.clone()]);
        settle(
            SettleInto::Dir(&mut rebuild),
            None,
            Settle::MarkErrored(&src),
        );
        assert!(rebuild.errored.contains(&src), "{:?}", rebuild.errored);
        assert_eq!(rebuild.forward_deps.get(&src), Some(&vec![dep.clone()]));
        assert!(rebuild.last_mtimes.is_empty(), "{:?}", rebuild.last_mtimes);

        // File mode: the baseline again.
        let foi: HashSet<PathBuf> = [src.clone(), dep.clone()].into_iter().collect();
        let mut file = file_state(foi.clone());
        settle(SettleInto::File(&mut file), None, Settle::MarkErrored(&src));
        assert_eq!(file.last_mtimes, snapshot_state(&foi));
        assert!(
            file.last_mtimes.contains_key(&src),
            "{:?}",
            file.last_mtimes
        );
    }

    /// A directory-mode startup failure settles the source as errored, same as
    /// `Settle::MarkErrored` in a rebuild: a source new to the graph gets the empty
    /// dependency set, and no baseline is taken — the startup baseline is still to come.
    /// File mode's startup settle has no state to record into (#257).
    #[test]
    fn settle_startup_error_records_the_source_in_directory_mode() {
        let (_dir, src, _dep) = source_and_dependency();

        let mut startup = empty_dir_state();
        settle_startup_error(StartupInto::Dir(&mut startup), None, &src);
        assert!(startup.errored.contains(&src), "{:?}", startup.errored);
        assert_eq!(startup.forward_deps.get(&src), Some(&vec![]));
        assert!(startup.last_mtimes.is_empty(), "{:?}", startup.last_mtimes);
    }

    /// A compile that panicked settles as its error does at the same site — the site picks
    /// the action, whatever failed — and is not reported: the panic hook reported it
    /// (#389, #257).
    #[test]
    fn a_panicked_compile_settles_as_an_error_does_and_is_not_reported() {
        let (_dir, src, dep) = source_and_dependency();
        let foi: HashSet<PathBuf> = [src.clone(), dep.clone()].into_iter().collect();
        let failures = || {
            [
                (
                    "an error",
                    CompileFailure::from(miette::miette!("broken")),
                    1,
                ),
                ("a panic", CompileFailure::Panicked, 0),
            ]
        };

        for (what, failure, reports) in failures() {
            let mut reported = Vec::new();
            let mut state = empty_dir_state();
            state.forward_deps.insert(src.clone(), vec![dep.clone()]);
            settle_reporting(
                SettleInto::Dir(&mut state),
                failure.into_report(),
                Settle::MarkErrored(&src),
                |e| reported.push(e.to_string()),
            );
            assert!(state.errored.contains(&src), "{what}: marked errored");
            assert_eq!(
                state.forward_deps.get(&src),
                Some(&vec![dep.clone()]),
                "{what}"
            );
            assert_eq!(reported.len(), reports, "{what}: reported {reported:?}");
        }

        for (what, failure, reports) in failures() {
            let mut reported = Vec::new();
            let mut state = file_state(foi.clone());
            settle_reporting(
                SettleInto::File(&mut state),
                failure.into_report(),
                Settle::MarkErrored(&src),
                |e| reported.push(e.to_string()),
            );
            assert_eq!(
                state.last_mtimes,
                snapshot_state(&foi),
                "{what}: rebaselined"
            );
            assert_eq!(reported.len(), reports, "{what}: reported {reported:?}");
        }

        // The error is reported as it is, once.
        let mut reported = Vec::new();
        settle_startup_error_reporting(
            StartupInto::File,
            CompileFailure::from(miette::miette!("broken")).into_report(),
            &src,
            |e| reported.push(e.to_string()),
        );
        assert_eq!(reported, ["broken"]);
    }

    /// An out-dir is unchanged until it goes. Deleted, it is new — no output the session
    /// wrote is there to skip — and so is the directory a write makes in its place, which
    /// the next check compares once [`OutDirAnchor::written`] has taken it. A directory
    /// put in its place is new once, then the one compared (unix: Windows tells the two
    /// apart by their creation time alone, which tunnelling can carry over).
    #[test]
    fn an_out_dir_deleted_or_replaced_at_its_path_is_new_once() {
        let base = tempfile::tempdir().unwrap();
        let out = base.path().join("out");
        std::fs::create_dir(&out).unwrap();
        let mut anchor = OutDirAnchor::record(Some(&out), None).expect("an out-dir");
        assert_eq!(
            anchor.check(),
            OutDirNow::Unchanged,
            "the directory recorded"
        );

        std::fs::remove_dir(&out).unwrap();
        assert_eq!(anchor.check(), OutDirNow::New, "deleted");
        assert_eq!(anchor.check(), OutDirNow::New, "still none");
        // The write creates the directory again.
        std::fs::create_dir(&out).unwrap();
        anchor.written();
        assert_eq!(
            anchor.check(),
            OutDirNow::Unchanged,
            "the directory the write made"
        );

        if cfg!(unix) {
            std::fs::rename(&out, base.path().join("out.old")).unwrap();
            std::fs::create_dir(&out).unwrap();
            assert_eq!(
                anchor.check(),
                OutDirNow::New,
                "another directory in its place"
            );
            assert_eq!(
                anchor.check(),
                OutDirNow::Unchanged,
                "then the one compared"
            );
        }
    }

    /// An out-dir named through a symlink is elsewhere once the link leads to another
    /// directory — one that is there, or one a write would create there — or nowhere, and
    /// is itself again once the link leads back: a check never takes the other directory
    /// as the one it compares.
    #[cfg(unix)]
    #[test]
    fn an_out_dir_the_typed_path_leads_away_from_is_elsewhere() {
        use std::os::unix::fs::symlink;

        let base = tempfile::tempdir().unwrap();
        for name in ["a", "b"] {
            std::fs::create_dir(base.path().join(name)).unwrap();
        }
        let link = base.path().join("link");
        symlink("a", &link).unwrap();
        let mut anchor = OutDirAnchor::record(Some(&link), None).expect("an out-dir");
        // `link/out` is not there yet: the write would create it in `a`.
        let mut below = OutDirAnchor::record(Some(&link.join("out")), None).expect("an out-dir");
        assert_eq!(anchor.check(), OutDirNow::Unchanged);
        assert_eq!(below.check(), OutDirNow::New, "none yet");

        let retarget = |to: &str| {
            std::fs::remove_file(&link).unwrap();
            symlink(to, &link).unwrap();
        };
        retarget("b");
        assert_eq!(
            anchor.check(),
            OutDirNow::Elsewhere,
            "a directory that is there"
        );
        assert_eq!(anchor.checked, None, "a refused write is anchored nowhere");
        assert_eq!(
            below.check(),
            OutDirNow::Elsewhere,
            "one a write would create"
        );
        retarget("nowhere");
        assert_eq!(
            anchor.check(),
            OutDirNow::Elsewhere,
            "a link that leads nowhere"
        );

        retarget("a");
        assert_eq!(anchor.check(), OutDirNow::Unchanged, "led back");
        assert_eq!(below.check(), OutDirNow::New, "led back, still none");
    }

    /// `build.output_dir` is checked below the directory `mds.json` was reached by, the
    /// path compared; `--out-dir` takes precedence over it, as it does for the output
    /// base, and with neither, or a configuration without `build.output_dir`, there is no
    /// out-dir to check.
    #[test]
    fn a_build_output_dir_is_checked_below_the_directory_of_mds_json() {
        use crate::build::{BuildConfig, MdsConfig};

        let base = tempfile::tempdir().unwrap();
        let dir = base.path().canonicalize().unwrap();
        let config = |output_dir: Option<&str>| ProjectConfig {
            config: MdsConfig {
                build: BuildConfig {
                    output_dir: output_dir.map(str::to_owned),
                    ..Default::default()
                },
                ..Default::default()
            },
            dir: dir.clone(),
            shown_dir: base.path().to_path_buf(),
        };
        let dist = config(Some("dist"));
        std::fs::create_dir(dir.join("dist")).unwrap();
        let mut anchor = OutDirAnchor::record(None, Some(&dist)).expect("an out-dir");
        assert_eq!(
            (&anchor.typed, &anchor.out_dir),
            (&base.path().to_path_buf(), &dir.join("dist"))
        );
        assert_eq!(anchor.check(), OutDirNow::Unchanged);
        std::fs::remove_dir(dir.join("dist")).unwrap();
        assert_eq!(anchor.check(), OutDirNow::New, "deleted below it");

        let flag = base.path().join("flag");
        let chosen = OutDirAnchor::record(Some(&flag), Some(&dist)).expect("an out-dir");
        assert_eq!(chosen.out_dir, dir.join("flag"), "--out-dir first");
        assert!(OutDirAnchor::record(None, Some(&config(None))).is_none());
        assert!(OutDirAnchor::record(None, None).is_none());

        // The writes are anchored at the directory `mds.json` is in, `dist` deleted or not.
        let config_dir = Some(CheckedAnchor {
            missing: 0,
            identity: DirIdentity::of(&dir).expect("a directory"),
        });
        assert_eq!(anchor.checked, config_dir);
        std::fs::create_dir(dir.join("dist")).unwrap();
        anchor.check();
        assert_eq!(anchor.checked, config_dir);
    }

    /// A check finds the directory the next write below the out-dir is anchored at (#160):
    /// the out-dir itself, or — once it is deleted, for the write to create it again — the
    /// nearest directory above it. The write is given that directory to expect, below it
    /// the file, named as before; a session with no out-dir writes its target as it is.
    #[test]
    fn a_check_finds_the_directory_the_next_write_is_anchored_at() {
        let base = tempfile::tempdir().unwrap();
        let root = base.path().canonicalize().unwrap();
        let out = root.join("out");
        std::fs::create_dir(&out).unwrap();
        let mut anchor = OutDirAnchor::record(Some(&out), None).expect("an out-dir");
        assert_eq!(anchor.checked, None, "nothing found before a check");
        let target = WriteTarget::new(out.join("a.md"), PathBuf::from("o/a.md"));
        let written = |anchor: &OutDirAnchor| {
            let checked = below_checked_out_dir(Some(anchor), &target);
            (
                checked.path.clone(),
                checked.shown.clone(),
                checked.below_anchor(),
                checked.checked_anchor(),
            )
        };

        assert_eq!(anchor.check(), OutDirNow::Unchanged);
        assert_eq!(
            written(&anchor),
            (
                out.join("a.md"),
                PathBuf::from("o/a.md"),
                1,
                DirIdentity::of(&out)
            ),
            "the out-dir"
        );

        std::fs::remove_dir(&out).unwrap();
        assert_eq!(anchor.check(), OutDirNow::New);
        assert_eq!(
            written(&anchor),
            (
                out.join("a.md"),
                PathBuf::from("o/a.md"),
                2,
                DirIdentity::of(&root)
            ),
            "deleted: the directory above it, the out-dir below it"
        );

        assert_eq!(below_checked_out_dir(None, &target), target, "no out-dir");
    }
}