mds-cli 0.4.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
//! Integration tests for `mds watch`.
//!
//! Strategy:
//! - Spawn through `spawn_ready`, which blocks until the watcher is fully armed, so a
//!   test's first edit cannot land in a window the watcher is blind to.
//! - Spawn `mds watch … --debounce 0` (immediate rebuild, no debounce delay).
//! - Poll output file content with a bounded `wait_for_file_contains`.
//! - Poll stderr with `wait_for_stderr_contains` when testing error / status messages.
//! - A RAII `ChildGuard` kills+waits the child on drop so tests never leave orphans.
//!
//! Every wait carries one of three bounds, and which one is a claim about the mechanism
//! that must deliver the result: [`TIMEOUT`] for an inotify event, [`TICK_TIMEOUT`] for
//! a self-heal idle tick, [`STARTUP_WINDOW_TIMEOUT`] for the deliberately
//! unsynchronized startup-window tests. See each constant's docs.
//!
//! Flakiness mitigations:
//! - Assert on output FILE content rather than stderr ordering.
//! - Write dependency files BEFORE adding the `@import` that references them.
//! - Use `-q` where stderr isn't under test.
//! - Always kill+wait child in `ChildGuard::drop`.

mod common;
use common::{mds_bin, spawn_watch_ready, spawn_watch_unsynchronized, StderrTap};

use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

// ── Helpers ────────────────────────────────────────────────────────────────

/// RAII guard that kills + waits the child process on drop.
struct ChildGuard(Child);

impl Drop for ChildGuard {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

impl ChildGuard {
    fn id(&self) -> u32 {
        self.0.id()
    }
    fn wait_status(&mut self) -> std::process::ExitStatus {
        self.0.wait().expect("wait failed")
    }
}

/// Spawn a watcher, block until it reports readiness, and wrap it in a `ChildGuard`.
///
/// Every test that edits files under an `mds watch` must go through this: it returns
/// only once every watch is armed and every `(mtime, size)` baseline captured, so a
/// subsequent edit cannot land in a window the watcher is blind to.
///
/// The returned [`StderrTap`] holds everything the child wrote to stderr, including
/// the startup lines printed before the readiness marker.
fn spawn_ready(cmd: &mut Command) -> (ChildGuard, StderrTap) {
    let (child, tap) = spawn_watch_ready(cmd);
    (ChildGuard(child), tap)
}

/// Spawn a watcher WITHOUT the readiness handshake and wrap it in a `ChildGuard`.
///
/// Reserved for the tests that exist precisely to exercise startup: a test that
/// synchronises on "startup finished" can never observe anything that happens
/// *during* startup. Every other test must use [`spawn_ready`].
fn spawn_unsynchronized(cmd: &mut Command) -> (ChildGuard, StderrTap) {
    let (child, tap) = spawn_watch_unsynchronized(cmd);
    (ChildGuard(child), tap)
}

/// Poll `path` until its content contains `needle`, or `timeout` elapses.
fn wait_for_file_contains(path: &Path, needle: &str, timeout: Duration) -> bool {
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        if let Ok(content) = std::fs::read_to_string(path) {
            if content.contains(needle) {
                return true;
            }
        }
        std::thread::sleep(Duration::from_millis(50));
    }
    false
}

/// Like [`wait_for_file_contains`] but polls at 1ms instead of 50ms.
///
/// Only for the startup-window tests. There the poll granularity is not just latency,
/// it is the test's own contribution to how late its edit lands inside the window it is
/// trying to hit — a 50ms poll spends a quarter of the `startup-race-probe` window
/// before the edit is even attempted.
fn wait_for_file_contains_tight(path: &Path, needle: &str, timeout: Duration) -> bool {
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        if let Ok(content) = std::fs::read_to_string(path) {
            if content.contains(needle) {
                return true;
            }
        }
        std::thread::sleep(Duration::from_millis(1));
    }
    false
}

/// Poll `path` until it no longer exists, or `timeout` elapses.
fn wait_for_file_gone(path: &Path, timeout: Duration) -> bool {
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        if !path.exists() {
            return true;
        }
        std::thread::sleep(Duration::from_millis(50));
    }
    false
}

/// Upper bound on how long an **inotify-delivered** effect may take to appear.
///
/// This is a **failure bound, not a synchroniser**. Every spawn goes through
/// [`spawn_ready`], so by the time a test edits a file the watcher is already armed
/// and the remaining work is one inotify delivery plus one compile — milliseconds in
/// practice, even with the suite at full parallelism. The old 10s value dated from
/// when these waits doubled as the startup synchroniser; keeping it only meant every
/// genuine regression cost 10s of wall clock per occurrence before reporting.
///
/// 2s leaves ~40 poll cycles of headroom over the observed millisecond-scale latency
/// — ample for a loaded container, still short enough that a real regression surfaces
/// promptly.
///
/// **This bound is only valid for a wait an OS event can satisfy.** A wait whose
/// recovery path runs on the self-heal idle tick instead must use [`TICK_TIMEOUT`],
/// which is expressed in ticks rather than in absolute latency; see its docs for the
/// enumeration of which waits those are and why.
const TIMEOUT: Duration = Duration::from_secs(2);

/// Upper bound for a wait that only the **self-heal idle tick** can satisfy.
///
/// A handful of scenarios destroy the inotify watch descriptor itself, so no OS event
/// can ever announce the recovery: `rmdir` of a watched directory removes the kernel's
/// watch, and the directory recreated in its place is a different inode that nothing is
/// watching. Recovery there is the `liveness_probe_*` re-arm, which runs once per
/// `--poll-interval`. Such a wait is denominated in **ticks**, and pricing it with
/// [`TIMEOUT`] — a latency bound — conflates two unrelated quantities and leaves the
/// headroom silently dependent on whatever `--poll-interval` the test happens to pass.
///
/// The tick-dependent waits, all of which use this bound:
/// - `watch_file_mode_parent_dir_delete_recreate_recovers`
/// - `watch_file_mode_parent_dir_deleted_bounded_errors_then_recovers`
/// - `watch_dir_mode_root_delete_recreate_recovers`
/// - `watch_vars_dir_delete_recreate_rearms`
///
/// Every other wait in this file is satisfied by an inotify event on a watch that was
/// never lost, and keeps [`TIMEOUT`].
///
/// 8s is ≥ 50 ticks at the 150ms poll-interval used by the slowest of them, and ≥ 8
/// ticks even at the 1000ms default, so the bound stays a failure bound under any
/// `--poll-interval` a test might reasonably choose.
const TICK_TIMEOUT: Duration = Duration::from_secs(8);

/// Upper bound for the deliberately unsynchronized startup-window tests.
///
/// Those tests race the watcher's own startup, so their wait spans whatever remains of
/// the startup compile plus the `startup-race-probe` delay when that feature is on.
/// Neither is a post-readiness latency, so [`TIMEOUT`] does not apply.
const STARTUP_WINDOW_TIMEOUT: Duration = Duration::from_secs(5);

// ── T-I14: Invalid combinations rejected at startup ────────────────────────

#[test]
fn watch_rejects_stdin() {
    let output = mds_bin()
        .args(["watch", "-"])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .unwrap();
    assert!(
        !output.status.success(),
        "watch with stdin should fail; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("stdin") || stderr.contains("build"),
        "error should mention stdin, got: {stderr}"
    );
}

#[test]
fn watch_rejects_dir_with_output_flag() {
    let dir = tempfile::tempdir().unwrap();
    let output = mds_bin()
        .args(["watch", dir.path().to_str().unwrap(), "-o", "out.md"])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .unwrap();
    assert!(
        !output.status.success(),
        "watch dir with -o should fail; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

// ── T-I1: Initial compile writes output ────────────────────────────────────

#[test]
fn watch_initial_compile_writes_output() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
    let out = dir.path().join("hello.md");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args(["watch", src.to_str().unwrap(), "--debounce", "0", "-q"])
            .stdout(Stdio::null()),
    );

    let found = wait_for_file_contains(&out, "Hello World!", TIMEOUT);
    assert!(found, "initial compile should write output to hello.md");
    drop(child);
}

// ── T-I2: Edit entry → output updates ─────────────────────────────────────

#[test]
fn watch_edit_entry_updates_output() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "---\nname: Alice\n---\nHello {{name}}!\n").unwrap();
    let out = dir.path().join("hello.md");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args(["watch", src.to_str().unwrap(), "--debounce", "0", "-q"])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile.
    assert!(
        wait_for_file_contains(&out, "Hello Alice!", TIMEOUT),
        "initial compile should produce Hello Alice!"
    );

    // Edit the source.
    std::fs::write(&src, "---\nname: Bob\n---\nHello {{name}}!\n").unwrap();

    // Wait for rebuild.
    assert!(
        wait_for_file_contains(&out, "Hello Bob!", TIMEOUT),
        "after editing, output should contain Hello Bob!"
    );

    drop(child);
}

// ── T-I3: Edit imported dep → entry output updates ─────────────────────────

#[test]
fn watch_edit_imported_dep_updates_entry() {
    let dir = tempfile::tempdir().unwrap();

    // Helper module exporting 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();

    // Entry that imports helper.
    let entry = dir.path().join("entry.mds");
    std::fs::write(
        &entry,
        "@import \"./helper.mds\" as h\n\n{{h.greet(\"World\")}}\n",
    )
    .unwrap();
    let out = dir.path().join("entry.md");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args(["watch", entry.to_str().unwrap(), "--debounce", "0", "-q"])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out, "Hello World!", TIMEOUT),
        "initial compile should produce Hello World!"
    );

    // Edit the helper to change the greeting.
    std::fs::write(
        &helper,
        "@define greet(name):\nHi there {{name}}!\n@end\n\n@export greet\n",
    )
    .unwrap();

    assert!(
        wait_for_file_contains(&out, "Hi there World!", TIMEOUT),
        "editing the imported helper should trigger a rebuild"
    );

    drop(child);
}

// ── T-I5: Compile error → process alive, output unchanged, fix recovers ────

#[test]
fn watch_compile_error_keeps_watcher_alive() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "---\nname: Alice\n---\nHello {{name}}!\n").unwrap();
    let out = dir.path().join("hello.md");

    let (mut child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args(["watch", src.to_str().unwrap(), "--debounce", "0", "-q"])
            .stdout(Stdio::null()),
    );

    // Wait for successful initial compile.
    assert!(
        wait_for_file_contains(&out, "Hello Alice!", TIMEOUT),
        "initial compile should succeed"
    );

    // Introduce a compile error.
    std::fs::write(&src, "Hello {{undefined_var_xyz}}!\n").unwrap();
    // Give the watcher time to attempt rebuild.
    std::thread::sleep(Duration::from_millis(500));

    // Process should still be alive.
    // (try_wait returns None = still running, Some = exited)
    let still_running = child.0.try_wait().unwrap().is_none();
    assert!(
        still_running,
        "watcher should stay alive after compile error"
    );

    // Fix the error — watcher should recover.
    std::fs::write(&src, "---\nname: Charlie\n---\nHello {{name}}!\n").unwrap();
    assert!(
        wait_for_file_contains(&out, "Hello Charlie!", TIMEOUT),
        "fixing the error should trigger a successful rebuild"
    );

    drop(child);
}

// ── T-I6: Directory mode startup compiles all, per-file updates work ───────

#[test]
fn watch_dir_mode_compiles_all_on_startup() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("a.mds"),
        "---\nname: A\n---\nFile A: {{name}}\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("b.mds"),
        "---\nname: B\n---\nFile B: {{name}}\n",
    )
    .unwrap();
    let out_dir = dir.path().join("out");
    std::fs::create_dir(&out_dir).unwrap();

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "File A: A", TIMEOUT),
        "a.md should be compiled on startup"
    );
    assert!(
        wait_for_file_contains(&out_dir.join("b.md"), "File B: B", TIMEOUT),
        "b.md should be compiled on startup"
    );

    // Edit a.mds → only a.md should update.
    std::fs::write(
        dir.path().join("a.mds"),
        "---\nname: A-edited\n---\nFile A: {{name}}\n",
    )
    .unwrap();
    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "File A: A-edited", TIMEOUT),
        "editing a.mds should update a.md"
    );
    // b.md should be untouched.
    let b_content = std::fs::read_to_string(out_dir.join("b.md")).unwrap();
    assert!(
        b_content.contains("File B: B"),
        "b.md should not be affected by edits to a.mds, got: {b_content}"
    );

    drop(child);
}

// ── T-I7: Directory mode picks up newly created .mds files ─────────────────

#[test]
fn watch_dir_mode_picks_up_new_files() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("a.mds"), "---\nname: A\n---\nFile A\n").unwrap();
    let out_dir = dir.path().join("out");
    std::fs::create_dir(&out_dir).unwrap();

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile.
    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "File A", TIMEOUT),
        "a.md should appear on startup"
    );

    // Create a new file AFTER the watcher is running.
    std::fs::write(
        dir.path().join("c.mds"),
        "---\nname: C\n---\nNew file {{name}}\n",
    )
    .unwrap();

    assert!(
        wait_for_file_contains(&out_dir.join("c.md"), "New file C", TIMEOUT),
        "newly created c.mds should be compiled to c.md"
    );

    drop(child);
}

// ── T-I8: Directory mode deletes output when source is deleted ─────────────

#[test]
fn watch_dir_mode_deletes_output_on_source_deletion() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("a.mds"), "---\nname: A\n---\nFile A\n").unwrap();
    std::fs::write(dir.path().join("b.mds"), "---\nname: B\n---\nFile B\n").unwrap();
    let out_dir = dir.path().join("out");
    std::fs::create_dir(&out_dir).unwrap();

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // Wait for both outputs to be created.
    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "File A", TIMEOUT),
        "a.md should appear on startup"
    );
    assert!(
        wait_for_file_contains(&out_dir.join("b.md"), "File B", TIMEOUT),
        "b.md should appear on startup"
    );

    // Delete a.mds.
    std::fs::remove_file(dir.path().join("a.mds")).unwrap();

    // a.md should be removed.
    assert!(
        wait_for_file_gone(&out_dir.join("a.md"), TIMEOUT),
        "a.md should be removed when a.mds is deleted"
    );
    // b.md must remain untouched.
    assert!(
        out_dir.join("b.md").exists(),
        "b.md should not be removed when only a.mds was deleted"
    );

    drop(child);
}

// ── T-I9: Edit --vars file triggers recompile ─────────────────────────────

#[test]
fn watch_vars_file_change_triggers_recompile() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    // Provide a frontmatter default so the template compiles even without vars.
    std::fs::write(&src, "---\nname: Default\n---\nHello {{name}}!\n").unwrap();
    let vars = dir.path().join("vars.json");
    std::fs::write(&vars, r#"{"name": "Alice"}"#).unwrap();
    let out = dir.path().join("hello.md");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "--vars",
                vars.to_str().unwrap(),
                "--debounce",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out, "Hello Alice!", TIMEOUT),
        "initial compile with vars should produce Hello Alice!"
    );

    // Edit the vars file.
    std::fs::write(&vars, r#"{"name": "Bob"}"#).unwrap();

    assert!(
        wait_for_file_contains(&out, "Hello Bob!", TIMEOUT),
        "editing vars file should trigger recompile with new name"
    );

    drop(child);
}

// ── T-I10: --clear with non-TTY pipe → ANSI sequence absent ───────────────

#[test]
fn watch_clear_non_tty_no_ansi_escape() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
    let out = dir.path().join("hello.md");

    // Spawn with piped stderr — not a TTY. `clear_terminal` only emits the ANSI
    // sequence on rebuilds (not the initial compile), so we must trigger a rebuild
    // to actually exercise the --clear code path.
    let (mut child, stderr_tap) = spawn_ready(
        mds_bin()
            .args(["watch", src.to_str().unwrap(), "--clear", "--debounce", "0"])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile.
    assert!(
        wait_for_file_contains(&out, "Hello World!", TIMEOUT),
        "initial compile should write output"
    );

    // Edit the source to trigger a rebuild — this is the path that calls
    // clear_terminal(). On a non-TTY pipe it must be a no-op.
    std::fs::write(&src, "---\nname: There\n---\nHello {{name}}!\n").unwrap();
    assert!(
        wait_for_file_contains(&out, "Hello There!", TIMEOUT),
        "rebuild should occur after editing source"
    );

    // Stop the child and collect everything it wrote to stderr.
    let _ = child.0.kill();
    let _ = child.0.wait();
    let stderr_bytes = stderr_tap.bytes();

    // AC-F6: the ANSI clear/home sequences emitted by clear_terminal()
    // (\x1b[2J, \x1b[3J, \x1b[H) must be ABSENT when stderr is not a TTY.
    assert!(
        !contains_subslice(&stderr_bytes, b"\x1b[2J"),
        "ANSI erase-screen (\\x1b[2J) must not be emitted on a non-TTY pipe; \
         stderr was: {:?}",
        String::from_utf8_lossy(&stderr_bytes)
    );
    assert!(
        !contains_subslice(&stderr_bytes, b"\x1b[3J"),
        "ANSI erase-scrollback (\\x1b[3J) must not be emitted on a non-TTY pipe"
    );
    assert!(
        !contains_subslice(&stderr_bytes, b"\x1b["),
        "no ANSI CSI escape (\\x1b[) should appear on a non-TTY pipe"
    );
}

/// Return true if `haystack` contains `needle` as a contiguous subslice.
fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.is_empty() {
        return true;
    }
    haystack.windows(needle.len()).any(|w| w == needle)
}

// ── T-I11: Output resolution — -o <file> ──────────────────────────────────

#[test]
fn watch_output_flag_writes_to_specified_file() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
    let out = dir.path().join("custom_output.md");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "-o",
                out.to_str().unwrap(),
                "--debounce",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out, "Hello World!", TIMEOUT),
        "watch with -o should write to the specified file"
    );
    assert!(
        !dir.path().join("hello.md").exists(),
        "default hello.md should not be written when -o overrides"
    );

    drop(child);
}

// ── T-I12: --set vars applied on rebuild ──────────────────────────────────

#[test]
fn watch_set_vars_applied_on_rebuild() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("tpl.mds");
    std::fs::write(&src, "Hello {{name}}!\n").unwrap();
    let out = dir.path().join("tpl.md");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "--set",
                "name=Alice",
                "--debounce",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out, "Hello Alice!", TIMEOUT),
        "--set name=Alice should be applied on initial compile"
    );

    // Edit to trigger rebuild — --set should still apply.
    std::fs::write(&src, "Greetings {{name}}!\n").unwrap();
    assert!(
        wait_for_file_contains(&out, "Greetings Alice!", TIMEOUT),
        "--set name=Alice should persist across rebuilds"
    );

    drop(child);
}

// ── T-I13: Single-file @message template → intrinsic JSON output ──────────
//
// Output extension and format are derived from the compiled kind — no --format flag.
// A messages template (chat.mds) watched in single-file mode produces chat.json.

#[test]
fn watch_messages_template_produces_json_intrinsically() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("chat.mds");
    std::fs::write(&src, "@message user:\nWhat is 2+2?\n@end\n").unwrap();
    let out = dir.path().join("chat.json");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "-o",
                out.to_str().unwrap(),
                "--debounce",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out, "What is 2+2?", TIMEOUT),
        "messages template should write JSON containing the message"
    );

    // Verify it's valid JSON.
    let content = std::fs::read_to_string(&out).unwrap();
    let parsed: serde_json::Value =
        serde_json::from_str(&content).expect("messages output should be valid JSON");
    assert!(
        parsed.is_array(),
        "messages output should be a JSON array, got: {content}"
    );

    drop(child);
}

// ── T-I15: stdout / stderr separation with -o - ────────────────────────────

#[test]
fn watch_stdout_contains_content_when_o_stdout() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();

    // -o - forces stdout output.
    let (mut child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "-o",
                "-",
                "--debounce",
                "0",
                "-q",
            ])
            .stdout(Stdio::piped()),
    );

    // Read from stdout with a timeout.
    use std::io::Read as _;
    let deadline = Instant::now() + TIMEOUT;
    let mut buf = String::new();
    let mut found = false;
    // Give the child time to produce output.
    while Instant::now() < deadline {
        let mut tmp = [0u8; 256];
        if let Some(stdout) = child.0.stdout.as_mut() {
            match stdout.read(&mut tmp) {
                Ok(0) | Err(_) => {}
                Ok(n) => {
                    buf.push_str(&String::from_utf8_lossy(&tmp[..n]));
                    if buf.contains("Hello World!") {
                        found = true;
                        break;
                    }
                }
            }
        }
        std::thread::sleep(Duration::from_millis(50));
    }

    assert!(found, "with -o -, compiled output should appear on stdout");
    drop(child);
}

// ── T-I16: Ctrl+C clean exit (#[cfg(unix)]) ────────────────────────────────

#[test]
#[cfg(unix)]
fn watch_ctrl_c_exits_cleanly() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
    let out = dir.path().join("hello.md");

    let (mut guard, _stderr_tap) = spawn_ready(
        mds_bin()
            .args(["watch", src.to_str().unwrap(), "--debounce", "0"])
            .stdout(Stdio::null()),
    );
    let pid = guard.id();

    // Wait for initial compile so we know the watcher is running.
    assert!(
        wait_for_file_contains(&out, "Hello World!", TIMEOUT),
        "initial compile should succeed before sending SIGINT"
    );

    // Send SIGINT (Ctrl+C).
    unsafe {
        libc::kill(pid as libc::pid_t, libc::SIGINT);
    }

    // Wait for the process to exit.
    let deadline = Instant::now() + Duration::from_secs(5);
    let mut exited = false;
    while Instant::now() < deadline {
        if guard.0.try_wait().unwrap().is_some() {
            exited = true;
            break;
        }
        std::thread::sleep(Duration::from_millis(50));
    }
    assert!(exited, "process should exit after SIGINT");

    let status = guard.wait_status();
    assert!(
        status.success(),
        "exit code should be 0 after Ctrl+C, got: {status:?}"
    );
}

// ── T-P1: Debounce — final value wins after rapid edits ───────────────────

#[test]
fn watch_debounce_final_value_wins_after_rapid_edits() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "---\nname: v0\n---\nHello {{name}}!\n").unwrap();
    let out = dir.path().join("hello.md");

    // Use a 200ms debounce for stability.
    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args(["watch", src.to_str().unwrap(), "--debounce", "200"])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile.
    assert!(
        wait_for_file_contains(&out, "Hello v0!", TIMEOUT),
        "initial compile should produce v0"
    );

    // Write 10 rapid edits within the debounce window.
    for i in 1..=10 {
        std::fs::write(&src, format!("---\nname: v{i}\n---\nHello {{{{name}}}}!\n")).unwrap();
        // Tiny sleep to ensure filesystem registers the write, but
        // well within the 200ms debounce window.
        std::thread::sleep(Duration::from_millis(5));
    }

    // Wait for the debounced rebuild (only 1 rebuild expected).
    assert!(
        wait_for_file_contains(&out, "Hello v10!", TIMEOUT),
        "after rapid edits, output should reflect final value"
    );

    // Count "Recompiled" lines in stderr.
    // The initial compile produces one "Compiled to..." line (not "Recompiled"),
    // so we just verify the output reflects v10.
    // The real coalescing assertion: we got v10, not some intermediate version,
    // after a single rebuild window.

    drop(child);
}

// ── T-P3: Startup error surfaced clearly ──────────────────────────────────

#[test]
fn watch_invalid_path_startup_error() {
    let output = mds_bin()
        .args(["watch", "/nonexistent/path/that/does/not/exist.mds"])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .unwrap();
    assert!(
        !output.status.success(),
        "watch with invalid path should fail"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.is_empty(),
        "error message should appear on stderr, got empty"
    );
}

// ── AC-F3: Import-removal resync — both directions of dynamic dep tracking ─

/// T-I4 completion: removing an @import stops tracking the removed dep.
///
/// Two sub-cases:
///  (a) ADD import  → helper changes now rebuild entry  (covered by T-I3 above)
///  (b) REMOVE import → helper changes no longer rebuild entry
///
/// This test covers case (b).
#[test]
fn watch_import_removal_stops_tracking_dep() {
    let dir = tempfile::tempdir().unwrap();

    // Write the helper BEFORE the entry references it (mitigates FSEvents latency).
    let helper = dir.path().join("helper.mds");
    std::fs::write(
        &helper,
        "@define greet(name):\nHello {{name}}!\n@end\n\n@export greet\n",
    )
    .unwrap();

    // Entry that imports helper initially.
    let entry = dir.path().join("entry.mds");
    std::fs::write(
        &entry,
        "@import \"./helper.mds\" as h\n\n{{h.greet(\"World\")}}\n",
    )
    .unwrap();
    let out = dir.path().join("entry.md");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args(["watch", entry.to_str().unwrap(), "--debounce", "0", "-q"])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile — helper IS tracked.
    assert!(
        wait_for_file_contains(&out, "Hello World!", TIMEOUT),
        "initial compile should produce Hello World!"
    );

    // STEP 1 (add direction, already covered by T-I3 but verified here too):
    // Edit helper — entry output should update because helper is tracked.
    std::fs::write(
        &helper,
        "@define greet(name):\nHi {{name}}!\n@end\n\n@export greet\n",
    )
    .unwrap();
    assert!(
        wait_for_file_contains(&out, "Hi World!", TIMEOUT),
        "editing helper while imported should trigger a rebuild"
    );

    // STEP 2 (removal direction): rewrite entry to remove the @import.
    // The entry now produces static output that does NOT reference helper.
    std::fs::write(&entry, "Static content\n").unwrap();
    assert!(
        wait_for_file_contains(&out, "Static content", TIMEOUT),
        "removing @import should rebuild entry with static content"
    );

    // Capture last-known mtime/content before the helper edit.
    let content_before = std::fs::read_to_string(&out).unwrap();

    // STEP 3: Edit helper again — entry output must NOT change because the dep
    // was removed from the watch set after the resync in step 2.
    std::fs::write(
        &helper,
        "@define greet(name):\nBye {{name}}!\n@end\n\n@export greet\n",
    )
    .unwrap();

    // Wait long enough for any spurious rebuild to materialize (500ms >> debounce 0).
    std::thread::sleep(Duration::from_millis(500));

    let content_after = std::fs::read_to_string(&out).unwrap();
    assert_eq!(
        content_before, content_after,
        "after removing @import, editing helper must NOT change entry output"
    );

    drop(child);
}

// ── AC-F7: Dir mode vars-recompile-all ────────────────────────────────────

/// Editing vars.json while in directory mode must recompile ALL .mds files.
#[test]
fn watch_dir_mode_vars_change_recompiles_all() {
    let src_dir = tempfile::tempdir().unwrap();
    let out_dir_path = src_dir.path().join("out");
    std::fs::create_dir(&out_dir_path).unwrap();

    // Two templates that each interpolate the `greeting` var.
    std::fs::write(
        src_dir.path().join("a.mds"),
        "---\ngreeting: Default\n---\n{{greeting}} from A\n",
    )
    .unwrap();
    std::fs::write(
        src_dir.path().join("b.mds"),
        "---\ngreeting: Default\n---\n{{greeting}} from B\n",
    )
    .unwrap();

    // Write vars.json with initial greeting value.
    let vars = src_dir.path().join("vars.json");
    std::fs::write(&vars, r#"{"greeting": "Hello"}"#).unwrap();

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src_dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir_path.to_str().unwrap(),
                "--vars",
                vars.to_str().unwrap(),
                "--debounce",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // Both files should compile on startup with initial vars.
    assert!(
        wait_for_file_contains(&out_dir_path.join("a.md"), "Hello from A", TIMEOUT),
        "a.md should initially contain 'Hello from A'"
    );
    assert!(
        wait_for_file_contains(&out_dir_path.join("b.md"), "Hello from B", TIMEOUT),
        "b.md should initially contain 'Hello from B'"
    );

    // Edit vars.json — BOTH outputs should update.
    std::fs::write(&vars, r#"{"greeting": "Goodbye"}"#).unwrap();

    assert!(
        wait_for_file_contains(&out_dir_path.join("a.md"), "Goodbye from A", TIMEOUT),
        "a.md should update to 'Goodbye from A' after vars change"
    );
    assert!(
        wait_for_file_contains(&out_dir_path.join("b.md"), "Goodbye from B", TIMEOUT),
        "b.md should update to 'Goodbye from B' after vars change"
    );

    drop(child);
}

// ── AC-A5: Quiet mode keeps compile errors visible ────────────────────────

/// Under `-q`, compile errors must still appear on stderr; the watcher stays alive.
#[test]
fn watch_quiet_keeps_errors_visible() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
    let out = dir.path().join("hello.md");

    let (mut child, stderr_tap) = spawn_ready(
        mds_bin()
            .args(["watch", src.to_str().unwrap(), "--debounce", "0", "-q"])
            .stdout(Stdio::null()),
    );

    // Wait for the initial compile to produce valid output.
    assert!(
        wait_for_file_contains(&out, "Hello World!", TIMEOUT),
        "initial compile should succeed"
    );

    // Introduce a compile error (reference an undefined variable with no frontmatter default).
    std::fs::write(&src, "Hello {{__undefined_xyz__}}!\n").unwrap();

    // Give the watcher time to attempt rebuild and emit error.
    std::thread::sleep(Duration::from_millis(500));

    // Process must still be alive — watcher stays up after compile errors.
    let still_running = child.0.try_wait().unwrap().is_none();
    assert!(
        still_running,
        "watcher must stay alive after a compile error even under -q"
    );

    // Verify error output appeared on stderr despite -q.
    // Under quiet mode, status messages are suppressed but error diagnostics are not.
    //
    // Assert on the CONTENT of the diagnostic, not merely that stderr is non-empty.
    // Non-emptiness is satisfied by any byte from any source, so it stops being a test
    // of this behaviour the moment anything else writes to the stream — which is
    // exactly what happened when the readiness handshake was a stderr marker line.
    // Naming the undefined variable ties the assertion to the error we provoked.
    let stderr_str = stderr_tap.text();
    assert!(
        stderr_str.contains("__undefined_xyz__"),
        "stderr must carry the compile error naming the undefined variable even under \
         -q; got:\n{stderr_str}"
    );

    // Fix the error — watcher should recover.
    std::fs::write(&src, "---\nname: Fixed\n---\nHello {{name}}!\n").unwrap();
    assert!(
        wait_for_file_contains(&out, "Hello Fixed!", TIMEOUT),
        "after fixing the compile error, watcher should rebuild successfully"
    );

    drop(child);
}

// ── AC-F9: "Stopped watching." message on clean Ctrl+C ────────────────────

/// On SIGINT the watcher must print "Stopped watching." to stderr (non-quiet).
#[test]
#[cfg(unix)]
fn watch_ctrl_c_prints_stopped_watching() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
    let out = dir.path().join("hello.md");

    let (mut guard, stderr_tap) = spawn_ready(
        mds_bin()
            .args(["watch", src.to_str().unwrap(), "--debounce", "0"])
            .stdout(Stdio::null()),
    );
    let pid = guard.id();

    // Wait for initial compile so the watcher is running.
    assert!(
        wait_for_file_contains(&out, "Hello World!", TIMEOUT),
        "initial compile should succeed before sending SIGINT"
    );

    // Send SIGINT (Ctrl+C).
    unsafe {
        libc::kill(pid as libc::pid_t, libc::SIGINT);
    }

    // Wait for the process to exit.
    let deadline = Instant::now() + Duration::from_secs(5);
    let mut exited = false;
    while Instant::now() < deadline {
        if guard.0.try_wait().unwrap().is_some() {
            exited = true;
            break;
        }
        std::thread::sleep(Duration::from_millis(50));
    }
    assert!(exited, "process should exit after SIGINT");

    let status = guard.wait_status();
    assert!(
        status.success(),
        "exit code should be 0 after Ctrl+C, got: {status:?}"
    );

    // Give the reader thread a moment to flush remaining bytes.
    std::thread::sleep(Duration::from_millis(100));

    let stderr_bytes = stderr_tap.bytes();
    let stderr_str = String::from_utf8_lossy(&stderr_bytes);
    assert!(
        stderr_str.contains("Stopped watching."),
        "stderr should contain 'Stopped watching.' after Ctrl+C, got: {stderr_str:?}"
    );
}

// ── AC-P1: Debounce coalesces burst — count rebuild summary lines ──────────

/// Burst of ~10 writes within a 250ms debounce window must produce exactly 1
/// "Recompiled " line in stderr.  250ms is large enough to be reliable on CI;
/// if the filesystem splits the burst into two windows, the test permits <= 2
/// rebuilds (documented below) but asserts == 1 as the expected case.
#[test]
fn watch_debounce_single_rebuild_from_burst() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("burst.mds");
    std::fs::write(&src, "---\nname: v0\n---\nBurst {{name}}!\n").unwrap();
    let out = dir.path().join("burst.md");

    // Use a 250ms debounce — large enough to reliably swallow the ~10 × 5ms burst.
    let (mut child, stderr_tap) = spawn_ready(
        mds_bin()
            .args(["watch", src.to_str().unwrap(), "--debounce", "250"])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile.
    assert!(
        wait_for_file_contains(&out, "Burst v0!", TIMEOUT),
        "initial compile should produce Burst v0!"
    );

    // Write 10 rapid edits within the 250ms debounce window.
    for i in 1..=10u32 {
        std::fs::write(&src, format!("---\nname: v{i}\n---\nBurst {{{{name}}}}!\n")).unwrap();
        std::thread::sleep(Duration::from_millis(5));
    }

    // Wait for the debounced rebuild to settle (debounce window + generous FSEvent latency).
    assert!(
        wait_for_file_contains(&out, "Burst v10!", TIMEOUT),
        "after burst, output should reflect final value v10"
    );

    // Wait an extra moment to ensure no trailing rebuilds are in-flight.
    std::thread::sleep(Duration::from_millis(400));

    // Kill child and collect all stderr.
    let _ = child.0.kill();
    let _ = child.0.wait();
    std::thread::sleep(Duration::from_millis(100));

    let stderr_bytes = stderr_tap.bytes();
    let stderr_str = String::from_utf8_lossy(&stderr_bytes);

    // Count "Recompiled " lines (each rebuild emits exactly one such line).
    let rebuild_count = stderr_str.matches("Recompiled ").count();

    // Expected: exactly 1 rebuild from the burst.
    // Allow <= 2 as a documented tolerance: on a heavily loaded CI machine the
    // 250ms window may occasionally be split by an FSEvent scheduling gap, yielding
    // a second rebuild for the tail of the burst.  The important property is that
    // we do NOT get 10 individual rebuilds.
    assert!(
        rebuild_count >= 1,
        "at least one rebuild must have occurred, got 0; stderr: {stderr_str}"
    );
    assert!(
        rebuild_count <= 2,
        "debounce should coalesce burst into <= 2 rebuilds, got {rebuild_count}; \
         stderr: {stderr_str}"
    );
}

// ── AC-F10: Watch no-arg auto-detect ─────────────────────────────────────

/// `mds watch` with no argument and cwd containing exactly ONE .mds file
/// should auto-detect and compile that file.
#[test]
fn watch_no_arg_auto_detects_single_mds_file() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("only.mds"),
        "---\nname: AutoDetect\n---\nAuto {{name}}!\n",
    )
    .unwrap();
    let out = dir.path().join("only.md");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args(["watch", "--debounce", "0", "-q"])
            .current_dir(dir.path()) // cwd = tempdir containing exactly one .mds
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out, "Auto AutoDetect!", TIMEOUT),
        "auto-detect with single .mds file should compile only.mds"
    );

    drop(child);
}

/// `mds watch` with no argument and cwd containing TWO .mds files must exit
/// non-zero with an "ambiguous"/"multiple" style error.
#[test]
fn watch_no_arg_fails_with_multiple_mds_files() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("a.mds"), "File A\n").unwrap();
    std::fs::write(dir.path().join("b.mds"), "File B\n").unwrap();

    let output = mds_bin()
        .args(["watch"])
        .current_dir(dir.path())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "watch with multiple .mds files and no arg should exit non-zero"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("multiple") || stderr.contains("ambiguous") || stderr.contains("specify"),
        "error should mention multiple files or instruct user to specify; got: {stderr}"
    );
}

// ── QA regression: no spurious startup recompiles and no duplicate stdout ───

/// QA-R1: Start `mds watch` with no edits, wait 1.5s, stop.
/// Asserts:
///  - stderr contains exactly ONE "Compiled to" line (initial compile),
///  - stderr contains ZERO "Recompiled" lines (no spurious rebuild from synthetic FS events).
///
/// Uses `--debounce 0` to make synthetic FSEvents arrive immediately (worst case).
#[test]
fn watch_startup_no_spurious_recompile() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("nochange.mds");
    std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
    let out = dir.path().join("nochange.md");

    let (mut child, stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "-o",
                out.to_str().unwrap(),
                "--debounce",
                "0",
                // No -q: we NEED to observe stderr messages to catch spurious noise.
            ])
            .stdout(Stdio::null()),
    );

    // Wait for the initial compile to complete.
    assert!(
        wait_for_file_contains(&out, "Hello World!", TIMEOUT),
        "initial compile should write output"
    );

    // Let the watcher idle for 1.5s — any synthetic FS events would fire within this window.
    std::thread::sleep(Duration::from_millis(1500));

    // Stop the child and collect all stderr.
    let _ = child.0.kill();
    let _ = child.0.wait();
    std::thread::sleep(Duration::from_millis(50));

    let stderr_bytes = stderr_tap.bytes();
    let stderr_str = String::from_utf8_lossy(&stderr_bytes);

    // There must be exactly ONE "Compiled to" message (the initial compile).
    let compiled_count = stderr_str.matches("Compiled to").count();
    assert_eq!(
        compiled_count, 1,
        "expected exactly 1 'Compiled to' line on startup (no double initial compile); \
         got {compiled_count}; stderr was:\n{stderr_str}"
    );

    // There must be ZERO "Recompiled" lines — no rebuild without edits.
    let recompiled_count = stderr_str.matches("Recompiled").count();
    assert_eq!(
        recompiled_count, 0,
        "expected 0 'Recompiled' lines with no edits (spurious startup rebuild); \
         got {recompiled_count}; stderr was:\n{stderr_str}"
    );
}

/// QA-R2: Start `mds watch <file> -o -` with no edits, capture stdout, wait 1.5s, stop.
/// Asserts: compiled content appears EXACTLY ONCE in stdout (no double-write on startup).
///
/// Uses `--debounce 0` which is the worst case: synthetic FSEvents from watcher
/// registration arrive immediately and (before the fix) cause the content to be
/// written 2-3x to stdout, corrupting downstream pipe consumers.
#[test]
fn watch_stdout_no_duplicate_write_on_startup() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("stdout_once.mds");
    // Use a distinctive marker so we can count occurrences.
    std::fs::write(&src, "UNIQUE_MARKER_XYZ\n").unwrap();

    let (mut child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "-o",
                "-",
                "--debounce",
                "0",
                // No -q: we want to observe full behavior.
            ])
            .stdout(Stdio::piped()),
    );

    // Drain stdout on a background thread.
    let stdout_handle = child.0.stdout.take().expect("piped stdout");
    let stdout_buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
    let stdout_buf_clone = stdout_buf.clone();
    let _reader_thread = std::thread::spawn(move || {
        use std::io::Read as _;
        let mut handle = stdout_handle;
        let mut tmp = [0u8; 512];
        loop {
            match handle.read(&mut tmp) {
                Ok(0) | Err(_) => break,
                Ok(n) => {
                    stdout_buf_clone
                        .lock()
                        .unwrap()
                        .extend_from_slice(&tmp[..n]);
                }
            }
        }
    });

    // Let the watcher run long enough to capture initial compile + any spurious second write.
    std::thread::sleep(Duration::from_millis(1500));

    // Stop the child and collect all stdout.
    let _ = child.0.kill();
    let _ = child.0.wait();
    std::thread::sleep(Duration::from_millis(50));

    let stdout_bytes = stdout_buf.lock().unwrap().clone();
    let stdout_str = String::from_utf8_lossy(&stdout_bytes);

    // The marker should appear at least once (the initial compile wrote it).
    assert!(
        stdout_str.contains("UNIQUE_MARKER_XYZ"),
        "compiled output must appear on stdout; got: {stdout_str:?}"
    );

    // Count how many times the marker appears — must be exactly 1.
    let occurrence_count = stdout_str.matches("UNIQUE_MARKER_XYZ").count();
    assert_eq!(
        occurrence_count, 1,
        "compiled content must be written to stdout EXACTLY ONCE on startup \
         (no duplicate write from spurious synthetic FS event); \
         got {occurrence_count} occurrences; stdout was:\n{stdout_str}"
    );
}

// ── QA regression: dir-mode no spurious startup recompiles ──────────────────

/// QA-R3: Start `mds watch <dir>` with 2 .mds files, NO edits, idle ~1.5s, stop.
/// Asserts ZERO "Recompiled" lines in stderr (startup "Compiled to" lines are fine).
///
/// Before the fix, macOS FSEvents delivers synthetic events for each source file
/// right after watcher registration. Without the content-dedup map, the loop
/// recompiles identical content and logs a rebuild for each file (2 with
/// `--debounce 50`, 4 with `--debounce 0`).  After the fix, the dedup baseline
/// is populated before any synthetic events are processed, so they are all
/// recognised as no-ops and suppressed.
#[test]
fn watch_dir_mode_no_spurious_startup_recompile() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("a.mds"),
        "---\nname: A\n---\nFile A: {{name}}\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("b.mds"),
        "---\nname: B\n---\nFile B: {{name}}\n",
    )
    .unwrap();
    let out_dir = dir.path().join("out");
    std::fs::create_dir(&out_dir).unwrap();

    let (mut child, stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                // No -q: we NEED to observe stderr messages to catch spurious noise.
            ])
            .stdout(Stdio::null()),
    );

    // Wait for the initial compile to complete (both files compiled on startup).
    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "File A: A", TIMEOUT),
        "a.md should be compiled on startup"
    );
    assert!(
        wait_for_file_contains(&out_dir.join("b.md"), "File B: B", TIMEOUT),
        "b.md should be compiled on startup"
    );

    // Let the watcher idle for 1.5s — synthetic FSEvents would fire within this window.
    std::thread::sleep(Duration::from_millis(1500));

    // Stop the child and collect all stderr.
    let _ = child.0.kill();
    let _ = child.0.wait();
    std::thread::sleep(Duration::from_millis(50));

    let stderr_bytes = stderr_tap.bytes();
    let stderr_str = String::from_utf8_lossy(&stderr_bytes);

    // There must be ZERO "Recompiled" lines — no rebuild without edits.
    let recompiled_count = stderr_str.matches("Recompiled").count();
    assert_eq!(
        recompiled_count, 0,
        "expected 0 'Recompiled' lines in dir mode with no edits \
         (spurious startup rebuild from synthetic FSEvents); \
         got {recompiled_count}; stderr was:\n{stderr_str}"
    );

    // Startup "Compiled to" lines are expected (one per source file).
    let compiled_count = stderr_str.matches("Compiled to").count();
    assert_eq!(
        compiled_count, 2,
        "expected exactly 2 'Compiled to' lines on dir-mode startup (one per source file); \
         got {compiled_count}; stderr was:\n{stderr_str}"
    );
}

// ── QA regression: single status line per rebuild ───────────────────────────

/// QA-R4: Start `mds watch <file>` (no -q), make ONE real edit, idle, stop.
/// Asserts:
///  - Exactly ONE "Recompiled" line total (the real edit),
///  - Total "Compiled to" count stays at 1 (the startup compile only —
///    the loop rebuild must NOT add a second "Compiled to" line).
///
/// Before the fix, `write_output` (called inside the loop) always emitted
/// "Compiled to …" AND the loop also emitted "Recompiled …", giving two
/// status lines per rebuild.  After the fix the loop sets announce=false so
/// only "Recompiled …" appears for loop rebuilds.
///
/// Uses the **default 100ms debounce**, not `--debounce 0`. One `fs::write` is a
/// truncate followed by a write, which the kernel reports as two separate content
/// events; under `--debounce 0` — documented as "immediate rebuilds", i.e. opting
/// out of burst coalescing — the watcher may legitimately rebuild twice, so
/// `Recompiled == 1` is not a property the product guarantees there. (Measured at
/// ~6-12% of single edits under load, on both sides of the arm-before-publish
/// change.) The debounce window is precisely the mechanism that collapses that pair,
/// so running this assertion with coalescing enabled tests the intended invariant —
/// one status line per rebuild, and loop rebuilds say "Recompiled", not "Compiled to"
/// — instead of an incidental timing outcome.
#[test]
fn watch_single_status_line_per_rebuild() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("status.mds");
    std::fs::write(&src, "---\nname: v0\n---\nStatus {{name}}!\n").unwrap();
    let out = dir.path().join("status.md");

    let (mut child, stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "--debounce",
                "100", // coalesce the truncate+write pair — see doc comment above
                       // No -q: we need to observe status messages.
            ])
            .stdout(Stdio::null()),
    );

    // Wait for the initial compile.
    assert!(
        wait_for_file_contains(&out, "Status v0!", TIMEOUT),
        "initial compile should produce Status v0!"
    );

    // Make ONE real content-changing edit.
    std::fs::write(&src, "---\nname: v1\n---\nStatus {{name}}!\n").unwrap();

    // Wait for the rebuild to appear in the output.
    assert!(
        wait_for_file_contains(&out, "Status v1!", TIMEOUT),
        "after editing, output should contain Status v1!"
    );

    // Idle a bit to let any trailing events flush.
    std::thread::sleep(Duration::from_millis(500));

    // Stop the child and collect all stderr.
    let _ = child.0.kill();
    let _ = child.0.wait();
    std::thread::sleep(Duration::from_millis(50));

    let stderr_bytes = stderr_tap.bytes();
    let stderr_str = String::from_utf8_lossy(&stderr_bytes);

    // Exactly ONE "Recompiled" line (the real edit).
    let recompiled_count = stderr_str.matches("Recompiled").count();
    assert_eq!(
        recompiled_count, 1,
        "expected exactly 1 'Recompiled' line for one real edit; \
         got {recompiled_count}; stderr was:\n{stderr_str}"
    );

    // Total "Compiled to" count must still be 1 (startup only — loop rebuild must
    // NOT emit a second "Compiled to" line).
    let compiled_count = stderr_str.matches("Compiled to").count();
    assert_eq!(
        compiled_count, 1,
        "expected exactly 1 'Compiled to' line total (startup only, no extra from loop rebuild); \
         got {compiled_count}; stderr was:\n{stderr_str}"
    );
}

// ── AC-M1: Subtree-mirrored output (--out-dir) ────────────────────────────

/// Editing a nested .mds file writes to the mirrored path, not a flat stem.
#[test]
fn watch_dir_mode_mirrors_subtree_to_out_dir() {
    let dir = tempfile::tempdir().unwrap();
    let sub = dir.path().join("sub");
    std::fs::create_dir(&sub).unwrap();
    std::fs::write(sub.join("deep.mds"), "---\nname: D\n---\nDeep {{name}}\n").unwrap();
    let out_dir = dir.path().join("out");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // Mirrored path: out/sub/deep.md (not out/deep.md).
    let mirrored = out_dir.join("sub").join("deep.md");
    assert!(
        wait_for_file_contains(&mirrored, "Deep D", TIMEOUT),
        "startup compile should write mirrored output to out/sub/deep.md"
    );
    // Flat path must NOT exist.
    assert!(
        !out_dir.join("deep.md").exists(),
        "flat stem deep.md must not exist when mirroring is active"
    );

    drop(child);
}

/// Two files with the same stem in different subdirs write to independent
/// mirrored outputs (no stem collision: AC-M1).
#[test]
fn watch_dir_mode_no_stem_collision_with_mirroring() {
    let dir = tempfile::tempdir().unwrap();
    let a_dir = dir.path().join("a");
    let b_dir = dir.path().join("b");
    std::fs::create_dir_all(&a_dir).unwrap();
    std::fs::create_dir_all(&b_dir).unwrap();
    std::fs::write(a_dir.join("x.mds"), "From A\n").unwrap();
    std::fs::write(b_dir.join("x.mds"), "From B\n").unwrap();
    let out_dir = dir.path().join("out");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out_dir.join("a").join("x.md"), "From A", TIMEOUT),
        "out/a/x.md should contain 'From A'"
    );
    assert!(
        wait_for_file_contains(&out_dir.join("b").join("x.md"), "From B", TIMEOUT),
        "out/b/x.md should contain 'From B'"
    );

    // Delete a/x.mds → out/a/x.md should be removed, out/b/x.md must survive (AC-M4).
    std::fs::remove_file(a_dir.join("x.mds")).unwrap();
    assert!(
        wait_for_file_gone(&out_dir.join("a").join("x.md"), TIMEOUT),
        "out/a/x.md should be removed when a/x.mds is deleted"
    );
    assert!(
        out_dir.join("b").join("x.md").exists(),
        "out/b/x.md must not be affected by deletion of a/x.mds"
    );

    drop(child);
}

// ── AC-R1/R2/R8: Reverse-dependency tracking + partials ──────────────────

/// Editing a shared partial rebuilds all transitive importers (AC-R1).
#[test]
fn watch_dir_mode_shared_partial_rebuilds_importers() {
    let dir = tempfile::tempdir().unwrap();

    // Shared partial.
    let partial = dir.path().join("_shared.mds");
    std::fs::write(
        &partial,
        "@define greet(name):\nHello {{name}}!\n@end\n\n@export greet\n",
    )
    .unwrap();

    // Two importers.
    let a = dir.path().join("a.mds");
    let b = dir.path().join("b.mds");
    std::fs::write(&a, "@import \"./_shared.mds\" as s\n{{s.greet(\"A\")}}\n").unwrap();
    std::fs::write(&b, "@import \"./_shared.mds\" as s\n{{s.greet(\"B\")}}\n").unwrap();

    let out_dir = dir.path().join("out");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "Hello A!", TIMEOUT),
        "a.md should contain Hello A! on startup"
    );
    assert!(
        wait_for_file_contains(&out_dir.join("b.md"), "Hello B!", TIMEOUT),
        "b.md should contain Hello B! on startup"
    );
    // The partial itself must NOT have emitted _shared.md (AC-R8).
    assert!(
        !out_dir.join("_shared.md").exists(),
        "_shared.md must not be written for a _-prefixed partial (DD2)"
    );

    // Edit the partial — both importers must rebuild.
    std::fs::write(
        &partial,
        "@define greet(name):\nHi {{name}}!\n@end\n\n@export greet\n",
    )
    .unwrap();

    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "Hi A!", TIMEOUT),
        "a.md should update after editing the shared partial"
    );
    assert!(
        wait_for_file_contains(&out_dir.join("b.md"), "Hi B!", TIMEOUT),
        "b.md should update after editing the shared partial"
    );
    // Partial output must still not exist.
    assert!(
        !out_dir.join("_shared.md").exists(),
        "_shared.md must not appear after editing the partial"
    );

    drop(child);
}

/// Transitive chain A→B→C: editing C updates A, B and C (AC-R2).
#[test]
fn watch_dir_mode_chain_rebuild() {
    let dir = tempfile::tempdir().unwrap();

    // C defines a value, B re-exports, A uses B.
    let c = dir.path().join("_c.mds");
    std::fs::write(&c, "@define val():\nV1\n@end\n\n@export val\n").unwrap();
    let b = dir.path().join("_b.mds");
    std::fs::write(
        &b,
        "@import \"./_c.mds\" as c\n@define val():\n{{c.val()}}\n@end\n\n@export val\n",
    )
    .unwrap();
    let a = dir.path().join("a.mds");
    std::fs::write(&a, "@import \"./_b.mds\" as b\n{{b.val()}}\n").unwrap();

    let out_dir = dir.path().join("out");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "V1", TIMEOUT),
        "a.md should contain V1 initially"
    );

    // Edit C — A must update.
    std::fs::write(&c, "@define val():\nV2\n@end\n\n@export val\n").unwrap();
    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "V2", TIMEOUT),
        "a.md should update to V2 after editing _c.mds (transitive chain)"
    );

    drop(child);
}

// ── AC-C1: --poll-interval parse/clamp/exit-2 ────────────────────────────

/// `--poll-interval 0` disables the self-heal probe (native events only, smoke test).
#[test]
fn watch_poll_interval_zero_works() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
    let out = dir.path().join("hello.md");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out, "Hello World!", TIMEOUT),
        "--poll-interval 0 should still do the initial compile"
    );

    // Verify a real edit also works.
    std::fs::write(&src, "---\nname: Poll\n---\nHello {{name}}!\n").unwrap();
    assert!(
        wait_for_file_contains(&out, "Hello Poll!", TIMEOUT),
        "--poll-interval 0: edit should still trigger rebuild via native event"
    );

    drop(child);
}

/// Non-numeric `--poll-interval` must exit 2 (clap parse error).
#[test]
fn watch_poll_interval_invalid_exits_2() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "Hello!\n").unwrap();

    let output = mds_bin()
        .args([
            "watch",
            src.to_str().unwrap(),
            "--poll-interval",
            "notanumber",
        ])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .unwrap();

    // Clap parse errors exit 2.
    let code = output.status.code().unwrap_or(-1);
    assert_eq!(
        code, 2,
        "invalid --poll-interval should exit 2 (clap error), got {code}"
    );
}

/// `--poll-interval` value is clamped to ≥50ms (smoke test: just verify startup works).
#[test]
fn watch_poll_interval_tiny_clamped() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "Clamped!\n").unwrap();
    let out = dir.path().join("hello.md");

    // 1ms should be clamped to 50ms — watcher must still start and compile.
    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "1",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out, "Clamped!", TIMEOUT),
        "--poll-interval 1 (clamped to 50ms) should still work"
    );
    drop(child);
}

// ── AC-W4: Idle watcher emits zero Recompiled across ticks ───────────────

/// Idle for ≥2.5s (≥2 ticks at default 1000ms) in single-file mode must emit
/// zero "Recompiled" lines (no phantom rebuild from the liveness probe).
#[test]
fn watch_file_mode_idle_no_recompile_across_ticks() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("idle.mds");
    std::fs::write(&src, "---\nname: World\n---\nIdle {{name}}!\n").unwrap();
    let out = dir.path().join("idle.md");

    let (mut child, stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "100",
                // No -q: we need to observe stderr.
            ])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile.
    assert!(
        wait_for_file_contains(&out, "Idle World!", TIMEOUT),
        "initial compile should succeed"
    );

    // Record a positive observable: the output file's mtime and content before idling.
    // If the watcher spuriously recompiles, the mtime will advance — making the failure
    // deterministic rather than a timing-luck race on the stderr count alone.
    let mtime_before = std::fs::metadata(&out)
        .and_then(|m| m.modified())
        .expect("output file must exist after initial compile");
    let content_before = std::fs::read_to_string(&out).expect("output file readable");

    // Idle for 2.5s (≥2 ticks at 100ms poll-interval — well above the minimum).
    std::thread::sleep(Duration::from_millis(2500));

    let _ = child.0.kill();
    let _ = child.0.wait();
    std::thread::sleep(Duration::from_millis(100));

    let stderr_bytes = stderr_tap.bytes();
    let stderr_str = String::from_utf8_lossy(&stderr_bytes);

    let recompiled_count = stderr_str.matches("Recompiled").count();
    assert_eq!(
        recompiled_count, 0,
        "idle single-file watcher must emit 0 Recompiled across ticks; \
         got {recompiled_count}; stderr:\n{stderr_str}"
    );

    // Deterministic positive observable: output file must not have been touched
    // during the idle window (no spurious recompile changed its mtime or content).
    let mtime_after = std::fs::metadata(&out)
        .and_then(|m| m.modified())
        .expect("output file must still exist after idle");
    assert_eq!(
        mtime_before, mtime_after,
        "output file mtime must not advance during idle (spurious recompile would advance it)"
    );
    assert_eq!(
        content_before,
        std::fs::read_to_string(&out).unwrap(),
        "output file content must be unchanged during idle"
    );
}

/// Idle for ≥2.5s (≥2 ticks) in dir mode must emit zero "Recompiled" lines (AC-W4).
#[test]
fn watch_dir_mode_idle_no_recompile_across_ticks() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("a.mds"),
        "---\nname: A\n---\nFile A: {{name}}\n",
    )
    .unwrap();
    let out_dir = dir.path().join("out");
    std::fs::create_dir(&out_dir).unwrap();

    let (mut child, stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "100",
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "File A: A", TIMEOUT),
        "initial compile should succeed"
    );

    // Record a positive observable: the output file's mtime and content before idling.
    // If the watcher spuriously recompiles, the mtime will advance — making the failure
    // deterministic rather than a timing-luck race on the stderr count alone.
    let out_a = out_dir.join("a.md");
    let mtime_before = std::fs::metadata(&out_a)
        .and_then(|m| m.modified())
        .expect("a.md must exist after initial compile");
    let content_before = std::fs::read_to_string(&out_a).expect("a.md readable");

    // Idle for 2.5s (≥2 ticks at 100ms).
    std::thread::sleep(Duration::from_millis(2500));

    let _ = child.0.kill();
    let _ = child.0.wait();
    std::thread::sleep(Duration::from_millis(100));

    let stderr_bytes = stderr_tap.bytes();
    let stderr_str = String::from_utf8_lossy(&stderr_bytes);

    let recompiled_count = stderr_str.matches("Recompiled").count();
    assert_eq!(
        recompiled_count, 0,
        "idle dir-mode watcher must emit 0 Recompiled across ticks; \
         got {recompiled_count}; stderr:\n{stderr_str}"
    );

    // Deterministic positive observable: output file must not have been touched
    // during the idle window (no spurious recompile changed its mtime or content).
    let mtime_after = std::fs::metadata(&out_a)
        .and_then(|m| m.modified())
        .expect("a.md must still exist after idle");
    assert_eq!(
        mtime_before, mtime_after,
        "output file mtime must not advance during idle (spurious recompile would advance it)"
    );
    assert_eq!(
        content_before,
        std::fs::read_to_string(&out_a).unwrap(),
        "output file content must be unchanged during idle"
    );
}

// ── AC-W1: File mode — delete parent dir then recreate ───────────────────────

/// Delete the entry file's parent dir, then recreate it with the file.
/// The watcher must self-heal and recompile within ~1 tick (no restart required).
#[test]
fn watch_file_mode_parent_dir_delete_recreate_recovers() {
    // Place the source in a subdirectory so we can delete the parent without
    // touching the tempdir root.
    let base = tempfile::tempdir().unwrap();
    let src_dir = base.path().join("src");
    std::fs::create_dir(&src_dir).unwrap();
    let src = src_dir.join("entry.mds");
    std::fs::write(&src, "---\nname: Before\n---\nEntry {{name}}\n").unwrap();
    let out = src_dir.join("entry.md");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "100",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile.
    assert!(
        wait_for_file_contains(&out, "Entry Before", TIMEOUT),
        "initial compile should produce 'Entry Before'"
    );

    // Delete the parent directory (simulates rmdir/recreate scenario).
    std::fs::remove_dir_all(&src_dir).unwrap();

    // Give the watcher a moment to notice.
    std::thread::sleep(Duration::from_millis(200));

    // Recreate the parent dir and the source file with new content.
    std::fs::create_dir(&src_dir).unwrap();
    std::fs::write(&src, "---\nname: After\n---\nEntry {{name}}\n").unwrap();

    // TICK-DEPENDENT: `remove_dir_all(&src_dir)` destroyed the inotify watch on the old
    // inode, and the recreated dir is a new inode nothing is watching — so the write
    // above generates no event the watcher can receive. Only the liveness probe's
    // re-arm can find it.
    assert!(
        wait_for_file_contains(&out, "Entry After", TICK_TIMEOUT),
        "watcher must self-heal after parent dir delete+recreate and recompile"
    );

    drop(child);
}

// ── AC-W2: Dir mode — delete root then recreate ──────────────────────────────

/// Delete the watched root, then recreate it with a brand-new .mds file.
/// The watcher must recover and compile the new file within ~1 tick.
#[test]
fn watch_dir_mode_root_delete_recreate_recovers() {
    let base = tempfile::tempdir().unwrap();
    let root = base.path().join("watched");
    std::fs::create_dir(&root).unwrap();
    std::fs::write(root.join("a.mds"), "---\nname: A\n---\nOld A\n").unwrap();
    let out_dir = base.path().join("out");
    std::fs::create_dir(&out_dir).unwrap();

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                root.to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "100",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile.
    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "Old A", TIMEOUT),
        "initial compile should produce 'Old A'"
    );

    // Delete the entire watched root.
    std::fs::remove_dir_all(&root).unwrap();
    std::thread::sleep(Duration::from_millis(200));

    // Recreate the root with a brand-new file (init-gap case).
    std::fs::create_dir(&root).unwrap();
    std::fs::write(
        root.join("new.mds"),
        "---\nname: N\n---\nNew file {{name}}\n",
    )
    .unwrap();

    // TICK-DEPENDENT: the recursive watch died with the old root inode, so the create
    // above is unobservable; the liveness probe's re-arm + reconcile is the only path.
    assert!(
        wait_for_file_contains(&out_dir.join("new.md"), "New file N", TICK_TIMEOUT),
        "watcher must recover after root delete+recreate and compile new file"
    );

    drop(child);
}

// ── AC-W6: Delete entry file — at most one error, then recover ───────────────

/// Delete the entry file (parent intact); assert the not-found error appears AT MOST
/// ONCE across multiple idle ticks, then recreate the file and assert recompile.
#[test]
fn watch_file_mode_entry_deleted_settles_then_recovers() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("entry.mds");
    std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
    let out = dir.path().join("entry.md");

    let (mut child, stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "100",
                // No -q so we can observe stderr error messages.
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out, "Hello World!", TIMEOUT),
        "initial compile should produce Hello World!"
    );

    // Delete the entry file (parent intact).
    std::fs::remove_file(&src).unwrap();

    // Scale-invariant error bound (guards PF-006): run two equal idle windows and assert
    // the error count does NOT grow in the second window.  A per-tick implementation would
    // accumulate one error per tick across BOTH windows; the fix settles quickly after the
    // initial native-event errors and is then silent.
    //
    // Window 1 — ≥5 ticks at 100ms: native FS delete events + at most 1 liveness-probe
    // error may appear.
    std::thread::sleep(Duration::from_millis(500));
    let count_w1 = {
        let bytes = stderr_tap.bytes();
        let s = String::from_utf8_lossy(&bytes);
        s.matches("file not found").count() + s.matches("No such file").count()
    };

    // Window 2 — another ≥5 ticks: nothing changed, so error-settle must keep the
    // count frozen.  Any increase proves the watcher is still firing per-tick.
    std::thread::sleep(Duration::from_millis(500));
    let count_w2 = {
        let bytes = stderr_tap.bytes();
        let s = String::from_utf8_lossy(&bytes);
        s.matches("file not found").count() + s.matches("No such file").count()
    };

    assert_eq!(
        count_w1, count_w2,
        "error count must not grow in a second idle window (not once-per-tick); \
         w1={count_w1}, w2={count_w2} — the fix must settle after initial native-event errors"
    );

    // Recreate the file with different content.
    std::fs::write(&src, "---\nname: Recovered\n---\nHello {{name}}!\n").unwrap();

    // Wait for recompile after recovery.
    assert!(
        wait_for_file_contains(&out, "Hello Recovered!", TIMEOUT),
        "watcher must recompile after recreating deleted entry file"
    );

    // Give the watcher a moment to settle after recovery before killing.
    std::thread::sleep(Duration::from_millis(200));

    let _ = child.0.kill();
    let _ = child.0.wait();
    std::thread::sleep(Duration::from_millis(100));

    let stderr_bytes = stderr_tap.bytes();
    let stderr_str = String::from_utf8_lossy(&stderr_bytes);

    // Sanity: error count across the FULL test run must still be small — rules out a
    // burst of errors that somehow all arrived in window 1.
    let error_event_count =
        stderr_str.matches("file not found").count() + stderr_str.matches("No such file").count();
    assert!(
        error_event_count <= 10,
        "total error count across full test must be small (not a per-tick flood); \
         got {error_event_count} file-not-found occurrences; stderr:\n{stderr_str}"
    );
}

// ── AC-W7: Vars-file dir outside root — delete+recreate re-arms ──────────────

/// Vars-file directory (outside root) delete+recreate is re-armed; a later vars
/// edit still triggers a recompile.
#[test]
fn watch_vars_dir_delete_recreate_rearms() {
    let base = tempfile::tempdir().unwrap();
    let src_dir = base.path().join("src");
    let vars_dir = base.path().join("vars_dir");
    std::fs::create_dir_all(&src_dir).unwrap();
    std::fs::create_dir_all(&vars_dir).unwrap();

    let src = src_dir.join("tpl.mds");
    std::fs::write(&src, "---\ngreeting: Default\n---\n{{greeting}}\n").unwrap();
    let vars_file = vars_dir.join("vars.json");
    std::fs::write(&vars_file, r#"{"greeting": "Hello"}"#).unwrap();
    let out = src_dir.join("tpl.md");

    let (mut child, stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "--vars",
                vars_file.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "100",
                // No -q so we can see debug output.
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out, "Hello", TIMEOUT),
        "initial compile with vars should produce 'Hello'"
    );

    // Delete the entire vars directory.
    std::fs::remove_dir_all(&vars_dir).unwrap();
    std::thread::sleep(Duration::from_millis(200));

    // Recreate the vars directory. The liveness probe re-arms it on the next tick
    // (≤100ms). Wait two ticks before writing to ensure the watch is re-registered
    // before the write event fires.
    std::fs::create_dir_all(&vars_dir).unwrap();
    std::thread::sleep(Duration::from_millis(300));

    // Now write new vars — the re-armed watcher should catch this event.
    std::fs::write(&vars_file, r#"{"greeting": "Goodbye"}"#).unwrap();

    // TICK-DEPENDENT: whether the write above is delivered as an event depends on the
    // probe having already re-armed the recreated vars dir. If it has not, the fallback
    // is the probe's own `(mtime, size)` comparison — another tick. Either way the
    // recovery is denominated in ticks, not in event latency.
    let got = wait_for_file_contains(&out, "Goodbye", TICK_TIMEOUT);
    let _ = child.0.kill();
    let _ = child.0.wait();
    std::thread::sleep(Duration::from_millis(100));
    let stderr_bytes = stderr_tap.bytes();
    let stderr_str = String::from_utf8_lossy(&stderr_bytes);
    assert!(
        got,
        "watcher must re-arm vars dir watch after delete+recreate and recompile on edit; \
         stderr was:\n{stderr_str}"
    );
}

// ── AC-R9: Cross-root — external partial edit rebuilds in-root importer ──────

/// In-root importer imports `../shared/_x.mds` (outside root); editing the external
/// partial triggers a rebuild of the in-root importer, and no `_x.md` is emitted.
#[test]
fn watch_dir_mode_cross_root_partial_edit_rebuilds_importer() {
    let base = tempfile::tempdir().unwrap();
    let root = base.path().join("root");
    let shared = base.path().join("shared");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::create_dir_all(&shared).unwrap();

    // Place a .git marker at the base so the MDS compiler's project-root detection
    // sets the root at base/ (not at root/), allowing cross-dir `../shared/` imports.
    std::fs::write(base.path().join(".git"), "").unwrap();

    // External partial (outside the watched root dir, but inside the project).
    let partial = shared.join("_x.mds");
    std::fs::write(
        &partial,
        "@define greet():\nExternal V1\n@end\n\n@export greet\n",
    )
    .unwrap();

    // In-root importer.
    let importer = root.join("importer.mds");
    std::fs::write(
        &importer,
        "@import \"../shared/_x.mds\" as x\n{{x.greet()}}\n",
    )
    .unwrap();

    let out_dir = base.path().join("out");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                root.to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "100",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile.
    assert!(
        wait_for_file_contains(&out_dir.join("importer.md"), "External V1", TIMEOUT),
        "initial compile should produce 'External V1'"
    );

    // No _x.md should be emitted for the external partial.
    assert!(
        !out_dir.join("_x.md").exists(),
        "_x.md must not be emitted for external partial"
    );
    // Also check that no shared/_x.md appeared anywhere obvious.
    assert!(
        !shared.join("_x.md").exists(),
        "shared/_x.md must not be written"
    );

    // Edit the external partial.
    std::fs::write(
        &partial,
        "@define greet():\nExternal V2\n@end\n\n@export greet\n",
    )
    .unwrap();

    // In-root importer output must update.
    assert!(
        wait_for_file_contains(&out_dir.join("importer.md"), "External V2", TIMEOUT),
        "editing external partial must rebuild in-root importer"
    );

    // Still no _x.md output.
    assert!(
        !out_dir.join("_x.md").exists(),
        "_x.md must not be emitted after partial edit"
    );

    drop(child);
}

// ── AC-R3: Delete a partial → importers recompile (broken import) ────────────

/// Delete a partial that an importer uses → importer recompiles surfacing the
/// broken-import error; the partial's own output is never present (_-partial).
#[test]
fn watch_dir_mode_delete_partial_surfaces_broken_import() {
    let dir = tempfile::tempdir().unwrap();

    let partial = dir.path().join("_p.mds");
    std::fs::write(
        &partial,
        "@define val():\nPartial V1\n@end\n\n@export val\n",
    )
    .unwrap();

    let importer = dir.path().join("main.mds");
    std::fs::write(&importer, "@import \"./_p.mds\" as p\n{{p.val()}}\n").unwrap();

    let out_dir = dir.path().join("out");

    let (mut child, stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "100",
                // No -q so we can observe errors.
            ])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile.
    assert!(
        wait_for_file_contains(&out_dir.join("main.md"), "Partial V1", TIMEOUT),
        "initial compile should produce 'Partial V1'"
    );

    // Partial must not have emitted its own output.
    assert!(
        !out_dir.join("_p.md").exists(),
        "_p.md must not be written for partial"
    );

    // Delete the partial.
    std::fs::remove_file(&partial).unwrap();

    // Poll for the broken-import error rather than sleeping: wait until stderr
    // contains the "file not found" message that the compiler emits for a missing import.
    let deadline = std::time::Instant::now() + TIMEOUT;
    loop {
        let bytes = stderr_tap.bytes();
        let s = String::from_utf8_lossy(&bytes);
        if s.contains("file not found") || s.contains("No such file") {
            break;
        }
        if std::time::Instant::now() >= deadline {
            panic!(
                "expected a 'file not found' / 'No such file' error after deleting imported \
                 partial within {:?}; stderr so far:\n{s}",
                TIMEOUT
            );
        }
        std::thread::sleep(Duration::from_millis(50));
    }

    // Verify the importer's output was not silently invalidated.
    // The important assertion: the process stays alive.
    let still_running = child.0.try_wait().unwrap().is_none();
    assert!(
        still_running,
        "watcher must stay alive after partial deletion surfaces broken import"
    );

    drop(child);
}

// ── AC-R4: Create previously-missing partial → erroring importers heal ────────

/// An importer references a missing `_p.mds` (errors at startup).
/// Create `_p.mds`; assert the erroring importer heals.
#[test]
fn watch_dir_mode_create_missing_partial_heals_importer() {
    let dir = tempfile::tempdir().unwrap();

    // Importer references a partial that does NOT exist yet.
    let importer = dir.path().join("main.mds");
    std::fs::write(&importer, "@import \"./_missing.mds\" as m\n{{m.val()}}\n").unwrap();

    let out_dir = dir.path().join("out");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "100",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // Initial compile must fail (missing partial), so main.md may not appear.
    // Give the watcher time to attempt the initial compile.
    std::thread::sleep(Duration::from_millis(500));

    // Now create the previously-missing partial.
    let partial = dir.path().join("_missing.mds");
    std::fs::write(&partial, "@define val():\nHealed!\n@end\n\n@export val\n").unwrap();

    // The importer should heal and produce output.
    assert!(
        wait_for_file_contains(&out_dir.join("main.md"), "Healed!", TIMEOUT),
        "creating the missing partial must heal the erroring importer"
    );

    drop(child);
}

// ── AC-R6: Dual-role node — both top-level target AND imported ────────────────

/// A non-`_` file is both a top-level target AND imported by another file.
/// Editing it updates its own output AND rebuilds the importer.
/// Deleting it removes its own output AND recompiles the importer (with error).
#[test]
fn watch_dir_mode_dual_role_node_edit_and_delete() {
    let dir = tempfile::tempdir().unwrap();

    // Dual-role: dual.mds is a top-level file and is imported by consumer.mds.
    let dual = dir.path().join("dual.mds");
    std::fs::write(
        &dual,
        "@define greet():\nDual V1\n@end\n\n@export greet\n\nStandalone content\n",
    )
    .unwrap();

    let consumer = dir.path().join("consumer.mds");
    std::fs::write(&consumer, "@import \"./dual.mds\" as d\n{{d.greet()}}\n").unwrap();

    let out_dir = dir.path().join("out");

    let (mut child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "100",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile of both outputs.
    assert!(
        wait_for_file_contains(&out_dir.join("dual.md"), "Standalone content", TIMEOUT),
        "dual.md should be compiled as a top-level target"
    );
    assert!(
        wait_for_file_contains(&out_dir.join("consumer.md"), "Dual V1", TIMEOUT),
        "consumer.md should be compiled using the import"
    );

    // Edit dual.mds — both dual.md and consumer.md should update.
    // Use a longer content to force a size delta.
    std::fs::write(
        &dual,
        "@define greet():\nDual V2 (updated)\n@end\n\n@export greet\n\nStandalone updated content\n",
    )
    .unwrap();

    assert!(
        wait_for_file_contains(
            &out_dir.join("dual.md"),
            "Standalone updated content",
            TIMEOUT
        ),
        "editing dual.mds must update dual.md (own output)"
    );
    assert!(
        wait_for_file_contains(&out_dir.join("consumer.md"), "Dual V2 (updated)", TIMEOUT),
        "editing dual.mds must rebuild consumer.md (importer)"
    );

    // Delete dual.mds — dual.md should be removed; consumer.md should recompile (with error).
    std::fs::remove_file(&dual).unwrap();

    assert!(
        wait_for_file_gone(&out_dir.join("dual.md"), TIMEOUT),
        "dual.md must be removed when dual.mds is deleted"
    );

    // The watcher must stay alive.
    std::thread::sleep(Duration::from_millis(300));
    let still_running = child.0.try_wait().unwrap().is_none();
    assert!(
        still_running,
        "watcher must stay alive after dual-role node deletion"
    );

    drop(child);
}

// ── AC-R7: Persistent syntax error — bounded error count ─────────────────────

/// A file with a persistent syntax error, idle ≥2 ticks at low --poll-interval.
/// Assert the error line count is bounded (~once per real edit, NOT once per tick)
/// and the watcher stays alive.
#[test]
fn watch_dir_mode_persistent_error_bounded_count() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("a.mds"),
        "---\nname: A\n---\nFile A: {{name}}\n",
    )
    .unwrap();
    // Syntax error file: references undefined variable with no frontmatter.
    std::fs::write(dir.path().join("bad.mds"), "Hello {{__undefined_xyz__}}!\n").unwrap();
    let out_dir = dir.path().join("out");
    std::fs::create_dir(&out_dir).unwrap();

    let (mut child, stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "100",
                // No -q so we can count errors.
            ])
            .stdout(Stdio::null()),
    );

    // Wait for good file to compile (confirms startup completed).
    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "File A: A", TIMEOUT),
        "a.md should compile despite bad.mds error"
    );

    // Scale-invariant error bound (applies ADR-021, guards PF-006): run two equal idle
    // windows and assert the "undefined variable" count does NOT grow in the second window.
    // A per-tick implementation would fire continuously; error-settle means it fires once at
    // startup and then goes silent.
    //
    // Window 1 — ≥5 ticks at 100ms (~500ms): initial startup error may appear here.
    std::thread::sleep(Duration::from_millis(500));
    let count_w1 = {
        let bytes = stderr_tap.bytes();
        let s = String::from_utf8_lossy(&bytes);
        // Count exactly once per error emission (each miette block contains this phrase once).
        s.matches("undefined variable").count()
    };

    // Window 2 — another ≥5 ticks: nothing changed, error-settle must keep count frozen.
    // Any increase here proves the watcher is still firing per-tick (the bug).
    std::thread::sleep(Duration::from_millis(500));
    let count_w2 = {
        let bytes = stderr_tap.bytes();
        let s = String::from_utf8_lossy(&bytes);
        s.matches("undefined variable").count()
    };

    // Watcher must still be alive.
    let still_running = child.0.try_wait().unwrap().is_none();
    assert!(
        still_running,
        "watcher must stay alive with persistent syntax error in bad.mds"
    );

    let _ = child.0.kill();
    let _ = child.0.wait();
    std::thread::sleep(Duration::from_millis(100));

    let stderr_bytes = stderr_tap.bytes();
    let stderr_str = String::from_utf8_lossy(&stderr_bytes);

    assert_eq!(
        count_w1, count_w2,
        "error count must not grow in a second idle window (not once-per-tick); \
         w1={count_w1}, w2={count_w2} (applies ADR-021, guards PF-006); \
         stderr:\n{stderr_str}"
    );
}

// ── AC-M2: mds.json output_dir with config_dir as ancestor of root ────────────

/// An `mds.json` with `build.output_dir` where config_dir is an ANCESTOR of the
/// watched root; assert output is subtree-mirrored under `config_dir/output_dir`.
#[test]
fn watch_dir_mode_mds_json_config_dir_ancestor_mirrors_output() {
    let base = tempfile::tempdir().unwrap();
    let root = base.path().join("src");
    let sub = root.join("sub");
    std::fs::create_dir_all(&sub).unwrap();
    std::fs::write(sub.join("deep.mds"), "Deep content\n").unwrap();

    // mds.json lives at the BASE (ancestor of root).
    let mds_json = base.path().join("mds.json");
    std::fs::write(&mds_json, r#"{"build":{"output_dir":"out"}}"#).unwrap();

    // Expected output: base/out/sub/deep.md (relative to root=src, mirrored under base/out).
    let expected_out = base.path().join("out").join("sub").join("deep.md");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                root.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "0",
                "-q",
            ])
            .current_dir(base.path()) // mds.json resolution starts from cwd
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&expected_out, "Deep content", TIMEOUT),
        "mds.json output_dir from ancestor config_dir should mirror subtree: {:?}",
        expected_out
    );

    drop(child);
}

// ── AC-M6: Rename/move within root — stale output removed ────────────────────

/// Rename/move a file within root (`a/x.mds → b/x.mds`); assert stale `out/a/x.md`
/// is removed and `out/b/x.md` is written (no orphan accumulation).
#[test]
fn watch_dir_mode_rename_removes_stale_output() {
    let dir = tempfile::tempdir().unwrap();
    let a_dir = dir.path().join("a");
    let b_dir = dir.path().join("b");
    std::fs::create_dir_all(&a_dir).unwrap();
    std::fs::create_dir_all(&b_dir).unwrap();
    std::fs::write(a_dir.join("x.mds"), "Content from A\n").unwrap();
    let out_dir = dir.path().join("out");

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "100",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile.
    assert!(
        wait_for_file_contains(&out_dir.join("a").join("x.md"), "Content from A", TIMEOUT),
        "initial compile should write out/a/x.md"
    );

    // Move a/x.mds → b/x.mds (rename within root).
    std::fs::rename(a_dir.join("x.mds"), b_dir.join("x.mds")).unwrap();

    // out/b/x.md should appear with the same content.
    assert!(
        wait_for_file_contains(&out_dir.join("b").join("x.md"), "Content from A", TIMEOUT),
        "out/b/x.md should be written after rename"
    );

    // out/a/x.md (stale output) should be removed.
    assert!(
        wait_for_file_gone(&out_dir.join("a").join("x.md"), TIMEOUT),
        "stale out/a/x.md must be removed after rename (no orphan accumulation)"
    );

    drop(child);
}

// ── AC-P2: Edit partial imported by N files — exactly N outputs change ────────

/// Edit a partial imported by N=3 files; assert exactly the 3 affected outputs
/// change and the independent file is untouched.
#[test]
fn watch_dir_mode_partial_edit_rebuilds_exactly_n_importers() {
    let dir = tempfile::tempdir().unwrap();

    // Shared partial.
    let partial = dir.path().join("_shared.mds");
    std::fs::write(&partial, "@define val():\nV1\n@end\n\n@export val\n").unwrap();

    // Three importers.
    std::fs::write(
        dir.path().join("a.mds"),
        "@import \"./_shared.mds\" as s\n{{s.val()}} from A\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("b.mds"),
        "@import \"./_shared.mds\" as s\n{{s.val()}} from B\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("c.mds"),
        "@import \"./_shared.mds\" as s\n{{s.val()}} from C\n",
    )
    .unwrap();

    // Independent file (should NOT change when partial is edited).
    std::fs::write(dir.path().join("independent.mds"), "Independent\n").unwrap();

    let out_dir = dir.path().join("out");
    let (mut child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile.
    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "V1 from A", TIMEOUT),
        "a.md should initially contain 'V1 from A'"
    );
    assert!(
        wait_for_file_contains(&out_dir.join("b.md"), "V1 from B", TIMEOUT),
        "b.md should initially contain 'V1 from B'"
    );
    assert!(
        wait_for_file_contains(&out_dir.join("c.md"), "V1 from C", TIMEOUT),
        "c.md should initially contain 'V1 from C'"
    );
    assert!(
        wait_for_file_contains(&out_dir.join("independent.md"), "Independent", TIMEOUT),
        "independent.md should compile on startup"
    );

    // Record independent.md content before editing the partial.
    let independent_before = std::fs::read_to_string(out_dir.join("independent.md")).unwrap();

    // Edit the partial with different-length content to force a deterministic (mtime,size) delta.
    std::fs::write(
        &partial,
        "@define val():\nV2 updated\n@end\n\n@export val\n",
    )
    .unwrap();

    // All three importers must update.
    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "V2 updated from A", TIMEOUT),
        "a.md must update after partial edit"
    );
    assert!(
        wait_for_file_contains(&out_dir.join("b.md"), "V2 updated from B", TIMEOUT),
        "b.md must update after partial edit"
    );
    assert!(
        wait_for_file_contains(&out_dir.join("c.md"), "V2 updated from C", TIMEOUT),
        "c.md must update after partial edit"
    );

    // Independent file must be untouched.
    let independent_after = std::fs::read_to_string(out_dir.join("independent.md")).unwrap();
    assert_eq!(
        independent_before, independent_after,
        "independent.md must not be modified when an unrelated partial is edited"
    );

    // Tear down before checking.
    let _ = child.0.kill();
    let _ = child.0.wait();
}

// ── AC-P4: Bounded soak — 50 sequential edits ────────────────────────────────

/// 50 sequential edits to a partial; assert each round rebuilds importers, the
/// process stays responsive, and it exits cleanly.
#[test]
fn watch_dir_mode_soak_50_edits_bounded_and_clean_exit() {
    let dir = tempfile::tempdir().unwrap();

    let partial = dir.path().join("_soak.mds");
    std::fs::write(&partial, "@define val():\nSoak V0\n@end\n\n@export val\n").unwrap();

    let importer = dir.path().join("consumer.mds");
    std::fs::write(&importer, "@import \"./_soak.mds\" as s\n{{s.val()}}\n").unwrap();

    let out_dir = dir.path().join("out");
    let (mut child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "10", // Small but non-zero: coalesces rapid-fire writes
                "--poll-interval",
                "50",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile.
    assert!(
        wait_for_file_contains(&out_dir.join("consumer.md"), "Soak V0", TIMEOUT),
        "initial compile should produce 'Soak V0'"
    );

    // 50 sequential edits. Each edit uses a different content length to force
    // deterministic (mtime,size) deltas even on coarse-granularity filesystems.
    for i in 1_u32..=50 {
        // Pad with spaces to ensure each round has a unique byte count.
        let padding = " ".repeat(i as usize);
        std::fs::write(
            &partial,
            format!("@define val():\nSoak V{i}{padding}\n@end\n\n@export val\n"),
        )
        .unwrap();

        // Wait for this round's rebuild to propagate.
        let expected = format!("Soak V{i}");
        assert!(
            wait_for_file_contains(&out_dir.join("consumer.md"), &expected, TIMEOUT),
            "round {i}: consumer.md must contain '{expected}'"
        );
    }

    // Process must still be alive and responsive.
    let still_running = child.0.try_wait().unwrap().is_none();
    assert!(still_running, "watcher must remain alive after 50 edits");

    // Drop (kills the child process) — process stays responsive across 50 edits; teardown via kill.
    drop(child);
}

// ── QA Fix: File-mode parent dir deleted — bounded errors then recovers ───────

/// Regression test for the edge-triggered recovery fix (ADR-021).
///
/// When the watched entry's PARENT DIRECTORY is deleted entirely, the per-tick
/// `watcher.watch()` re-arm fails every idle tick (the parent is missing).  Before the
/// fix this forced `recovery = true` every tick → one compile attempt → one "file not
/// found" error PER TICK, violating the design's error-settle intent (DD1: "print at
/// most once per real attempt, not per tick").
///
/// After the fix the recovery logic is edge-triggered (uses
/// `external_recovery_decision` / `FileWatchState.missing_watched_dirs`):
/// - While the parent stays deleted, the watcher is quiet (no per-tick error).
/// - The moment the parent reappears (vanish→reappear edge), recovery fires and
///   recompiles (AC-W1 preserved).
///
/// At 150ms poll-interval over ≥6 ticks (~900ms idle with missing dir) the
/// not-found error must appear ≤ 3 times (proving "not once-per-tick") — a
/// per-tick implementation would produce ≥ 6 errors in that window.
#[test]
fn watch_file_mode_parent_dir_deleted_bounded_errors_then_recovers() {
    // Place the source in a sub-directory so we can delete the parent without
    // touching the tempdir root (which would delete the child process's cwd too).
    let base = tempfile::tempdir().unwrap();
    let src_dir = base.path().join("src");
    std::fs::create_dir(&src_dir).unwrap();
    let src = src_dir.join("tpl.mds");
    // Force deterministic content so the recovery write is unambiguously detectable.
    std::fs::write(&src, "V1-before\n").unwrap();
    let out = src_dir.join("tpl.md");

    let (mut child, stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "150",
                // No -q: we need to observe stderr errors.
            ])
            .stdout(Stdio::null()),
    );

    // Wait for initial compile.
    assert!(
        wait_for_file_contains(&out, "V1-before", TIMEOUT),
        "initial compile should produce V1-before"
    );

    // Delete the ENTIRE parent directory (not just the file — this is the bug scenario).
    std::fs::remove_dir_all(&src_dir).unwrap();

    // Scale-invariant error bound (guards PF-006, applies ADR-021): run two equal idle
    // windows and assert the error count does NOT grow in the second window.  A per-tick
    // implementation would produce ≥1 error per tick continuously; the fix settles after
    // the initial native-event error(s) and then goes silent.
    //
    // Window 1 — ≥6 ticks at 150ms (~900ms): native-event errors may appear here.
    std::thread::sleep(Duration::from_millis(900));
    let count_w1 = {
        let bytes = stderr_tap.bytes();
        let s = String::from_utf8_lossy(&bytes);
        s.matches("file not found").count() + s.matches("No such file").count()
    };

    // Window 2 — another ≥6 ticks: nothing changed, error-settle must keep count frozen.
    // Any increase here proves the watcher is still firing per-tick (the bug).
    std::thread::sleep(Duration::from_millis(900));
    let count_w2 = {
        let bytes = stderr_tap.bytes();
        let s = String::from_utf8_lossy(&bytes);
        s.matches("file not found").count() + s.matches("No such file").count()
    };

    assert_eq!(
        count_w1, count_w2,
        "error count must not grow in a second idle window (not once-per-tick); \
         w1={count_w1}, w2={count_w2} — the fix must settle after initial native-event errors \
         (applies ADR-021, guards PF-006)"
    );

    // Recreate the parent directory and write the file with new content.
    std::fs::create_dir(&src_dir).unwrap();
    std::fs::write(&src, "V2-recovered\n").unwrap();

    // TICK-DEPENDENT: same as AC-W1 — the parent dir was removed, so the watch on it is
    // gone and the recreated dir is unwatched. Recovery is the vanish→reappear edge in
    // `liveness_probe_file`, one tick at a time.
    assert!(
        wait_for_file_contains(&out, "V2-recovered", TICK_TIMEOUT),
        "watcher must self-heal after parent dir delete+recreate and recompile with V2 content"
    );

    // Watcher must still be alive after recovery.
    let still_alive = child.0.try_wait().unwrap().is_none();

    let _ = child.0.kill();
    let _ = child.0.wait();
    std::thread::sleep(Duration::from_millis(100));

    let stderr_bytes = stderr_tap.bytes();
    let stderr_str = String::from_utf8_lossy(&stderr_bytes);

    assert!(
        still_alive,
        "watcher must remain alive while parent dir is absent; stderr:\n{stderr_str}"
    );

    // Sanity: total error count must remain small — rules out a burst in window 1.
    let error_count =
        stderr_str.matches("file not found").count() + stderr_str.matches("No such file").count();
    assert!(
        error_count <= 8,
        "total error count across both idle windows must be small (not a per-tick flood); \
         got {error_count} occurrences; stderr:\n{stderr_str}"
    );
}

// ── AC-P5: 500-file idle — O(1) liveness probe at scale ──────────────────────

/// AC-P5: Start `mds watch <dir>` over 500 `.mds` files, wait for all initial
/// compiles to complete, then idle for ≥10 poll-interval ticks and assert ZERO
/// "Recompiled" lines in the idle window.
///
/// This is the regression guard for the ADR-021 invariant: "idle cost stays O(1)
/// regardless of tree size."  A per-tick full-tree walk (the anti-pattern) would
/// manifest as spurious "Recompiled" events under CI load; the edge-triggered
/// liveness probe (ADR-021) must emit none.
///
/// An additional positive observable — the sentinel output file's mtime must not
/// advance during the idle window — makes the failure mode deterministic rather
/// than relying on timing luck alone.
///
/// applies ADR-021
#[test]
fn watch_dir_mode_idle_500_files_no_recompile() {
    const FILE_COUNT: usize = 500;
    let dir = tempfile::tempdir().unwrap();
    let out_dir = dir.path().join("out");
    std::fs::create_dir(&out_dir).unwrap();

    // Create FILE_COUNT trivially-simple .mds files.  Plain text (no frontmatter)
    // is valid MDS; keeps per-file compile time minimal.
    // Files are named file_0001.mds … file_0500.mds so the last one is lexicographically
    // predictable as the sentinel for "startup compilation done".
    for i in 1..=FILE_COUNT {
        std::fs::write(
            dir.path().join(format!("file_{i:04}.mds")),
            format!("scale-idle-{i}\n"),
        )
        .unwrap();
    }
    let sentinel_out = out_dir.join(format!("file_{FILE_COUNT:04}.md"));

    // Use --poll-interval 50 (the minimum floor) to keep the test fast while still
    // giving the liveness probe several real ticks during the idle window.
    // --debounce 0: immediate event processing, no coalesce delay.
    // No -q: we need to observe "Recompiled" in stderr.
    let (mut child, stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "50",
            ])
            .stdout(Stdio::null()),
    );

    // Assert the sentinel output exists — dir-mode compiles all files in a single
    // startup batch before entering the event loop, and the readiness handshake only
    // fires after that batch, so all 500 initial compiles are already done here. This
    // is a content assertion now, not a wait.
    assert!(
        wait_for_file_contains(&sentinel_out, &format!("scale-idle-{FILE_COUNT}"), TIMEOUT,),
        "AC-P5: sentinel file_{FILE_COUNT:04}.md must be written during startup compile \
         (all {FILE_COUNT} files compiled before idle window)"
    );

    // Record positive observable: sentinel mtime before the idle window.
    let mtime_before = std::fs::metadata(&sentinel_out)
        .and_then(|m| m.modified())
        .expect("sentinel output must exist after startup");

    // Idle for ≥10 ticks at 50ms poll-interval (500ms total, bounded).  A per-tick
    // full-tree walk would trigger O(FILE_COUNT) work per tick; edge-triggered probes
    // (ADR-021) must emit zero "Recompiled" lines during this window.
    std::thread::sleep(Duration::from_millis(600));

    let _ = child.0.kill();
    let _ = child.0.wait();
    std::thread::sleep(Duration::from_millis(100));

    let stderr_bytes = stderr_tap.bytes();
    let stderr_str = String::from_utf8_lossy(&stderr_bytes);

    let recompiled_count = stderr_str.matches("Recompiled").count();
    assert_eq!(
        recompiled_count, 0,
        "AC-P5: idle dir-mode watcher over {FILE_COUNT} files must emit 0 Recompiled \
         across ≥10 ticks (ADR-021: idle cost is O(1) regardless of tree size); \
         got {recompiled_count}; stderr:\n{stderr_str}"
    );

    // Deterministic positive observable: sentinel output mtime must be unchanged
    // (no spurious recompile touched it during the idle window).
    let mtime_after = std::fs::metadata(&sentinel_out)
        .and_then(|m| m.modified())
        .expect("sentinel output must still exist after idle");
    assert_eq!(
        mtime_before, mtime_after,
        "AC-P5: sentinel output mtime must not advance during idle window \
         (a spurious recompile would update it)"
    );
}

// ── AC-1/2/3/4: Symlink rejection at startup (parity with mds build) ─────────
//
// PF-004: an alternate code path (watch's up-front canonicalize) was silently
// bypassing the symlink guard enforced by NativeFs in mds build. These tests
// lock in the fix: mds watch now rejects symlinked entry / dir target / --vars
// at startup, matching mds build behavior.

/// AC-1: `mds watch <symlinked-file>` must reject at startup (non-zero exit;
/// stderr names the symlink restriction).  Mirrors
/// `symlinked_entry_exits_nonzero` in intrinsic_output.rs.
#[test]
#[cfg(unix)]
fn watch_rejects_symlinked_entry() {
    let dir = tempfile::tempdir().unwrap();

    // Real file with valid content.
    let real_file = dir.path().join("real.mds");
    std::fs::write(&real_file, "@message system:\nYou are helpful.\n@end\n").unwrap();

    // Symlink → real file.
    let link_file = dir.path().join("link.mds");
    std::os::unix::fs::symlink(&real_file, &link_file).unwrap();

    let out = dir.path().join("out.md");

    let output = mds_bin()
        .args([
            "watch",
            link_file.to_str().unwrap(),
            "-o",
            out.to_str().unwrap(),
        ])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "watch with a symlinked entry must fail at startup; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.contains("symlink") || stderr.contains("not allowed"),
        "error must mention symlink restriction; got: {stderr}"
    );
    assert!(
        !out.exists(),
        "output file must not be created when entry is rejected at startup"
    );
}

/// AC-2 (file mode): `mds watch <entry> --vars <symlinked-vars>` must reject at
/// startup (non-zero; stderr mentions symlink).  Mirrors
/// `symlinked_vars_file_exits_nonzero` in intrinsic_output.rs.
#[test]
#[cfg(unix)]
fn watch_rejects_symlinked_vars_file() {
    let dir = tempfile::tempdir().unwrap();

    // Real entry and vars files.
    let entry = dir.path().join("entry.mds");
    std::fs::write(&entry, "---\nname: World\n---\nHello {{name}}!\n").unwrap();

    let real_vars = dir.path().join("real_vars.json");
    std::fs::write(&real_vars, r#"{"name": "World"}"#).unwrap();

    // Symlink → real vars.
    let link_vars = dir.path().join("link_vars.json");
    std::os::unix::fs::symlink(&real_vars, &link_vars).unwrap();

    let out = dir.path().join("out.md");

    let output = mds_bin()
        .args([
            "watch",
            entry.to_str().unwrap(),
            "--vars",
            link_vars.to_str().unwrap(),
            "-o",
            out.to_str().unwrap(),
        ])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "watch with a symlinked --vars must fail at startup; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.contains("symlink") || stderr.contains("not allowed"),
        "error must mention symlink restriction for vars; got: {stderr}"
    );
}

/// AC-3: `mds watch <symlinked-dir>` must reject at startup (non-zero; stderr names
/// the symlink restriction; the symlinked dir is never traversed).
#[test]
#[cfg(unix)]
fn watch_rejects_symlinked_dir_target() {
    let dir = tempfile::tempdir().unwrap();

    // Real source directory with a valid .mds file.
    let real_src = dir.path().join("real_src");
    std::fs::create_dir(&real_src).unwrap();
    std::fs::write(
        real_src.join("a.mds"),
        "---\nname: A\n---\nFile A: {{name}}\n",
    )
    .unwrap();

    // Symlink → the real source directory.
    let link_dir = dir.path().join("link_src");
    std::os::unix::fs::symlink(&real_src, &link_dir).unwrap();

    let out_dir = dir.path().join("out");
    std::fs::create_dir(&out_dir).unwrap();

    let output = mds_bin()
        .args([
            "watch",
            link_dir.to_str().unwrap(),
            "--out-dir",
            out_dir.to_str().unwrap(),
        ])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "watch with a symlinked dir target must fail at startup; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.contains("symlink") || stderr.contains("not allowed"),
        "error must mention symlink restriction; got: {stderr}"
    );
    assert!(
        !out_dir.join("a.md").exists(),
        "symlinked dir must never be traversed; a.md must not be created"
    );
}

/// AC-4: A symlinked `.mds` source file inside a watched real directory is NOT
/// compiled, while a real sibling compiles normally.  This locks in the existing
/// discovery-skip behavior in `collect_mds_files` (dir entries that are symlinks
/// are already excluded by the follow-symlinks=false DirEntry filter).
#[test]
#[cfg(unix)]
fn watch_dir_skips_symlinked_source_file() {
    let dir = tempfile::tempdir().unwrap();

    // Real source directory — the one we watch.
    let src = dir.path().join("src");
    std::fs::create_dir(&src).unwrap();

    // A real .mds file inside the watched dir — SHOULD compile.
    std::fs::write(src.join("a.mds"), "---\nname: A\n---\nFile A: {{name}}\n").unwrap();

    // An external .mds file to be pointed at by the symlink.
    let external_dir = dir.path().join("external");
    std::fs::create_dir(&external_dir).unwrap();
    std::fs::write(
        external_dir.join("external.mds"),
        "---\nname: Ext\n---\nExternal: {{name}}\n",
    )
    .unwrap();

    // A symlinked .mds file inside the watched dir — must NOT compile.
    let link_mds = src.join("link.mds");
    std::os::unix::fs::symlink(external_dir.join("external.mds"), &link_mds).unwrap();

    let out_dir = dir.path().join("out");
    std::fs::create_dir(&out_dir).unwrap();

    let (child, _stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // Wait for the real file to compile.
    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "File A: A", TIMEOUT),
        "a.md (real sibling) should be compiled"
    );

    // The symlinked source must never appear in the output.
    // Poll briefly — if the watcher were to incorrectly process it, it would appear.
    let deadline = std::time::Instant::now() + std::time::Duration::from_millis(500);
    while std::time::Instant::now() < deadline {
        assert!(
            !out_dir.join("link.md").exists(),
            "link.md must not be created — symlinked source files must be skipped"
        );
        std::thread::sleep(std::time::Duration::from_millis(50));
    }

    drop(child);
}

// ── ESC-injection: watch initial-compile-error stderr sanitization ────────────

/// T-Watch-ESC [AC-F-W1]: the `eprint_error` call at the non-loop
/// initial-compile-error path in `run_watch_file` (watch.rs line ~937) must
/// sanitize any raw control bytes before writing to stderr.
///
/// Vector: a `.mds` file containing a raw ESC byte (U+001B) in an unclosed
/// `@define` — guaranteed syntax error — so the initial compile fails and
/// `eprint_error` is called before the watch loop begins.
///
/// Determinism: the initial compile is a synchronous call that completes before
/// the watch loop starts.  We wait a fixed bounded interval (500 ms, >> any
/// realistic compile time) then kill the process.  No file-system events are
/// polled, so this test is immune to FSEvents/inotify timing flakiness.
///
/// Assertions:
///   1. stderr carries the initial-compile error for THIS file (non-vacuous).
///   2. No raw ESC byte (0x1B) appears anywhere in stderr.
///
/// Assertion 1 exists solely to keep assertion 2 honest: "no ESC byte in stderr" is
/// trivially true of an empty stream, so a change that stopped the error being printed
/// at all would leave assertion 2 passing while testing nothing. It therefore has to
/// name something ONLY the rendered diagnostic produces. Note that the file's own stem
/// does not qualify: this watcher runs non-quiet, so `Watching /…/esc_watch.mds` is on
/// stderr whether or not the error was ever printed.
#[test]
fn watch_esc_in_initial_compile_error_is_sanitized() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("esc_watch.mds");
    // Unclosed @define with a raw ESC byte (0x1B) on the directive line so that
    // miette renders it inside the source context frame.
    std::fs::write(&src, b"@define \x1bfoo:\nhello\n").unwrap();

    // The readiness handshake already implies the initial compile ran to completion:
    // the error is printed on the startup path, and the marker is only emitted after
    // it. No sleep needed to "give it time".
    let (child, stderr_tap) = spawn_ready(
        mds_bin()
            .args(["watch", src.to_str().unwrap(), "--debounce", "0"])
            .stdout(Stdio::null()),
    );

    // Kill the watch process (ChildGuard.drop → kill + wait) to close the pipe.
    drop(child);

    let stderr_bytes = stderr_tap.bytes();
    let stderr_str = String::from_utf8_lossy(&stderr_bytes);

    // Assertion 1: the initial-compile error was rendered (non-vacuous guard for
    // assertion 2). `syntax error` comes from the diagnostic and from nothing else the
    // watcher writes — unlike the file stem, which the `Watching …` line also carries.
    assert!(
        stderr_str.contains("syntax error"),
        "watch initial-compile-error must render its diagnostic to stderr, otherwise \
         the ESC assertion below is vacuous; got:\n{stderr_str}"
    );

    // Assertion 2: no raw ESC byte (0x1B) anywhere in stderr.
    // eprint_error sanitizes via render_error_sanitized before writing;
    // if sanitization is removed the raw 0x1B byte leaks here.
    assert!(
        !stderr_bytes.contains(&0x1Bu8),
        "raw ESC byte (0x1B) must be sanitized in watch initial-compile-error stderr; \
         got (hex first 512): {:02x?}",
        &stderr_bytes[..stderr_bytes.len().min(512)]
    );
}

// ── #317 regression: an edit inside the startup window must not be lost ───────
//
// These are the only tests in this file that deliberately do NOT go through
// `spawn_ready`, and that is the entire point of them.
//
// `MDS_TEST_READY` signals "every watch armed and every baseline captured". It is
// emitted at the end of whatever startup ordering the code happens to have, so it is
// true by construction in both the fixed and the defective ordering — it just fires at
// a different wall-clock instant in each. A test that waits for it therefore cannot
// place an edit inside the window the ordering opens: by the time it is allowed to act,
// the window is closed by definition. Every handshake-gated test in this file passes
// against the pre-fix ordering, which is why the arm-before-publish fix shipped with no
// test that could detect its regression.
//
// These two synchronise on the *opening* of the window instead — the moment the startup
// output is published, which is where the defective ordering armed nothing — and then
// edit immediately. `--poll-interval 0` disables the self-heal probe so that inotify is
// the sole detector: with the probe enabled, `liveness_probe_file` rebuilds
// unconditionally on its first tick regardless of any baseline, which would recover the
// lost edit and mask the defect (see #319 for why that recovery is itself unreliable).
//
// Sensitivity comes from the `startup-race-probe` Cargo feature, which widens the
// publish→arm window to 200ms. Measured against the pre-fix arming order on Linux:
//
//   with the probe        file mode 6/6 red, dir mode 6/6 red
//   without the probe     file mode 3/3 red, dir mode 1/3 red
//
// So the default `cargo test` run detects the file-mode regression but is a coin flip
// on the dir-mode one, because there the unwidened window is only the few microseconds
// between the last output write and the `watcher.watch()` syscall. That is why CI runs
// this file a second time with the feature on. Feature and tests are one mechanism;
// neither half is a gate on its own.

/// File mode: an edit landing immediately after the first output is published must
/// still reach the output, with the self-heal probe disabled.
#[test]
fn watch_file_mode_edit_during_startup_window_is_not_lost() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("entry.mds");
    std::fs::write(&src, "---\nname: Before\n---\nEntry {{name}}\n").unwrap();
    let out = dir.path().join("entry.md");

    let (child, _tap) = spawn_unsynchronized(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "--debounce",
                "0",
                // Self-heal probe OFF: inotify must carry this on its own.
                "--poll-interval",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // The published startup output IS the start of the window.
    assert!(
        wait_for_file_contains_tight(&out, "Entry Before", STARTUP_WINDOW_TIMEOUT),
        "startup compile should publish 'Entry Before'"
    );

    // Edit now — inside the window under the defective ordering.
    std::fs::write(&src, "---\nname: After\n---\nEntry {{name}}\n").unwrap();

    assert!(
        wait_for_file_contains(&out, "Entry After", STARTUP_WINDOW_TIMEOUT),
        "an edit made immediately after the startup output was published must not be \
         lost: with --poll-interval 0 the OS watch is the only detector, so this fails \
         if the watch is armed after the output is written (#317)"
    );

    drop(child);
}

/// Directory mode: same property for the recursive root watch.
#[test]
fn watch_dir_mode_edit_during_startup_window_is_not_lost() {
    let base = tempfile::tempdir().unwrap();
    let root = base.path().join("root");
    let out_dir = base.path().join("out");
    std::fs::create_dir(&root).unwrap();
    let src = root.join("a.mds");
    std::fs::write(&src, "---\nname: Before\n---\nDir {{name}}\n").unwrap();
    let out = out_dir.join("a.md");

    let (child, _tap) = spawn_unsynchronized(
        mds_bin()
            .args([
                "watch",
                root.to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains_tight(&out, "Dir Before", STARTUP_WINDOW_TIMEOUT),
        "startup compile should publish 'Dir Before'"
    );

    std::fs::write(&src, "---\nname: After\n---\nDir {{name}}\n").unwrap();

    assert!(
        wait_for_file_contains(&out, "Dir After", STARTUP_WINDOW_TIMEOUT),
        "an edit made immediately after the startup output was published must not be \
         lost in dir mode: the recursive root watch must be armed before the tree walk, \
         not after the outputs are written (#317)"
    );

    drop(child);
}

/// Directory mode: an edit to a **cross-root dependency**, made in the window before
/// that dependency's directory can be armed, must still reach the output (#321).
///
/// This is the one window arming order cannot close, and it is not an artefact of the
/// test harness: a cross-root dependency's directory is discovered by the compile that
/// reads it, so there is no earlier instant at which to arm it. Whatever the ordering,
/// some interval exists in which an edit to such a file produces no event for anyone.
///
/// So this test deliberately does the opposite of the two #317 tests above. They run
/// with `--poll-interval 0` to prove inotify carries the edit alone; this one leaves
/// the probe enabled, because here the idle-tick content backstop is the *only*
/// mechanism that can carry it. Before the backstop existed, directory mode diffed only
/// `collect_mds_files(root)` — which never contains a cross-root dependency — so the
/// edit was not late, it was gone.
///
/// Sensitivity, like the #317 tests, comes from the `startup-race-probe` feature: it
/// widens the publish→arm window to 200ms, which is what makes the edit land inside it
/// reliably rather than by luck. See the block comment above.
#[test]
fn watch_dir_mode_cross_root_edit_during_startup_window_is_not_lost() {
    let base = tempfile::tempdir().unwrap();
    let root = base.path().join("root");
    let shared = base.path().join("shared");
    let out_dir = base.path().join("out");
    std::fs::create_dir(&root).unwrap();
    std::fs::create_dir(&shared).unwrap();
    // .git marker so the compiler's project root is `base`, permitting `../shared`.
    std::fs::write(base.path().join(".git"), "").unwrap();

    let partial = shared.join("_x.mds");
    std::fs::write(
        &partial,
        "@define greet():\nWindow V1\n@end\n\n@export greet\n",
    )
    .unwrap();
    let importer = root.join("importer.mds");
    std::fs::write(
        &importer,
        "@import \"../shared/_x.mds\" as x\n{{x.greet()}}\n",
    )
    .unwrap();
    let out = out_dir.join("importer.md");

    let (child, _tap) = spawn_unsynchronized(
        mds_bin()
            .args([
                "watch",
                root.to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                // Probe ON: the content backstop is the mechanism under test.
                "--poll-interval",
                "100",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    // The published startup output IS the start of the window: the external dep dir is
    // armed only after every source has been compiled and written.
    assert!(
        wait_for_file_contains_tight(&out, "Window V1", STARTUP_WINDOW_TIMEOUT),
        "startup compile should publish 'Window V1'"
    );

    // Edit the cross-root partial now — inside the window where nothing is watching it.
    std::fs::write(
        &partial,
        "@define greet():\nWindow V2\n@end\n\n@export greet\n",
    )
    .unwrap();

    // TICK-DEPENDENT: no filesystem event announces this edit, so recovery is the idle
    // tick's `(mtime, size)` diff against the baseline captured before the first read.
    assert!(
        wait_for_file_contains(&out, "Window V2", TICK_TIMEOUT),
        "an edit to a cross-root dependency during the startup window must be recovered \
         by the idle-tick content backstop: its directory cannot be armed before the \
         compile discovers it, so no event exists to deliver, and diffing only the \
         in-root file list can never see the change (#321)"
    );

    drop(child);
}

/// Single-file mode: the same end-to-end property for a dependency outside the entry's
/// directory — an edit in the startup window must still reach the output.
///
/// **Measured limitation, stated so it cannot be misread as a guard it is not.** This
/// test does not discriminate *which* mechanism delivers the result, because single-file
/// mode has two that each suffice alone, and one of them is unconditional:
/// `liveness_probe_file` returns `recovery || changed` with `recovery` including
/// `first_tick`, so its first tick rebuilds whatever the baseline says. Measured against
/// an arm with the dependency baseline moved back to the post-compile snapshot, this test
/// still passed 10/10 — the first-tick rebuild covered it. It therefore guards the
/// disjunction "first-tick rebuild *or* a baseline older than the read", not either term.
///
/// It is kept because that disjunction is the property a user depends on, and because
/// removing the unconditional first-tick rebuild — an obvious way to save a redundant
/// startup compile — would leave the baseline as the only remaining satisfier. It is
/// **not** evidence that the baseline capture point is correct; nothing here is.
/// The directory-mode counterpart above *is* discriminating (measured 10/10 RED against
/// the arm without the content backstop), because directory mode has no unconditional
/// first-tick rebuild.
#[test]
fn watch_file_mode_dep_edit_during_startup_window_is_not_lost() {
    let base = tempfile::tempdir().unwrap();
    let entry_dir = base.path().join("tpl");
    let shared = base.path().join("shared");
    std::fs::create_dir(&entry_dir).unwrap();
    std::fs::create_dir(&shared).unwrap();
    std::fs::write(base.path().join(".git"), "").unwrap();

    let partial = shared.join("_x.mds");
    std::fs::write(
        &partial,
        "@define greet():\nDep V1\n@end\n\n@export greet\n",
    )
    .unwrap();
    let entry = entry_dir.join("entry.mds");
    std::fs::write(&entry, "@import \"../shared/_x.mds\" as x\n{{x.greet()}}\n").unwrap();
    let out = entry_dir.join("entry.md");

    let (child, _tap) = spawn_unsynchronized(
        mds_bin()
            .args([
                "watch",
                entry.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "100",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains_tight(&out, "Dep V1", STARTUP_WINDOW_TIMEOUT),
        "startup compile should publish 'Dep V1'"
    );

    std::fs::write(
        &partial,
        "@define greet():\nDep V2\n@end\n\n@export greet\n",
    )
    .unwrap();

    assert!(
        wait_for_file_contains(&out, "Dep V2", TICK_TIMEOUT),
        "an edit to a dependency outside the entry's directory during the startup \
         window must be recovered by the idle tick: the dependency's baseline has to \
         predate the edit, which it only does if it is captured when the compile \
         reports the dep rather than at the end of startup (#321)"
    );

    drop(child);
}

// ── #319: the idle tick must not be starvable ────────────────────────────────
//
// The backstop above is only worth as much as the tick that runs it. Handing
// `recv_timeout` a fresh `--poll-interval` budget per message made the tick starvable
// by any event stream faster than the interval — and the watcher's own compiles, an
// editor's scratch writes, a dev server, or a sync client all qualify. A starved tick
// does not delay recovery; it removes it.

/// The idle tick must still fire while filesystem events arrive faster than the
/// `--poll-interval` (#319).
///
/// The change under test is one no event can announce: `remove_dir_all` destroys the
/// recursive watch descriptor, and the directory recreated in its place is a different
/// inode that nothing is watching. Only the probe's re-arm and reconcile can recover
/// it. Meanwhile a reader polls the cross-root dependency 30× faster than the poll
/// interval, so every one of those reads is an `Access` event on a watch that is still
/// live — the watcher drops each as irrelevant, which is exactly why a message-driven
/// countdown never reached zero.
///
/// The reader is deliberately outside the deleted root: a flood that stops when the
/// root does would prove nothing about starvation.
#[test]
fn watch_dir_mode_idle_tick_fires_under_event_flood() {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;

    let base = tempfile::tempdir().unwrap();
    let root = base.path().join("root");
    let shared = base.path().join("shared");
    let out_dir = base.path().join("out");
    std::fs::create_dir(&root).unwrap();
    std::fs::create_dir(&shared).unwrap();
    std::fs::create_dir(&out_dir).unwrap();
    std::fs::write(base.path().join(".git"), "").unwrap();

    // A cross-root dependency: its directory is armed, so reads of it are delivered as
    // events for the lifetime of the watcher, independent of the root.
    let partial = shared.join("_p.mds");
    std::fs::write(&partial, "@define hi():\nP\n@end\n\n@export hi\n").unwrap();
    std::fs::write(
        root.join("a.mds"),
        "@import \"../shared/_p.mds\" as p\n{{p.hi()}}\n",
    )
    .unwrap();

    let (child, _tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                root.to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "--poll-interval",
                "150",
                "-q",
            ])
            .stdout(Stdio::null()),
    );

    assert!(
        wait_for_file_contains(&out_dir.join("a.md"), "P", TIMEOUT),
        "initial compile should produce 'P'"
    );

    // Flood: read the armed cross-root dependency every 5ms — 30 events per tick.
    let stop = Arc::new(AtomicBool::new(false));
    let flood = {
        let stop = Arc::clone(&stop);
        let partial = partial.clone();
        std::thread::spawn(move || {
            // Bounded by the stop flag, which the test always sets before joining.
            while !stop.load(Ordering::Relaxed) {
                let _ = std::fs::read(&partial);
                std::thread::sleep(Duration::from_millis(5));
            }
        })
    };

    // Destroy the root's watch descriptor, then recreate the directory with new content.
    std::fs::remove_dir_all(&root).unwrap();
    std::thread::sleep(Duration::from_millis(200));
    std::fs::create_dir(&root).unwrap();
    std::fs::write(root.join("new.mds"), "---\nname: N\n---\nFlood {{name}}\n").unwrap();

    let recovered = wait_for_file_contains(&out_dir.join("new.md"), "Flood N", TICK_TIMEOUT);

    stop.store(true, Ordering::Relaxed);
    flood.join().expect("flood thread panicked");

    assert!(
        recovered,
        "the idle tick must fire while events arrive 30x faster than --poll-interval: \
         nothing but the probe's re-arm can observe a root recreated as a new inode, so \
         a tick whose deadline restarts on every message loses this change permanently \
         rather than late (#319)"
    );

    drop(child);
}

// ── Ctrl+C during the startup compile ────────────────────────────────────────
//
// `watch_ctrl_c_exits_cleanly` and `watch_ctrl_c_prints_stopped_watching` both signal
// only after `spawn_ready` returns, so they cover Ctrl+C during the *event loop* and
// say nothing about Ctrl+C during startup. Those are different code paths with
// different handlers in force, and only the second one scales with the size of the
// user's tree.
//
// Installing `ctrlc::set_handler` converts SIGINT from "terminate" into "enqueue
// `Msg::Interrupt`", and that message is read only by the event loop. Install it above
// the startup compile and Ctrl+C is inert for the compile's whole duration: the tool
// keeps writing outputs, ignores every further press, and finally exits 0. The
// user-visible defect is that Ctrl+C does nothing and the tool writes files the user
// was trying to stop it writing.

/// Directory mode: SIGINT delivered while the startup compile is still running must
/// terminate the process, not be queued until the compile finishes.
#[test]
#[cfg(unix)]
fn watch_dir_mode_ctrl_c_during_startup_compile_terminates() {
    use std::os::unix::process::ExitStatusExt;

    // Large enough that the compile is still far from finished when the first outputs
    // appear, small enough to stay a fast test. Dir-mode startup makes two full passes
    // over this set, so the window is roughly twice what the first pass suggests.
    const SOURCES: usize = 1200;
    /// Number of published outputs that proves the startup compile is under way.
    /// Deliberately tiny relative to SOURCES so the signal lands with the overwhelming
    /// majority of the work still ahead.
    const OBSERVE_AT: usize = 10;

    let base = tempfile::tempdir().unwrap();
    let root = base.path().join("root");
    let out_dir = base.path().join("out");
    std::fs::create_dir(&root).unwrap();
    for i in 0..SOURCES {
        std::fs::write(
            root.join(format!("s{i:04}.mds")),
            "---\nname: S\n---\nSource {{name}}\n",
        )
        .unwrap();
    }

    let count_outputs = |dir: &Path| -> usize {
        std::fs::read_dir(dir)
            .map(|rd| rd.filter_map(|e| e.ok()).count())
            .unwrap_or(0)
    };

    let (mut guard, _tap) = spawn_unsynchronized(
        mds_bin()
            .args([
                "watch",
                root.to_str().unwrap(),
                "--out-dir",
                out_dir.to_str().unwrap(),
                "--debounce",
                "0",
                "-q",
            ])
            .stdout(Stdio::null()),
    );
    let pid = guard.id();

    // Gate on the artifact rather than on a guessed sleep: wait until the startup
    // compile has demonstrably begun (some outputs) and demonstrably not finished
    // (nowhere near all of them).
    let deadline = Instant::now() + Duration::from_secs(30);
    let mut observed = 0usize;
    while Instant::now() < deadline {
        observed = count_outputs(&out_dir);
        if observed >= OBSERVE_AT {
            break;
        }
        std::thread::sleep(Duration::from_millis(1));
    }
    assert!(
        (OBSERVE_AT..SOURCES / 2).contains(&observed),
        "test precondition: SIGINT must be sent while the startup compile is in \
         flight; saw {observed} of {SOURCES} outputs (want {OBSERVE_AT}..{})",
        SOURCES / 2
    );

    unsafe {
        libc::kill(pid as libc::pid_t, libc::SIGINT);
    }

    let signalled_at = Instant::now();
    let deadline = Instant::now() + Duration::from_secs(20);
    let mut exited = false;
    while Instant::now() < deadline {
        if guard.0.try_wait().unwrap().is_some() {
            exited = true;
            break;
        }
        std::thread::sleep(Duration::from_millis(1));
    }
    let elapsed = signalled_at.elapsed();
    let written = count_outputs(&out_dir);
    assert!(
        exited,
        "process must exit after SIGINT during startup compile"
    );

    let status = guard.wait_status();

    // The discriminator. Before the event loop exists there is nothing to service a
    // queued `Msg::Interrupt`, so the correct behaviour is the default disposition:
    // death by SIGINT. A clean `code() == Some(0)` here means a handler was installed
    // above the startup compile, swallowed the signal, and let startup run to
    // completion — the #317 follow-up defect.
    assert_eq!(
        status.signal(),
        Some(libc::SIGINT),
        "SIGINT during the startup compile must terminate the process; instead it \
         exited with {status:?} after {elapsed:?}, having written {written} of \
         {SOURCES} outputs — the signal was swallowed until the event loop started"
    );

    // The user-visible half of the same property, asserted independently of how the
    // process died: it must stop producing output promptly.
    assert!(
        written < SOURCES / 2,
        "after Ctrl+C during startup the watcher must stop writing outputs; it wrote \
         {written} of {SOURCES}"
    );
}

/// File mode: same property. The gate is the `Watching …` line, which `run_watch_file`
/// prints before it creates the watcher and therefore before the startup compile; the
/// entry imports enough partials that the compile is still running when SIGINT lands.
#[test]
#[cfg(unix)]
fn watch_file_mode_ctrl_c_during_startup_compile_terminates() {
    use std::os::unix::process::ExitStatusExt;

    const PARTIALS: usize = 400;

    let dir = tempfile::tempdir().unwrap();
    let mut entry = String::new();
    for i in 0..PARTIALS {
        let name = format!("_p{i:04}");
        std::fs::write(
            dir.path().join(format!("{name}.mds")),
            format!("@define v{i}():\nP{i}\n@end\n\n@export v{i}\n"),
        )
        .unwrap();
        entry.push_str(&format!("@import \"./{name}.mds\" as p{i}\n"));
    }
    entry.push_str("done\n");
    let src = dir.path().join("entry.mds");
    std::fs::write(&src, &entry).unwrap();

    let (mut guard, tap) = spawn_unsynchronized(
        // No -q: the `Watching …` line is the startup gate.
        mds_bin()
            .args(["watch", src.to_str().unwrap(), "--debounce", "0"])
            .stdout(Stdio::null()),
    );
    let pid = guard.id();

    let deadline = Instant::now() + Duration::from_secs(30);
    let mut saw_watching = false;
    while Instant::now() < deadline {
        if tap.text().contains("Watching ") {
            saw_watching = true;
            break;
        }
        std::thread::sleep(Duration::from_millis(1));
    }
    assert!(
        saw_watching,
        "expected the `Watching …` startup line; stderr:\n{}",
        tap.text()
    );
    // `Watching …` is printed before the watcher is even created, so the startup
    // compile of a 400-import entry is still ahead.
    assert!(
        !dir.path().join("entry.md").exists(),
        "test precondition: the startup compile must not have published its output yet"
    );

    unsafe {
        libc::kill(pid as libc::pid_t, libc::SIGINT);
    }

    let deadline = Instant::now() + Duration::from_secs(20);
    let mut exited = false;
    while Instant::now() < deadline {
        if guard.0.try_wait().unwrap().is_some() {
            exited = true;
            break;
        }
        std::thread::sleep(Duration::from_millis(1));
    }
    assert!(
        exited,
        "process must exit after SIGINT during startup compile"
    );

    let status = guard.wait_status();
    assert_eq!(
        status.signal(),
        Some(libc::SIGINT),
        "SIGINT during the startup compile must terminate the process; instead it \
         exited with {status:?} — the signal was swallowed until the event loop started"
    );
}

// ── I8: file-watch mode warns exactly ONCE across two edits (#200) ──────────

/// Count non-overlapping occurrences of `needle` in `haystack`.
fn count_occurrences(haystack: &str, needle: &str) -> usize {
    let mut count = 0;
    let mut start = 0;
    while let Some(pos) = haystack[start..].find(needle) {
        count += 1;
        start += pos + needle.len();
    }
    count
}

/// Pinned --set duplicate-key warning string (issue #200, spec §7.2).
const DUP_SET_WARNING: &str =
    "warning: variable 'x' is set more than once by --set; the last value wins";

/// Wait until the stderr tap contains the given needle, or timeout elapses.
///
/// Polls the shared StderrTap at 20ms intervals; returns the final contents.
fn wait_for_stderr_contains_str(tap: &StderrTap, needle: &str, timeout: Duration) -> String {
    let deadline = Instant::now() + timeout;
    loop {
        let text = tap.text();
        if text.contains(needle) || Instant::now() >= deadline {
            return text;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
}

#[test]
fn i8_file_watch_duplicate_set_warns_exactly_once_across_two_edits() {
    // I8: mds watch (file mode) with --set x=1 --set x=2 must print the
    // duplicate-key warning exactly once — at startup — not on every rebuild.
    //
    // Negative controls (manually verified during development — see commit body):
    //   - Adding emit to watch.rs:935 → count rises to ≥ 3 across two edits.
    //   - Adding emit to watch.rs:1914 → count grows per event batch.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    std::fs::write(&src, "version 1").unwrap();
    let out = dir.path().join("t.md");

    let (child, stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                src.to_str().unwrap(),
                "--debounce",
                "0",
                "--set",
                "x=1",
                "--set",
                "x=2",
            ])
            .stdout(Stdio::null()),
    );

    // Wait for the startup warning to appear.
    let stderr_after_start = wait_for_stderr_contains_str(&stderr_tap, DUP_SET_WARNING, TIMEOUT);
    let count_at_start = count_occurrences(&stderr_after_start, DUP_SET_WARNING);
    assert_eq!(
        count_at_start, 1,
        "I8: expected exactly 1 warning at startup, got {}; stderr:\n{}",
        count_at_start, stderr_after_start
    );

    // Edit 1: trigger a rebuild.
    std::fs::write(&src, "version 2").unwrap();
    assert!(
        wait_for_file_contains(&out, "version 2", TIMEOUT),
        "I8: rebuild after edit 1 must complete"
    );

    // Edit 2: trigger another rebuild.
    std::fs::write(&src, "version 3").unwrap();
    assert!(
        wait_for_file_contains(&out, "version 3", TIMEOUT),
        "I8: rebuild after edit 2 must complete"
    );

    // After two rebuilds, the warning count must still be 1 (negative control:
    // emitting at the rebuild sites would raise it).
    let final_stderr = stderr_tap.text();
    let final_count = count_occurrences(&final_stderr, DUP_SET_WARNING);
    assert_eq!(
        final_count, 1,
        "I8: after two edits the warning must still appear exactly once; \
         got {}; stderr:\n{}",
        final_count, final_stderr
    );

    drop(child);
}

// ── I9: dir-watch mode warns exactly ONCE — guards the :2185 double-print ────

#[test]
fn i9_dir_watch_duplicate_set_warns_exactly_once_at_startup() {
    // I9: mds watch (dir mode) with --set x=1 --set x=2 must print the
    // duplicate-key warning exactly once — at startup — and NOT again on rebuilds.
    //
    // dir_watch_startup calls build_runtime_vars twice (once at :2064 to emit,
    // once at :2185 for the dedup baseline to discard).  This test is the SOLE
    // mechanical guard that:
    //   - the second call at :2185 does NOT also emit (double-print on startup), AND
    //   - rebuild calls at :1914 do NOT emit (per-event growth).
    //
    // Negative controls (manually verified during development — see commit body):
    //   - Adding emit at watch.rs:2185 → count becomes 2 with no edits at all.
    //   - Adding emit at watch.rs:1914 → count grows to ≥ 2 after the rebuild below.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    std::fs::write(&src, "version 1").unwrap();
    let out = dir.path().join("t.md");

    let (child, stderr_tap) = spawn_ready(
        mds_bin()
            .args([
                "watch",
                dir.path().to_str().unwrap(),
                "--debounce",
                "0",
                "--set",
                "x=1",
                "--set",
                "x=2",
            ])
            .stdout(Stdio::null()),
    );

    // Wait for the startup warning.
    let stderr_startup = wait_for_stderr_contains_str(&stderr_tap, DUP_SET_WARNING, TIMEOUT);
    let count_at_startup = count_occurrences(&stderr_startup, DUP_SET_WARNING);
    assert_eq!(
        count_at_startup, 1,
        "I9: dir-watch startup must emit the warning exactly once (guards :2185); \
         got {}; stderr:\n{}",
        count_at_startup, stderr_startup
    );

    // Trigger a rebuild to exercise the :1914 path (handle_dir_event).
    std::fs::write(&src, "version 2").unwrap();
    assert!(
        wait_for_file_contains(&out, "version 2", TIMEOUT),
        "I9: rebuild after edit must complete"
    );

    // After the rebuild, the count must still be 1 (guards :1914 per-event growth).
    let stderr_after_edit = stderr_tap.text();
    let count_after_edit = count_occurrences(&stderr_after_edit, DUP_SET_WARNING);
    assert_eq!(
        count_after_edit, 1,
        "I9: after one rebuild, warning must still appear exactly once (guards :1914); \
         got {}; stderr:\n{}",
        count_after_edit, stderr_after_edit
    );

    drop(child);
}