markdown-org-extract 0.17.0

Library and CLI for extracting tasks from markdown files with Emacs Org-mode support
Documentation
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
//! End-to-end CLI tests. The binary is invoked through `assert_cmd` against
//! the markdown fixtures in `examples/`, with `--current-date` pinned so the
//! output is deterministic.

use assert_cmd::Command;
use predicates::str::contains;
use std::fs;
use tempfile::tempdir;

fn bin() -> Command {
    Command::cargo_bin("markdown-org-extract").expect("binary should build")
}

#[test]
fn shows_help_with_usage_section() {
    bin()
        .arg("--help")
        .assert()
        .success()
        .stdout(contains("Usage:"))
        .stdout(contains("--dir"))
        .stdout(contains("--format"));
}

#[test]
fn rejects_nonexistent_dir() {
    bin()
        .args([
            "--dir",
            "/this/path/should/never/exist_xyz",
            "--current-date",
            "2025-12-05",
        ])
        .assert()
        .failure()
        .stderr(contains("directory does not exist"));
}

#[test]
fn examples_directory_emits_json_with_relative_paths() {
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--format",
            "json",
            "--current-date",
            "2025-12-05",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    // Output is JSON
    assert!(stdout.starts_with("[") || stdout.starts_with("{"));
    // Relative paths by default — no host filesystem prefix
    assert!(
        !stdout.contains("/home/"),
        "default output must not contain absolute paths: {stdout:.200}"
    );
}

#[test]
fn absolute_paths_flag_emits_full_paths() {
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--absolute-paths",
            "--format",
            "json",
            "--current-date",
            "2025-12-05",
        ])
        .output()
        .expect("run");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    // With --absolute-paths we should see the path containing the fixture
    // directory. Use the platform-native separator so this works on Windows
    // (where JSON output preserves backslashes) as well as POSIX.
    let needle = format!("examples{}", std::path::MAIN_SEPARATOR);
    assert!(
        stdout.contains(&needle),
        "expected absolute path containing {needle:?} in stdout: {stdout:.200}"
    );
}

#[test]
fn output_flag_writes_to_file() {
    let dir = tempdir().unwrap();
    let target = dir.path().join("out.json");

    bin()
        .args([
            "--dir",
            "examples",
            "--format",
            "json",
            "--current-date",
            "2025-12-05",
            "--output",
        ])
        .arg(&target)
        .assert()
        .success();

    let content = fs::read_to_string(&target).unwrap();
    assert!(!content.is_empty());
    assert!(content.contains("\"date\""));
}

#[test]
fn output_flag_rejects_symlink() {
    let dir = tempdir().unwrap();
    let real = dir.path().join("real.json");
    let link = dir.path().join("link.json");
    fs::write(&real, "existing").unwrap();
    #[cfg(unix)]
    std::os::unix::fs::symlink(&real, &link).unwrap();

    #[cfg(unix)]
    {
        bin()
            .args([
                "--dir",
                "examples",
                "--format",
                "json",
                "--current-date",
                "2025-12-05",
                "--output",
            ])
            .arg(&link)
            .assert()
            .failure()
            .stderr(contains("symlink"));
    }
}

#[test]
fn holidays_year_returns_json_array() {
    let out = bin().args(["--holidays", "2026"]).output().expect("run");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.trim().starts_with('['));
    assert!(stdout.contains("2026-01-01"));
}

#[test]
fn invalid_year_rejected() {
    bin().args(["--holidays", "1800"]).assert().failure();
}

#[test]
fn double_star_glob_is_accepted() {
    // Regression: with globset we now support real glob patterns; `**/*.md`
    // is valid and should match recursively.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--glob",
            "**/*.md",
            "--format",
            "json",
            "--current-date",
            "2025-12-05",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn verbose_and_quiet_are_mutually_exclusive() {
    bin()
        .args([
            "--dir",
            "examples",
            "-v",
            "--quiet",
            "--current-date",
            "2025-12-05",
        ])
        .assert()
        .failure()
        .stderr(contains("cannot be used"));
}

#[test]
fn no_color_flag_is_accepted() {
    bin()
        .args([
            "--dir",
            "examples",
            "--no-color",
            "--current-date",
            "2025-12-05",
        ])
        .assert()
        .success();
}

#[test]
fn rejects_invalid_max_tasks() {
    bin()
        .args([
            "--dir",
            "examples",
            "--max-tasks",
            "0",
            "--current-date",
            "2025-12-05",
        ])
        .assert()
        .failure()
        .stderr(contains("--max-tasks"));
}

#[test]
fn max_tasks_one_caps_output() {
    // Tasks mode does not accept date arguments (see ADR-0009), so no
    // --current-date here; the cap is over the flat task list and is
    // deterministic from --max-tasks alone.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--format",
            "json",
            "--tasks",
            "--max-tasks",
            "1",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    // Count top-level JSON objects in the flat task list. Minimal sanity check:
    // limit=1 must not produce a multi-element array opening with `{` after `[`.
    // We rely on parsed shape: an array with at most one element.
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let arr = parsed.as_array().expect("array");
    assert!(
        arr.len() <= 1,
        "got {} tasks, expected at most 1",
        arr.len()
    );
}

#[test]
fn holidays_conflicts_with_scan_flags() {
    // --holidays short-circuits before any scanning; combining it with a
    // scan/agenda flag is almost certainly a user mistake — fail loudly
    // instead of silently ignoring the extra flag.
    bin()
        .args(["--holidays", "2026", "--dir", "examples"])
        .assert()
        .failure()
        .stderr(contains("cannot be used"));

    bin()
        .args(["--holidays", "2026", "--tasks"])
        .assert()
        .failure()
        .stderr(contains("cannot be used"));
}

#[test]
fn tasks_conflicts_with_range_flags() {
    // --tasks emits a flat list and ignores agenda windowing; --from/--to
    // only make sense with --agenda week/month, so combining them with
    // --tasks should fail rather than silently drop the range.
    bin()
        .args([
            "--tasks",
            "--from",
            "2026-01-01",
            "--current-date",
            "2026-01-15",
        ])
        .assert()
        .failure()
        .stderr(contains("cannot be used"));

    bin()
        .args([
            "--tasks",
            "--to",
            "2026-01-31",
            "--current-date",
            "2026-01-15",
        ])
        .assert()
        .failure()
        .stderr(contains("cannot be used"));
}

#[test]
fn rejects_malformed_glob() {
    bin()
        .args([
            "--dir",
            "examples",
            "--glob",
            "{md,",
            "--current-date",
            "2025-12-05",
        ])
        .assert()
        .failure()
        .stderr(contains("invalid pattern"));
}

#[test]
fn agenda_tasks_mode_produces_flat_list() {
    // `--agenda tasks` is the value-enum form of the legacy `--tasks` flag.
    // Both must produce the same flat-list JSON shape (top-level array of
    // task objects, not an array of day-objects).
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "tasks",
            "--format",
            "json",
            "--max-tasks",
            "3",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let arr = parsed.as_array().expect("top-level array");
    // Flat task list: each element is a task object with `file`/`line` etc.,
    // not a day object with `date`/`overdue`/... keys.
    if let Some(first) = arr.first() {
        let obj = first.as_object().expect("task object");
        assert!(
            obj.contains_key("file") && obj.contains_key("line"),
            "expected flat-task shape, got: {first}"
        );
        assert!(
            !obj.contains_key("date"),
            "got day-shaped object instead of flat task: {first}"
        );
    }
}

#[test]
fn unknown_locale_is_hard_error_even_under_quiet() {
    // --locale must reject unknown entries at parse time, not at log time:
    // a tracing::warn! would be swallowed by --quiet and a user typing
    // `--locale en,de --quiet` would silently get zero `de` mappings.
    // Validate-at-CLI puts the error on the same tier as `--dir` /
    // `--tz` / `--date` checks (exit code 2 from AppError::InvalidOutput
    // equivalents -- here clap's own usage-error path produces 2).
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--current-date",
            "2025-12-05",
            "--locale",
            "ru,xx",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        !out.status.success(),
        "expected failure, got success; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(
        out.status.code(),
        Some(2),
        "expected exit code 2 for usage error, got: {:?}, stderr: {}",
        out.status.code(),
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("unknown locale"),
        "expected 'unknown locale' wording, got: {stderr}"
    );
    assert!(
        stderr.contains("xx"),
        "expected offending value 'xx', got: {stderr}"
    );
}

#[test]
fn known_locales_do_not_warn() {
    // ru and en are both supported (en as a no-op). Neither should emit a
    // warning even when used together.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--current-date",
            "2025-12-05",
            "--locale",
            "ru,en",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        out.stderr.is_empty(),
        "expected no warnings for ru,en, got: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn validator_error_messages_match_clap_lowercase_style() {
    // clap prints `error: invalid value '<v>' for '--<arg> ...':` before the
    // validator's text. If our validators start with `Invalid <kind> '<v>':`
    // the whole line becomes `invalid value ...: Invalid <kind> ...:` -- the
    // same noun twice with mismatched capitalisation. Pin the style: no
    // re-echoed value, no capitalised prefix, lowercased reason.
    let out = bin()
        .args(["--dir", "examples", "--current-date", "abc"])
        .output()
        .expect("run");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("invalid value 'abc'"),
        "expected clap prefix, got: {stderr}"
    );
    assert!(
        !stderr.contains("Invalid date"),
        "validator must not start with `Invalid date`, got: {stderr}"
    );
    assert!(
        stderr.contains("use YYYY-MM-DD format"),
        "expected lowercase hint, got: {stderr}"
    );
}

#[test]
fn color_flag_accepts_auto_always_never() {
    // All three values must parse. `auto` is the default and behaves like
    // pre-existing logic (TTY-based). `always` and `never` are the explicit
    // override forms.
    for v in ["auto", "always", "never"] {
        bin()
            .args([
                "--dir",
                "examples",
                "--color",
                v,
                "--max-tasks",
                "1",
                "--tasks",
                "--format",
                "json",
            ])
            .assert()
            .success();
    }
}

#[test]
fn color_flag_rejects_unknown_value() {
    bin()
        .args([
            "--dir",
            "examples",
            "--current-date",
            "2025-12-05",
            "--color",
            "purple",
        ])
        .assert()
        .failure()
        .stderr(contains("invalid value"));
}

#[test]
fn agenda_conflicts_with_tasks_flag() {
    // `--agenda day` (or week/month) selects a windowed view; `--tasks`
    // selects a flat list. The two modes are mutually exclusive at the
    // clap layer via conflicts_with on --agenda. Pin the rejection so a
    // refactor that drops the conflict cannot quietly let one mode
    // override the other.
    bin()
        .args([
            "--dir",
            "examples",
            "--current-date",
            "2025-12-05",
            "--agenda",
            "week",
            "--tasks",
        ])
        .assert()
        .failure()
        .stderr(contains("cannot be used"));
}

#[test]
fn verbose_conflicts_with_quiet() {
    // `-v` raises log level above warn; `-q` lowers it to error. Combining
    // them is meaningless: the user can't both want more and less
    // diagnostics at the same time. The conflict is on the --quiet arg.
    bin()
        .args([
            "--dir",
            "examples",
            "--current-date",
            "2025-12-05",
            "--verbose",
            "--quiet",
        ])
        .assert()
        .failure()
        .stderr(contains("cannot be used"));

    // `-v` short form must trigger the same conflict; the relationship is
    // on the long names but short aliases share the same arg id.
    bin()
        .args([
            "--dir",
            "examples",
            "--current-date",
            "2025-12-05",
            "-v",
            "-q",
        ])
        .assert()
        .failure()
        .stderr(contains("cannot be used"));
}

#[test]
fn color_conflicts_with_no_color() {
    // Both flags carry intent; combining them is almost certainly a mistake.
    // Force the user to pick one rather than silently letting --no-color win.
    bin()
        .args([
            "--dir",
            "examples",
            "--current-date",
            "2025-12-05",
            "--color",
            "always",
            "--no-color",
        ])
        .assert()
        .failure()
        .stderr(contains("cannot be used"));
}

#[test]
fn help_mentions_format_md_alias() {
    // README documents `--format md`, so the short help must echo the alias.
    // clap doesn't render value-enum aliases in `[possible values: ...]`, so
    // the alias has to live in the per-arg docstring. Pin both `-h` and
    // `--help` against silently dropping it.
    let short = bin().arg("-h").output().expect("run");
    let short_out = String::from_utf8_lossy(&short.stdout);
    assert!(
        short_out.contains("`md`"),
        "expected `md` alias in -h, got: {short_out}"
    );
    let long = bin().arg("--help").output().expect("run");
    let long_out = String::from_utf8_lossy(&long.stdout);
    assert!(
        long_out.contains("`md`"),
        "expected `md` alias in --help, got: {long_out}"
    );
}

#[test]
fn output_dash_writes_to_stdout_and_creates_no_file() {
    // `--output -` is the standard unix sigil for "write to stdout"; with it,
    // the result must arrive on stdout and no file named `-` should appear.
    let dir = tempdir().unwrap();
    let out = bin()
        .current_dir(dir.path())
        .args([
            "--dir",
            concat!(env!("CARGO_MANIFEST_DIR"), "/examples"),
            "--format",
            "json",
            "--tasks",
            "--output",
            "-",
            "--max-tasks",
            "1",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    let _parsed: serde_json::Value =
        serde_json::from_str(&stdout).expect("stdout must be valid JSON");
    assert!(
        !dir.path().join("-").exists(),
        "literal file `-` must not be created"
    );
}

#[test]
fn verbose_emits_info_summary_on_stderr() {
    // -v lifts the default log level to info, which makes the `scan finished`
    // summary visible. Locks the info-emitter against accidental downgrade.
    let out = bin()
        .args(["--dir", "examples", "--current-date", "2025-12-05", "-v"])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("scan finished"),
        "expected info summary on stderr at -v, got: {stderr}"
    );
}

#[test]
fn quiet_suppresses_all_diagnostics_on_stderr() {
    // --quiet drops the log level to error and skips the processing-summary
    // print on its own. With a clean fixture set there should be nothing
    // diagnostic on stderr — pin this so future tracing additions don't
    // silently leak through quiet mode.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--current-date",
            "2025-12-05",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        out.stderr.is_empty(),
        "expected empty stderr with --quiet, got: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn help_no_color_mentions_env_var_equivalence() {
    // The --no-color help text must say the NO_COLOR env var has the *same*
    // effect (not "honors as well", which reads ambiguously). Pin the wording
    // so a future help-text edit cannot reintroduce the ambiguity.
    let out = bin().arg("--help").output().expect("run");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("NO_COLOR"), "missing NO_COLOR mention");
    assert!(
        stdout.contains("same effect"),
        "expected 'same effect' wording, got: {stdout}"
    );
}

#[test]
fn help_verbose_documents_the_trace_ceiling() {
    // MIN-8 (2026-05-25 review): the --verbose help promised
    // info/debug/trace but said nothing about `-vvvv+` saturating at
    // trace. A user who escalated past `-vvv` expecting "more than trace"
    // got a runtime saturation warning with no documentation behind it.
    // The help now states the ceiling; pin the wording so it cannot
    // silently regress while `verbose_saturation_warns_on_vvvv_and_beyond`
    // keeps pinning the runtime side.
    let out = bin().arg("--help").output().expect("run");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("-vvv` is the maximum") || stdout.contains("-vvv is the maximum"),
        "expected the --verbose help to document the trace ceiling, got: {stdout}"
    );
}

#[test]
fn help_groups_arguments_into_named_sections() {
    // The flag count has grown to the point where a flat list is hard to
    // scan. clap's `help_heading` puts related flags under labelled sections
    // ("Input:", "Output:", ...). Pin the headings so a future edit cannot
    // silently regress to a flat list and leave users wading through 19
    // options in arrival order.
    let out = bin().arg("--help").output().expect("run");
    let stdout = String::from_utf8_lossy(&out.stdout);
    for heading in [
        "Input:",
        "Output:",
        "Agenda:",
        "Limits:",
        "Diagnostics:",
        "Actions:",
    ] {
        assert!(
            stdout.contains(heading),
            "expected `{heading}` section in --help, got: {stdout}"
        );
    }
}

#[test]
fn help_long_about_includes_runnable_examples() {
    // `--help` (long form) must include at least one example command so a
    // first-time reader sees what an invocation looks like. We pin the
    // ones most likely to be copy-pasted (today's agenda, holidays year,
    // bash completion install) rather than every example, so harmless
    // wording tweaks don't fail the test.
    let out = bin().arg("--help").output().expect("run");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("Examples:"),
        "expected `Examples:` block in long --help, got: {stdout}"
    );
    for needle in [
        "markdown-org-extract --dir ~/notes --agenda day",
        "markdown-org-extract --holidays 2026",
        "markdown-org-extract --completions bash",
    ] {
        assert!(
            stdout.contains(needle),
            "expected example `{needle}` in long --help, got: {stdout}"
        );
    }
}

#[test]
fn short_help_omits_examples_block() {
    // `-h` is the at-a-glance summary; the multi-line `Examples:` block
    // belongs only in `--help`. clap normally hides `long_about` from
    // `-h`, but if a future edit moves the examples into `about` they
    // would leak into `-h` and clutter the summary. Pin the contract.
    let out = bin().arg("-h").output().expect("run");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        !stdout.contains("Examples:"),
        "short `-h` must not include the Examples block, got: {stdout}"
    );
}

#[test]
fn help_long_about_includes_exit_status_section() {
    // CLI-UX info 1 / finding 9 (2026-05-25 review): shell scripts and bug
    // reports branch on exit codes, but they were documented only in the
    // source and the README. `--help` now carries an `Exit status:` block so
    // the codes are discoverable from the binary itself. Pin the heading plus
    // the two least-obvious codes (130 for signal, 74 for IO).
    let out = bin().arg("--help").output().expect("run");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("Exit status:"),
        "expected an `Exit status:` block in --help, got: {stdout}"
    );
    for code in ["130", "74"] {
        assert!(
            stdout.contains(code),
            "expected exit code `{code}` in the --help Exit status block, got: {stdout}"
        );
    }
}

#[test]
fn help_long_about_includes_environment_section() {
    // CLI-UX info 8 / finding (2026-05-25 review): the recognised env vars
    // (RUST_LOG, NO_COLOR, CLICOLOR, CLICOLOR_FORCE) were scattered across
    // individual flag help-texts. `--help` now consolidates them under an
    // `Environment:` block. Pin the heading and RUST_LOG (the one with
    // behavioural precedence over --verbose/--quiet).
    let out = bin().arg("--help").output().expect("run");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("Environment:"),
        "expected an `Environment:` block in --help, got: {stdout}"
    );
    assert!(
        stdout.contains("RUST_LOG"),
        "expected RUST_LOG in the --help Environment block, got: {stdout}"
    );
}

#[test]
fn short_about_mentions_json_default() {
    // CLI-UX info 1 / recommendation 2 (2026-05-25 review): JSON is the
    // default wire format (ADR-0001), but the short `about` shown by `-h`
    // did not say so — a user saw it only in the long `--help`. Pin the
    // JSON-default mention in the at-a-glance summary.
    let out = bin().arg("-h").output().expect("run");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("JSON by default"),
        "expected the short -h about to mention JSON as the default, got: {stdout}"
    );
}

#[test]
fn completions_help_uses_user_local_path() {
    // CLI-UX info 7 / recommendation 4 (2026-05-25 review): the per-arg help
    // for --completions suggested a system-wide path (/etc/bash_completion.d,
    // needs sudo) while the Examples block used a user-local one. A
    // root-free CLI should not steer users toward sudo. The system-wide
    // path is gone from --help; assert it does not reappear.
    let out = bin().arg("--help").output().expect("run");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        !stdout.contains("/etc/bash_completion.d"),
        "the --completions help must not steer users to a sudo-only system path, got: {stdout}"
    );
}

#[test]
fn completions_emit_elvish_and_powershell() {
    // CLI-UX info 5 / recommendation 5 (2026-05-25 review): the ValueEnum
    // accepts elvish and powershell, and the README lists them, but only
    // bash/zsh/fish were exercised. Smoke-pin that these two also emit a
    // non-trivial script and exit 0, so a clap_complete bump that drops one
    // fails CI.
    for shell in ["elvish", "powershell"] {
        let out = bin().args(["--completions", shell]).output().expect("run");
        assert!(
            out.status.success(),
            "--completions {shell} must succeed; stderr: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert!(
            out.stdout.len() > 200,
            "--completions {shell} should emit a non-trivial script, got {} bytes",
            out.stdout.len()
        );
    }
}

#[test]
fn version_flag_prints_semver() {
    // CLI-UX info 6 / recommendation 6 (2026-05-25 review): `#[command(version)]`
    // wires up --version, but nothing pinned it, so an accidental removal
    // would go unnoticed. Pin the exact `markdown-org-extract <X.Y.Z>` line
    // against the crate version.
    let out = bin().arg("--version").output().expect("run");
    assert!(
        out.status.success(),
        "--version must succeed; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    let expected = format!("markdown-org-extract {}", env!("CARGO_PKG_VERSION"));
    assert_eq!(
        stdout.trim(),
        expected,
        "--version output must be `{expected}`, got: {stdout}"
    );
}

#[test]
fn rejects_inverted_from_to_range() {
    // --from > --to should fail loudly with the DateRange variant; silently
    // accepting an empty range would produce a confusingly empty agenda. The
    // check is in agenda::parse_range; pin it from the CLI surface so a
    // refactor that drops the comparison cannot ship.
    bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "week",
            "--from",
            "2025-12-10",
            "--to",
            "2025-12-01",
            "--current-date",
            "2025-12-05",
        ])
        .assert()
        .failure()
        .stderr(contains("after end date"));
}

#[test]
fn debug_log_uses_unified_file_key_not_path() {
    // -vv enables debug-level events. The parser emits a `parsed file` event
    // inside a `file` span. Both the span and the parser events key the path
    // under `file = ...` (matching `Task.file`); the older split where the
    // span used `path=` while events used `file=` (O3, 2026-05-25 review) is
    // gone. The tracing fmt-layer prints span fields in the message, so a
    // clean run's stderr must carry `file=` and must NOT carry a stray `path=`
    // segment. Locks the unified key against regression.
    let out = bin()
        .args(["--dir", "examples", "--current-date", "2025-12-05", "-vv"])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("file="),
        "expected `file=` from the unified file key, got stderr: {stderr}"
    );
    assert!(
        !stderr.contains("path="),
        "the file span/events must use `file=`, never a stray `path=`; stderr: {stderr}"
    );
}

#[test]
fn run_span_wraps_scan_finished_at_info() {
    // O4 (2026-05-25 review): a root `run` span carries the scanned `dir` so
    // every event under it — including the info-level `scan finished` summary
    // — is attributable to a run. At -v the info span is active, so the
    // fmt-layer prefixes the `scan finished` line with `run{dir=...}:`. Pins
    // the root span against accidental removal without bloating the default
    // (warn) output, where an info span is inactive.
    let out = bin()
        .args(["--dir", "examples", "--current-date", "2025-12-05", "-v"])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    let scan_line = stderr
        .lines()
        .find(|l| l.contains("scan finished"))
        .unwrap_or_else(|| panic!("no `scan finished` line at -v; stderr: {stderr}"));
    assert!(
        scan_line.contains("run{dir="),
        "the `scan finished` line must inherit the root `run{{dir=...}}` span; line was: {scan_line}"
    );
}

#[test]
fn parse_repeater_rejection_uses_static_event_name() {
    // O6 (2026-05-25 review): the trace event fired when `parse_repeater`
    // rejects an input used the message `parse_repeater: rejected`, mixing the
    // operation identifier with the text. With `with_target(false)` the
    // operation is otherwise invisible, so the message is now a single static
    // name `parse_repeater_rejected` (the reason stays in the `reason` field).
    // A zero-step repeater `+0d` is the cheapest rejected input to exercise.
    let dir = tempdir().unwrap();
    let path = dir.path().join("repeater.md");
    fs::write(
        &path,
        "### TODO repeater probe\n`SCHEDULED: <2024-12-09 Mon +0d>`\n",
    )
    .unwrap();

    let out = bin()
        .args([
            "--dir",
            dir.path().to_str().unwrap(),
            "--current-date",
            "2024-12-09",
            "-vvv",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("parse_repeater_rejected"),
        "expected the static event name `parse_repeater_rejected` at -vvv; stderr: {stderr}"
    );
    assert!(
        !stderr.contains("parse_repeater: rejected"),
        "the colon-style message must be gone; stderr: {stderr}"
    );
}

// Exit-code routing per AppError category. The values come from `sysexits.h`
// where applicable (74 = EX_IOERR, 70 = EX_SOFTWARE); usage errors use `2` to
// match clap's own argument-error exit code so the boundary between
// clap-level and app-level validation failures is invisible to the caller.

#[test]
fn exit_code_2_for_invalid_directory() {
    let out = bin()
        .args([
            "--dir",
            "/this/path/should/never/exist_xyz_exitcode",
            "--current-date",
            "2025-12-05",
        ])
        .output()
        .expect("run");
    assert_eq!(
        out.status.code(),
        Some(2),
        "invalid --dir is a usage error, must exit 2 (got {:?}); stderr: {}",
        out.status.code(),
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn exit_code_2_for_invalid_output_parent() {
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--output",
            "/this/parent/should/never/exist/out.json",
            "--current-date",
            "2025-12-05",
        ])
        .output()
        .expect("run");
    assert_eq!(
        out.status.code(),
        Some(2),
        "invalid --output (missing parent) is a usage error, must exit 2 (got {:?}); stderr: {}",
        out.status.code(),
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn exit_code_74_for_io_when_output_is_a_directory() {
    let tmp = tempdir().expect("tmpdir");
    let out_path = tmp.path().join("collision-dir");
    fs::create_dir(&out_path).expect("create collision dir");

    let out = bin()
        .args([
            "--dir",
            "examples",
            "--output",
            out_path.to_str().unwrap(),
            "--current-date",
            "2025-12-05",
        ])
        .output()
        .expect("run");
    assert_eq!(
        out.status.code(),
        Some(74),
        "writing to a path that is a directory is an IO error, must exit 74 (got {:?}); stderr: {}",
        out.status.code(),
        String::from_utf8_lossy(&out.stderr)
    );
    // The Io variant now embeds the failing path in Display; pin that so a
    // refactor that drops the context (e.g. by reinstating a blanket
    // From<io::Error>) leaves an empty "io: : ..." trail and breaks loudly.
    let stderr = String::from_utf8_lossy(&out.stderr);
    let path_str = out_path.to_string_lossy();
    assert!(
        stderr.contains(&*path_str),
        "expected the failing path '{path_str}' in stderr, got: {stderr}"
    );
}

// Unified date-window semantics (ADR-0009). The agenda module accepts
// --from/--to as an alternative to --date in day/week/month, fills a
// missing edge from current_date (--current-date or today), and rejects
// any date argument in tasks mode. The integration tests below pin the
// CLI surface so a future agenda refactor cannot silently regress.

fn day_count_in_json(stdout: &str) -> usize {
    let parsed: serde_json::Value =
        serde_json::from_str(stdout).expect("stdout must be valid JSON");
    parsed.as_array().expect("top-level array").len()
}

/// The dates of the day-agendas in a JSON payload, in the order they were
/// emitted. Used by the grid tests, which are about which days came back
/// rather than how many.
fn day_dates_in_json(stdout: &str) -> Vec<String> {
    let parsed: serde_json::Value =
        serde_json::from_str(stdout).expect("stdout must be valid JSON");
    parsed
        .as_array()
        .expect("top-level array")
        .iter()
        .map(|day| {
            day.get("date")
                .and_then(serde_json::Value::as_str)
                .expect("every day carries a date")
                .to_string()
        })
        .collect()
}

#[test]
fn scheduled_cell_carries_the_occurrence_after_it() {
    // The JSON a client draws a cell from names the occurrence following that
    // cell, so a weekly task on 8 Dec points at 15 Dec while a daily one on
    // the same day points at 9 Dec. Pinned from the CLI because the field is
    // part of the wire contract, not an internal.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "day",
            "--current-date",
            "2025-12-08",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let parsed: serde_json::Value =
        serde_json::from_str(&String::from_utf8_lossy(&out.stdout)).expect("valid JSON");
    let day = parsed
        .as_array()
        .and_then(|days| days.first())
        .expect("one day");
    let scheduled: Vec<&serde_json::Value> = ["scheduled_timed", "scheduled_no_time"]
        .iter()
        .filter_map(|bucket| day.get(*bucket))
        .filter_map(serde_json::Value::as_array)
        .flatten()
        .collect();

    let after_for = |repeater: &str| -> Option<String> {
        scheduled
            .iter()
            .find(|task| task.get("timestamp_repeater").and_then(|r| r.as_str()) == Some(repeater))
            .and_then(|task| task.get("timestamp_next_after"))
            .and_then(serde_json::Value::as_str)
            .map(str::to_string)
    };

    assert_eq!(after_for("+1w").as_deref(), Some("2025-12-15"));
    assert_eq!(after_for("+1d").as_deref(), Some("2025-12-09"));
}

#[test]
fn agenda_month_grid_covers_the_weeks_the_month_touches() {
    // August 2026 opens on a Saturday and closes on a Monday: a grid of whole
    // Monday weeks runs 27.07 through 06.09.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "month-grid",
            "--date",
            "2026-08-12",
            "--current-date",
            "2026-08-12",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let dates = day_dates_in_json(&String::from_utf8_lossy(&out.stdout));
    assert_eq!(dates.len(), 42, "six rows of seven");
    assert_eq!(dates.first().map(String::as_str), Some("2026-07-27"));
    assert_eq!(dates.last().map(String::as_str), Some("2026-09-06"));
}

#[test]
fn agenda_month_grid_follows_week_start() {
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "month-grid",
            "--week-start",
            "sunday",
            "--date",
            "2026-08-12",
            "--current-date",
            "2026-08-12",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let dates = day_dates_in_json(&String::from_utf8_lossy(&out.stdout));
    assert_eq!(dates.first().map(String::as_str), Some("2026-07-26"));
    assert_eq!(dates.last().map(String::as_str), Some("2026-09-05"));
}

#[test]
fn agenda_month_grid_grows_an_explicit_range_to_whole_weeks() {
    // A grid is rows of seven whatever picked the window, so an explicit
    // range is grown to the weeks it touches: Wed 5 Aug .. Tue 11 Aug becomes
    // Mon 3 Aug .. Sun 16 Aug.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "month-grid",
            "--from",
            "2026-08-05",
            "--to",
            "2026-08-11",
            "--current-date",
            "2026-08-12",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let dates = day_dates_in_json(&String::from_utf8_lossy(&out.stdout));
    assert_eq!(dates.len(), 14, "two rows of seven");
    assert_eq!(dates.first().map(String::as_str), Some("2026-08-03"));
    assert_eq!(dates.last().map(String::as_str), Some("2026-08-16"));
}

#[test]
fn agenda_month_grid_rejects_an_anchored_week_start() {
    bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "month-grid",
            "--week-start",
            "today",
            "--current-date",
            "2026-08-12",
        ])
        .assert()
        .failure()
        .stderr(contains("month-grid"));
}

#[test]
fn agenda_week_start_shifts_the_week() {
    // The same week read from Sunday starts a day earlier. Pinned from the CLI
    // because the flag is what a client passes; the window itself is unit
    // tested in agenda.rs.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "week",
            "--week-start",
            "sunday",
            "--current-date",
            "2026-08-19",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let dates = day_dates_in_json(&String::from_utf8_lossy(&out.stdout));
    assert_eq!(dates.first().map(String::as_str), Some("2026-08-16"));
    assert_eq!(dates.last().map(String::as_str), Some("2026-08-22"));
}

#[test]
fn agenda_week_start_rejects_a_name_that_is_not_a_weekday() {
    // Refused by the parser, so the run fails with the usage exit code before
    // a single note is read, and the message lists what would have been
    // accepted instead of naming only the rejected word.
    bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "week",
            "--week-start",
            "payday",
            "--current-date",
            "2026-08-19",
        ])
        .assert()
        .code(2)
        .stderr(contains("week-start"))
        .stderr(contains("possible values"))
        .stderr(contains("monday"))
        .stderr(contains("today"));
}

#[test]
fn agenda_week_start_takes_a_three_letter_name() {
    // `sun` is the abbreviation org-mode users type; it must land on the same
    // window as `sunday`.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "week",
            "--week-start",
            "sun",
            "--current-date",
            "2026-08-19",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let dates = day_dates_in_json(&String::from_utf8_lossy(&out.stdout));
    assert_eq!(dates.first().map(String::as_str), Some("2026-08-16"));
    assert_eq!(dates.last().map(String::as_str), Some("2026-08-22"));
}

#[test]
fn agenda_week_start_ignores_case() {
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "week",
            "--week-start",
            "SUNDAY",
            "--current-date",
            "2026-08-19",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let dates = day_dates_in_json(&String::from_utf8_lossy(&out.stdout));
    assert_eq!(dates.first().map(String::as_str), Some("2026-08-16"));
}

#[test]
fn help_mentions_week_start_abbreviations() {
    // clap does not render value-enum aliases in `[possible values: …]`, so
    // the three-letter forms have to live in the flag's docstring — the same
    // arrangement `--format md` uses.
    let long = bin().arg("--help").output().expect("run");
    let long_out = String::from_utf8_lossy(&long.stdout);
    assert!(
        long_out.contains("`mon`"),
        "expected the `mon` abbreviation in --help, got: {long_out}"
    );
}

#[test]
fn agenda_day_with_from_to_emits_multi_day() {
    // --from/--to in day mode is no longer ignored: each day in [from..to]
    // produces a DayAgenda. Range 2025-12-01..2025-12-07 -> 7 days.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "day",
            "--from",
            "2025-12-01",
            "--to",
            "2025-12-07",
            "--current-date",
            "2025-12-05",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert_eq!(
        day_count_in_json(&stdout),
        7,
        "expected 7 day-agendas for [2025-12-01..2025-12-07]; got {stdout:.200}"
    );
}

#[test]
fn agenda_week_from_only_fills_to_from_current_date() {
    // --from X without --to: end is current_date. Range 2025-12-01..2025-12-05
    // -> 5 days.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "week",
            "--from",
            "2025-12-01",
            "--current-date",
            "2025-12-05",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(day_count_in_json(&String::from_utf8_lossy(&out.stdout)), 5);
}

#[test]
fn agenda_month_to_only_fills_from_from_current_date() {
    // --to Y without --from: start is current_date. Range 2025-12-05..2025-12-10
    // -> 6 days.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "month",
            "--to",
            "2025-12-10",
            "--current-date",
            "2025-12-05",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(day_count_in_json(&String::from_utf8_lossy(&out.stdout)), 6);
}

#[test]
fn agenda_day_from_after_current_date_fails() {
    // --from X without --to, where X > current_date: the inferred range is
    // inverted, must surface as DateRange.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "day",
            "--from",
            "2026-01-15",
            "--current-date",
            "2025-12-05",
        ])
        .output()
        .expect("run");
    assert!(!out.status.success(), "expected failure");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("after end date"),
        "expected DateRange diagnostic; got: {stderr}"
    );
}

#[test]
fn agenda_tasks_rejects_date_argument() {
    // Tasks mode is task-based, not date-centric: ADR-0009 rejects --date,
    // --from, --to, --current-date in this mode. --from is already blocked at
    // clap level (conflicts_with = "tasks"); --date must surface from agenda.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "tasks",
            "--date",
            "2025-12-05",
        ])
        .output()
        .expect("run");
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("tasks mode does not accept date arguments"),
        "expected ADR-0009 tasks-mode rejection; got: {stderr}"
    );
}

/// Shell completions: `--completions <SHELL>` short-circuits scanning and
/// emits the completion script for the given shell. The integration test
/// pins three shells (bash, zsh, fish) and asserts that the output mentions
/// the binary name; a script that does not at least name the binary cannot
/// be a valid completion file. The exact dialect of each shell's script is
/// owned by clap_complete and not re-asserted here.
#[test]
fn completions_emit_per_shell_script() {
    for shell in ["bash", "zsh", "fish"] {
        let out = bin().args(["--completions", shell]).output().expect("run");
        assert!(
            out.status.success(),
            "completions for {shell} must succeed; stderr: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            stdout.contains("markdown-org-extract"),
            "completion script for {shell} must mention the binary name; got: {stdout:.200}"
        );
        assert!(
            stdout.len() > 200,
            "completion script for {shell} looks empty ({} bytes)",
            stdout.len()
        );
    }
}

#[test]
fn completions_conflicts_with_scan_flags() {
    // --completions is a short-circuit like --holidays; mixing it with scan
    // flags would produce nonsense, so clap rejects the combination.
    bin()
        .args(["--completions", "bash", "--dir", "examples"])
        .assert()
        .failure()
        .stderr(contains("cannot be used"));
}

#[test]
fn completions_rejects_unknown_shell() {
    bin()
        .args(["--completions", "tcsh"])
        .assert()
        .failure()
        .stderr(contains("invalid value"));
}

/// Multi-segment glob pattern against a relative `--dir`. WalkBuilder used
/// to be fed `&cli.dir` (relative), so emitted paths stayed relative and
/// `strip_prefix(dir_canonical)` failed, dropping callers to a `file_name()`
/// fallback that could not match a multi-segment pattern like `sub/*.md`.
/// Feeding WalkBuilder the canonical absolute path fixes this; this test
/// pins the fix so any later refactor cannot regress it.
#[test]
fn multi_segment_glob_matches_with_relative_dir() {
    let tmp = tempdir().expect("tmp");
    let workspace = tmp.path().join("ws");
    let sub = workspace.join("sub");
    fs::create_dir_all(&sub).expect("mkdir sub");
    fs::write(sub.join("foo.md"), "### TODO Foo task\n").expect("write foo.md");
    fs::write(sub.join("bar.md"), "### TODO Bar task\n").expect("write bar.md");
    fs::write(
        workspace.join("top.md"),
        "### TODO Top task should not be matched\n",
    )
    .expect("write top.md");

    let out = bin()
        .current_dir(tmp.path())
        .args([
            "--dir", "ws", "--glob", "sub/*.md", "--tasks", "--format", "json", "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "scan must succeed; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let arr = parsed.as_array().expect("array");
    assert_eq!(
        arr.len(),
        2,
        "expected exactly 2 matches (foo.md, bar.md); got {arr:?}"
    );
    let headings: Vec<&str> = arr
        .iter()
        .filter_map(|t| t.get("heading").and_then(|h| h.as_str()))
        .collect();
    assert!(
        headings.iter().any(|h| h.contains("Foo")),
        "expected Foo task; headings: {headings:?}"
    );
    assert!(
        headings.iter().any(|h| h.contains("Bar")),
        "expected Bar task; headings: {headings:?}"
    );
    assert!(
        !headings.iter().any(|h| h.contains("Top")),
        "Top task must not match `sub/*.md`; headings: {headings:?}"
    );
}

/// Test fixture: an unreadable subdirectory should not abort the scan. The
/// test creates a workspace with one readable file and one mode-0 subtree,
/// runs the binary against the workspace root, and verifies that
///
/// 1. The exit code is 0 (the scan reported usable output).
/// 2. The readable file's tasks are present in stdout.
/// 3. The summary on stderr mentions walk_errors > 0.
#[cfg(unix)]
#[test]
fn output_write_to_readonly_parent_exits_74_with_path_in_stderr() {
    // EACCES on the write itself (parent dir is r-x, no w) is the most
    // common --output failure in CI sandboxes and locked-down deploy
    // directories. The path must be in stderr — without it the user
    // sees a bare "Permission denied (os error 13)" and has to guess.
    use std::os::unix::fs::PermissionsExt;

    let tmp = tempdir().expect("tmpdir");
    let ro_dir = tmp.path().join("ro");
    fs::create_dir(&ro_dir).expect("mkdir ro");
    let out_path = ro_dir.join("out.json");

    let mut perms = fs::metadata(&ro_dir).expect("metadata").permissions();
    perms.set_mode(0o555);
    fs::set_permissions(&ro_dir, perms).expect("chmod 555");

    let out = bin()
        .args([
            "--dir",
            "examples",
            "--output",
            out_path.to_str().unwrap(),
            "--current-date",
            "2025-12-05",
            "--quiet",
        ])
        .output()
        .expect("run");

    // Restore perms before assertions so tempdir cleanup can remove the dir.
    let mut perms = fs::metadata(&ro_dir).expect("metadata").permissions();
    perms.set_mode(0o755);
    fs::set_permissions(&ro_dir, perms).expect("chmod restore");

    assert_eq!(
        out.status.code(),
        Some(74),
        "write into read-only parent must exit 74 (EX_IOERR); stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    let path_str = out_path.to_string_lossy();
    assert!(
        stderr.contains(&*path_str),
        "expected the failing path '{path_str}' in stderr, got: {stderr}"
    );
}

#[cfg(unix)]
#[test]
fn output_write_to_readonly_file_exits_74_with_path_in_stderr() {
    // Overwriting an existing file that has no write bit set is the
    // second failure mode for --output. Same exit code (74), same
    // path-in-stderr contract — pin both so a refactor that swallows
    // the path or downgrades the exit code regresses loudly.
    use std::os::unix::fs::PermissionsExt;

    let tmp = tempdir().expect("tmpdir");
    let out_path = tmp.path().join("locked.json");
    fs::write(&out_path, b"placeholder").expect("write placeholder");
    let mut perms = fs::metadata(&out_path).expect("metadata").permissions();
    perms.set_mode(0o444);
    fs::set_permissions(&out_path, perms).expect("chmod 444");

    let out = bin()
        .args([
            "--dir",
            "examples",
            "--output",
            out_path.to_str().unwrap(),
            "--current-date",
            "2025-12-05",
            "--quiet",
        ])
        .output()
        .expect("run");

    // Restore so tempdir can clean up.
    let mut perms = fs::metadata(&out_path).expect("metadata").permissions();
    perms.set_mode(0o644);
    fs::set_permissions(&out_path, perms).expect("chmod restore");

    assert_eq!(
        out.status.code(),
        Some(74),
        "overwrite of read-only file must exit 74 (EX_IOERR); stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    let path_str = out_path.to_string_lossy();
    assert!(
        stderr.contains(&*path_str),
        "expected the failing path '{path_str}' in stderr, got: {stderr}"
    );
}

#[cfg(unix)]
#[test]
fn walker_continues_after_permission_denied_subdir() {
    use std::os::unix::fs::PermissionsExt;

    let root = tempdir().expect("tmp");
    fs::write(
        root.path().join("ok.md"),
        "# Notes\n\n### TODO First\n`SCHEDULED: <2025-12-05 Fri>`\n",
    )
    .expect("write ok.md");

    let blocked = root.path().join("blocked");
    fs::create_dir(&blocked).expect("mkdir blocked");
    fs::write(
        blocked.join("hidden.md"),
        "# Hidden\n### TODO Hidden task\n",
    )
    .expect("write hidden.md");
    let mut perms = fs::metadata(&blocked).expect("metadata").permissions();
    perms.set_mode(0o000);
    fs::set_permissions(&blocked, perms).expect("chmod 0");

    let out = bin()
        .args([
            "--dir",
            root.path().to_str().unwrap(),
            "--tasks",
            "--format",
            "json",
            "-v",
        ])
        .output()
        .expect("run");

    // Restore permissions before assertions so the tempdir cleanup can recurse.
    let mut perms = fs::metadata(&blocked).expect("metadata").permissions();
    perms.set_mode(0o755);
    fs::set_permissions(&blocked, perms).expect("chmod restore");

    assert!(
        out.status.success(),
        "scan must succeed despite walker error; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("First"),
        "readable file's task must be in output; stdout: {stdout:.500}"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("walk_errors") || stderr.contains("walker entry failed"),
        "summary or per-error warning must mention the walker error; stderr: {stderr}"
    );
}

#[test]
fn holidays_conflicts_with_agenda_window_arguments() {
    // `--holidays` short-circuits before any scanning, so an agenda argument
    // beside it would be silently dropped. Every window argument is listed in
    // the conflict set, `--week-start` included.
    bin()
        .args(["--holidays", "2026", "--week-start", "sunday"])
        .assert()
        .code(2)
        .stderr(contains("cannot be used with"));
    bin()
        .args(["--holidays", "2026", "--current-date", "2026-08-19"])
        .assert()
        .code(2)
        .stderr(contains("cannot be used with"));
}

#[test]
fn agenda_tasks_rejects_week_start_argument() {
    // A week start is a window argument like the dates beside it, and the flat
    // list has no window to begin. Refused through `--agenda tasks`, the path
    // clap's `conflicts_with = "tasks"` does not cover.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "tasks",
            "--week-start",
            "sunday",
        ])
        .output()
        .expect("run");
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("tasks mode does not accept date arguments"),
        "expected the tasks-mode rejection; got: {stderr}"
    );
}

#[test]
fn tasks_flag_conflicts_with_week_start() {
    // The legacy `--tasks` spelling is refused earlier, by the parser itself.
    bin()
        .args(["--dir", "examples", "--tasks", "--week-start", "sunday"])
        .assert()
        .code(2)
        .stderr(contains("cannot be used with"));
}

#[test]
fn agenda_day_accepts_week_start_without_changing_the_window() {
    // The flag reaches week-shaped windows only; a single day has no week to
    // align, so it is accepted and leaves the day alone rather than being
    // refused.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "day",
            "--week-start",
            "sunday",
            "--current-date",
            "2026-08-19",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let dates = day_dates_in_json(&String::from_utf8_lossy(&out.stdout));
    assert_eq!(dates, vec!["2026-08-19".to_string()]);
}

#[test]
fn agenda_tasks_rejects_current_date_argument() {
    // --current-date in tasks mode is also rejected: tasks mode has no
    // overdue calculation, so the "today" reference has no effect.
    let out = bin()
        .args([
            "--dir",
            "examples",
            "--agenda",
            "tasks",
            "--current-date",
            "2025-12-05",
        ])
        .output()
        .expect("run");
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("tasks mode does not accept date arguments"),
        "expected ADR-0009 tasks-mode rejection; got: {stderr}"
    );
}

// Byte-exact JSON snapshots. The wire contract is documented in ADR-0001
// (JSON on stdout) and consumed by downstream tooling; a reordering of
// fields, a change of indentation, or a missing newline would silently
// break that contract. The tests below pin two output shapes against a
// hand-written fixture so any structural drift requires updating the
// snapshot here in the same commit as the source change.

#[test]
fn json_snapshot_tasks_mode_minimal_fixture() {
    // A single TODO with SCHEDULED + relative paths is the smallest input
    // that exercises every Task field (file, line, heading, content,
    // task_type, timestamp, timestamp_type, timestamp_date). `tasks` mode
    // forbids --current-date by ADR-0009, so there are no date-dependent
    // outputs to make the snapshot drift between runs.
    let tmp = tempdir().expect("tmpdir");
    fs::write(
        tmp.path().join("notes.md"),
        "# Notes\n\n### TODO Pin me\n`SCHEDULED: <2026-05-21 Thu>`\n",
    )
    .expect("write notes.md");

    let out = bin()
        .args([
            "--dir",
            tmp.path().to_str().unwrap(),
            "--tasks",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("stdout is UTF-8");
    let expected = "\
[
  {
    \"file\": \"notes.md\",
    \"line\": 3,
    \"heading\": \"Pin me\",
    \"content\": \"\",
    \"task_type\": \"TODO\",
    \"timestamp\": \"SCHEDULED: <2026-05-21 Thu>\",
    \"timestamp_type\": \"SCHEDULED\",
    \"timestamp_active\": true,
    \"timestamp_date\": \"2026-05-21\"
  }
]
";
    assert_eq!(
        stdout, expected,
        "JSON tasks snapshot must be byte-exact; got:\n{stdout}"
    );
}

#[test]
fn json_snapshot_agenda_day_minimal_fixture() {
    // Pin the agenda-day envelope (date, scheduled_timed, scheduled_no_time,
    // upcoming). Same fixture as the tasks snapshot but with
    // `--agenda day --current-date 2026-05-21` to materialise the wrapper
    // fields. Without this snapshot a renamed array key or a flip of
    // overdue vs scheduled would slip past every existing test.
    let tmp = tempdir().expect("tmpdir");
    fs::write(
        tmp.path().join("notes.md"),
        "# Notes\n\n### TODO Pin me\n`SCHEDULED: <2026-05-21 Thu>`\n",
    )
    .expect("write notes.md");

    let out = bin()
        .args([
            "--dir",
            tmp.path().to_str().unwrap(),
            "--agenda",
            "day",
            "--current-date",
            "2026-05-21",
            "--tz",
            "UTC",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("stdout is UTF-8");
    let expected = "\
[
  {
    \"date\": \"2026-05-21\",
    \"scheduled_timed\": [],
    \"scheduled_no_time\": [
      {
        \"file\": \"notes.md\",
        \"line\": 3,
        \"heading\": \"Pin me\",
        \"content\": \"\",
        \"task_type\": \"TODO\",
        \"timestamp\": \"SCHEDULED: <2026-05-21 Thu>\",
        \"timestamp_type\": \"SCHEDULED\",
        \"timestamp_active\": true,
        \"timestamp_date\": \"2026-05-21\"
      }
    ],
    \"upcoming\": []
  }
]
";
    assert_eq!(
        stdout, expected,
        "JSON agenda-day snapshot must be byte-exact; got:\n{stdout}"
    );
}

#[test]
fn json_snapshot_agenda_day_repeating_task_carries_timestamp_next() {
    // Pin `timestamp_next` (ADR-0023) in the wire contract: its position
    // after `timestamp_repeater`, its `YYYY-MM-DD` shape, and the anchoring
    // rule. The fixture repeats monthly from the 31st, so the value also
    // proves the field is computed from the task's own anchor rather than
    // from the rewritten `timestamp_date` of the rendered occurrence
    // (30.04 here): month-end anchoring survives, giving 31.05.
    let tmp = tempdir().expect("tmpdir");
    fs::write(
        tmp.path().join("notes.md"),
        "# Notes\n\n### TODO Pin me\n`SCHEDULED: <2026-01-31 Sat ++1m>`\n",
    )
    .expect("write notes.md");

    let out = bin()
        .args([
            "--dir",
            tmp.path().to_str().unwrap(),
            "--agenda",
            "day",
            "--current-date",
            "2026-05-21",
            "--tz",
            "UTC",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("stdout is UTF-8");
    let expected = "\
[
  {
    \"date\": \"2026-05-21\",
    \"overdue\": [
      {
        \"file\": \"notes.md\",
        \"line\": 3,
        \"heading\": \"Pin me\",
        \"content\": \"\",
        \"task_type\": \"TODO\",
        \"timestamp\": \"SCHEDULED: <2026-04-30 Thu ++1m>\",
        \"timestamp_type\": \"SCHEDULED\",
        \"timestamp_active\": true,
        \"timestamp_date\": \"2026-04-30\",
        \"timestamp_repeater\": \"++1m\",
        \"timestamp_next\": \"2026-05-31\",
        \"days_offset\": -21
      }
    ],
    \"scheduled_timed\": [],
    \"scheduled_no_time\": [],
    \"upcoming\": []
  }
]
";
    assert_eq!(
        stdout, expected,
        "JSON agenda-day repeating snapshot must be byte-exact; got:\n{stdout}"
    );
}

#[test]
fn timestamp_next_is_the_same_in_every_cell_of_a_week_payload() {
    // The field names the next occurrence relative to now, not to the cell
    // it is rendered in, so one task must carry one value across the whole
    // week -- including the cells whose `timestamp_date` was rewritten to
    // that cell's own date.
    let tmp = tempdir().expect("tmpdir");
    fs::write(
        tmp.path().join("notes.md"),
        "# Notes\n\n### TODO Weekly sync\n`SCHEDULED: <2026-07-21 Tue ++7d>`\n",
    )
    .expect("write notes.md");

    let out = bin()
        .args([
            "--dir",
            tmp.path().to_str().unwrap(),
            "--agenda",
            "week",
            "--current-date",
            "2026-07-22",
            "--tz",
            "UTC",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("stdout is UTF-8");
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");

    let mut seen: Vec<String> = Vec::new();
    for day in parsed.as_array().expect("array of days") {
        for bucket in [
            "overdue",
            "scheduled_timed",
            "scheduled_no_time",
            "upcoming",
        ] {
            for item in day[bucket].as_array().into_iter().flatten() {
                seen.push(
                    item["timestamp_next"]
                        .as_str()
                        .unwrap_or("<missing>")
                        .to_string(),
                );
            }
        }
    }

    assert!(!seen.is_empty(), "week payload must contain the task");
    assert!(
        seen.iter().all(|v| v == "2026-07-28"),
        "every cell must carry 2026-07-28; got {seen:?} in:\n{stdout}"
    );
}

#[test]
fn timestamp_next_is_absent_in_tasks_mode() {
    // ADR-0009 keeps the flat list date-less, so ADR-0023 deliberately does
    // not annotate it: a now-relative field would make the output
    // non-deterministic. A repeating task is the case that would regress.
    let tmp = tempdir().expect("tmpdir");
    fs::write(
        tmp.path().join("notes.md"),
        "# Notes\n\n### TODO Weekly sync\n`SCHEDULED: <2026-07-21 Tue ++7d>`\n",
    )
    .expect("write notes.md");

    let out = bin()
        .args(["--dir", tmp.path().to_str().unwrap(), "--tasks", "--quiet"])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("stdout is UTF-8");
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");

    for task in parsed.as_array().expect("array of tasks") {
        assert!(
            task.get("timestamp_next").is_none(),
            "tasks mode must not carry timestamp_next; got:\n{stdout}"
        );
    }
}

#[test]
fn timestamp_next_is_absent_for_a_task_without_a_repeater() {
    let tmp = tempdir().expect("tmpdir");
    fs::write(
        tmp.path().join("notes.md"),
        "# Notes\n\n### TODO One-off\n`SCHEDULED: <2026-05-21 Thu>`\n",
    )
    .expect("write notes.md");

    let out = bin()
        .args([
            "--dir",
            tmp.path().to_str().unwrap(),
            "--agenda",
            "day",
            "--current-date",
            "2026-05-21",
            "--tz",
            "UTC",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("stdout is UTF-8");
    assert!(
        !stdout.contains("timestamp_next"),
        "a non-repeating task must not carry the field; got:\n{stdout}"
    );
}

#[test]
fn json_snapshot_tasks_mode_clock_entry() {
    // MIN-12 (2026-05-25 tests review): the existing snapshots never
    // exercised the CLOCK fields. Pin the `clocks` array element shape
    // (start / end / duration) and the derived `total_clock_time` so a
    // rename or reordering of those keys -- a breaking change under
    // ADR-0015 -- cannot slip past the suite. CLOCK bracket forms are
    // governed by ADR-0003.
    let tmp = tempdir().expect("tmpdir");
    fs::write(
        tmp.path().join("clock.md"),
        "# Notes\n\n### TODO Clocked task\n`SCHEDULED: <2026-05-21 Thu>`\n\
         `CLOCK: [2026-05-21 Thu 10:00]--[2026-05-21 Thu 11:30] => 1:30`\n",
    )
    .expect("write clock.md");

    let out = bin()
        .args([
            "--dir",
            tmp.path().to_str().unwrap(),
            "--tasks",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("stdout is UTF-8");
    let expected = "\
[
  {
    \"file\": \"clock.md\",
    \"line\": 3,
    \"heading\": \"Clocked task\",
    \"content\": \"\",
    \"task_type\": \"TODO\",
    \"timestamp\": \"SCHEDULED: <2026-05-21 Thu>\",
    \"timestamp_type\": \"SCHEDULED\",
    \"timestamp_active\": true,
    \"timestamp_date\": \"2026-05-21\",
    \"clocks\": [
      {
        \"start\": \"2026-05-21 Thu 10:00\",
        \"end\": \"2026-05-21 Thu 11:30\",
        \"duration\": \"1:30\"
      }
    ],
    \"total_clock_time\": \"1:30\"
  }
]
";
    assert_eq!(
        stdout, expected,
        "JSON CLOCK snapshot must be byte-exact; got:\n{stdout}"
    );
}

#[test]
fn json_snapshot_tasks_mode_inactive_timestamp() {
    // MIN-12: pin `timestamp_active: false` for an inactive `[...]`
    // timestamp. The active/inactive marker is the ADR-0014 contract that
    // markdown-org-vscode relies on to round-trip the bracket form; a
    // regression that dropped or inverted it would be a silent breaking
    // change.
    let tmp = tempdir().expect("tmpdir");
    fs::write(
        tmp.path().join("inactive.md"),
        "# Notes\n\n### TODO Inactive stamp\n`[2026-05-21 Thu]`\n",
    )
    .expect("write inactive.md");

    let out = bin()
        .args([
            "--dir",
            tmp.path().to_str().unwrap(),
            "--tasks",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("stdout is UTF-8");
    let expected = "\
[
  {
    \"file\": \"inactive.md\",
    \"line\": 3,
    \"heading\": \"Inactive stamp\",
    \"content\": \"\",
    \"task_type\": \"TODO\",
    \"timestamp\": \"[2026-05-21 Thu]\",
    \"timestamp_type\": \"PLAIN\",
    \"timestamp_active\": false,
    \"timestamp_date\": \"2026-05-21\"
  }
]
";
    assert_eq!(
        stdout, expected,
        "JSON inactive-timestamp snapshot must be byte-exact; got:\n{stdout}"
    );
}

#[test]
fn json_snapshot_tasks_mode_repeater_and_warning_preserved() {
    // MIN-12: the warning cookie (`-3d`) is not a separate JSON field -- it
    // lives verbatim inside the `timestamp` string, which downstream tooling
    // re-parses. Pin that the string is surfaced byte-for-byte so a future
    // "helpful" normalisation of the timestamp cannot silently drop it. The
    // repeater (`+1m`) is additionally surfaced as its own canonical
    // `timestamp_repeater` field (ADR-0015) for RRULE mapping downstream,
    // while remaining present inside the raw `timestamp` string too.
    let tmp = tempdir().expect("tmpdir");
    fs::write(
        tmp.path().join("rep.md"),
        "# Notes\n\n### TODO Repeating with warning\n`DEADLINE: <2026-05-21 Thu +1m -3d>`\n",
    )
    .expect("write rep.md");

    let out = bin()
        .args([
            "--dir",
            tmp.path().to_str().unwrap(),
            "--tasks",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("stdout is UTF-8");
    let expected = "\
[
  {
    \"file\": \"rep.md\",
    \"line\": 3,
    \"heading\": \"Repeating with warning\",
    \"content\": \"\",
    \"task_type\": \"TODO\",
    \"timestamp\": \"DEADLINE: <2026-05-21 Thu +1m -3d>\",
    \"timestamp_type\": \"DEADLINE\",
    \"timestamp_active\": true,
    \"timestamp_date\": \"2026-05-21\",
    \"timestamp_repeater\": \"+1m\"
  }
]
";
    assert_eq!(
        stdout, expected,
        "JSON repeater/warning snapshot must be byte-exact; got:\n{stdout}"
    );
}

#[test]
fn json_snapshot_agenda_week_envelope() {
    // MIN-12: pin the week envelope. It is an array of seven day objects
    // (date / scheduled_timed / scheduled_no_time / upcoming) starting on
    // the Monday of the --current-date's ISO week (2026-05-18). The single
    // task lands on 2026-05-21 under scheduled_no_time; the other six days
    // are empty buckets, which pins both the day count and the per-day
    // shape against an array-key rename.
    let tmp = tempdir().expect("tmpdir");
    fs::write(
        tmp.path().join("wk.md"),
        "# Notes\n\n### TODO Week task\n`SCHEDULED: <2026-05-21 Thu>`\n",
    )
    .expect("write wk.md");

    let out = bin()
        .args([
            "--dir",
            tmp.path().to_str().unwrap(),
            "--agenda",
            "week",
            "--current-date",
            "2026-05-21",
            "--tz",
            "UTC",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("stdout is UTF-8");
    let expected = "\
[
  {
    \"date\": \"2026-05-18\",
    \"scheduled_timed\": [],
    \"scheduled_no_time\": [],
    \"upcoming\": []
  },
  {
    \"date\": \"2026-05-19\",
    \"scheduled_timed\": [],
    \"scheduled_no_time\": [],
    \"upcoming\": []
  },
  {
    \"date\": \"2026-05-20\",
    \"scheduled_timed\": [],
    \"scheduled_no_time\": [],
    \"upcoming\": []
  },
  {
    \"date\": \"2026-05-21\",
    \"scheduled_timed\": [],
    \"scheduled_no_time\": [
      {
        \"file\": \"wk.md\",
        \"line\": 3,
        \"heading\": \"Week task\",
        \"content\": \"\",
        \"task_type\": \"TODO\",
        \"timestamp\": \"SCHEDULED: <2026-05-21 Thu>\",
        \"timestamp_type\": \"SCHEDULED\",
        \"timestamp_active\": true,
        \"timestamp_date\": \"2026-05-21\"
      }
    ],
    \"upcoming\": []
  },
  {
    \"date\": \"2026-05-22\",
    \"scheduled_timed\": [],
    \"scheduled_no_time\": [],
    \"upcoming\": []
  },
  {
    \"date\": \"2026-05-23\",
    \"scheduled_timed\": [],
    \"scheduled_no_time\": [],
    \"upcoming\": []
  },
  {
    \"date\": \"2026-05-24\",
    \"scheduled_timed\": [],
    \"scheduled_no_time\": [],
    \"upcoming\": []
  }
]
";
    assert_eq!(
        stdout, expected,
        "JSON agenda-week snapshot must be byte-exact; got:\n{stdout}"
    );
}

#[test]
fn json_snapshot_agenda_month_envelope_shape() {
    // MIN-12: the month envelope reuses the same per-day object the week
    // snapshot pins byte-exactly, so rather than freeze a ~190-line
    // literal that breaks on every intentional edit, pin the month-window
    // contract structurally: 31 day objects for May 2026, spanning
    // 2026-05-01..2026-05-31, with the single task on the 21st. The
    // per-day key shape is already pinned by the week snapshot.
    let tmp = tempdir().expect("tmpdir");
    fs::write(
        tmp.path().join("mo.md"),
        "# Notes\n\n### TODO Month task\n`SCHEDULED: <2026-05-21 Thu>`\n",
    )
    .expect("write mo.md");

    let out = bin()
        .args([
            "--dir",
            tmp.path().to_str().unwrap(),
            "--agenda",
            "month",
            "--current-date",
            "2026-05-21",
            "--tz",
            "UTC",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("stdout is UTF-8");
    let days: Vec<serde_json::Value> = serde_json::from_str(&stdout).expect("valid JSON array");
    assert_eq!(days.len(), 31, "May 2026 has 31 day buckets");
    assert_eq!(days[0]["date"], "2026-05-01", "first bucket is the 1st");
    assert_eq!(days[30]["date"], "2026-05-31", "last bucket is the 31st");
    // Every bucket carries the four envelope keys.
    for (i, day) in days.iter().enumerate() {
        for key in ["date", "scheduled_timed", "scheduled_no_time", "upcoming"] {
            assert!(
                day.get(key).is_some(),
                "day {i} is missing the `{key}` envelope key: {day}"
            );
        }
    }
    // The task lands on the 21st under scheduled_no_time and nowhere else.
    let on_21 = &days[20];
    assert_eq!(on_21["date"], "2026-05-21");
    assert_eq!(
        on_21["scheduled_no_time"][0]["heading"], "Month task",
        "the task must sit on the 21st: {on_21}"
    );
    let total_tasks: usize = days
        .iter()
        .map(|d| d["scheduled_no_time"].as_array().map_or(0, |a| a.len()))
        .sum();
    assert_eq!(total_tasks, 1, "the task must appear on exactly one day");
}

// Output ends with a trailing newline regardless of format and destination.
// Rationale: POSIX defines a "text file" as ending in `\n`; without it the
// shell prompt is rendered on the same line as the last JSON `]`/HTML
// closing tag, and `diff` / line-counting tools mis-count the last line.
// Covers JSON / Markdown / HTML for both stdout and file outputs; the
// holiday short-circuit (`--holidays`) is exercised separately because it
// goes through a different write site (`handle_holidays`).

fn fixture_with_one_task() -> tempfile::TempDir {
    let tmp = tempdir().expect("tmpdir");
    fs::write(
        tmp.path().join("notes.md"),
        "# Notes\n\n### TODO Pin me\n`SCHEDULED: <2026-05-21 Thu>`\n",
    )
    .expect("write notes.md");
    tmp
}

fn run_with_format(tmp: &std::path::Path, format: &str) -> Vec<u8> {
    let out = bin()
        .args([
            "--dir",
            tmp.to_str().unwrap(),
            "--tasks",
            "--format",
            format,
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    out.stdout
}

#[test]
fn stdout_json_ends_with_newline() {
    let tmp = fixture_with_one_task();
    let bytes = run_with_format(tmp.path(), "json");
    assert_eq!(
        bytes.last().copied(),
        Some(b'\n'),
        "JSON stdout must end with a trailing newline; got tail: {:?}",
        String::from_utf8_lossy(&bytes[bytes.len().saturating_sub(8)..])
    );
}

#[test]
fn stdout_markdown_ends_with_newline() {
    let tmp = fixture_with_one_task();
    let bytes = run_with_format(tmp.path(), "markdown");
    assert_eq!(
        bytes.last().copied(),
        Some(b'\n'),
        "Markdown stdout must end with a trailing newline; got tail: {:?}",
        String::from_utf8_lossy(&bytes[bytes.len().saturating_sub(8)..])
    );
}

#[test]
fn stdout_html_ends_with_newline() {
    let tmp = fixture_with_one_task();
    let bytes = run_with_format(tmp.path(), "html");
    assert_eq!(
        bytes.last().copied(),
        Some(b'\n'),
        "HTML stdout must end with a trailing newline; got tail: {:?}",
        String::from_utf8_lossy(&bytes[bytes.len().saturating_sub(8)..])
    );
}

#[test]
fn output_file_ends_with_newline_for_each_format() {
    // The file-write path is `fs::write(p, output)`. Test all three formats
    // against the file path so a regression in only one format-stream pair
    // surfaces a precise failure rather than a generic "tail differs".
    let tmp = fixture_with_one_task();
    for format in ["json", "markdown", "html"] {
        let out_path = tmp.path().join(format!("out.{format}"));
        let result = bin()
            .args([
                "--dir",
                tmp.path().to_str().unwrap(),
                "--tasks",
                "--format",
                format,
                "--output",
                out_path.to_str().unwrap(),
                "--quiet",
            ])
            .output()
            .expect("run");
        assert!(
            result.status.success(),
            "format {format} failed to write: {}",
            String::from_utf8_lossy(&result.stderr)
        );
        let body = fs::read(&out_path).expect("read written file");
        assert_eq!(
            body.last().copied(),
            Some(b'\n'),
            "{} file output must end with a trailing newline; got tail: {:?}",
            format,
            String::from_utf8_lossy(&body[body.len().saturating_sub(8)..])
        );
    }
}

#[cfg(unix)]
#[test]
fn broken_pipe_exits_silently_without_diagnostic() {
    // Piping the binary into a consumer that closes the pipe (e.g.
    // `... | head -n 1`) used to surface `error: io: <stdout>: Broken
    // pipe (os error 32)` on stderr and a non-zero exit, even though
    // every Unix tool consuming the same pipeline is expected to terminate
    // quietly. Build a fixture large enough to exceed the typical 64 KB
    // pipe buffer so the write that fails is observed by the binary
    // (small outputs land entirely in the kernel buffer and the writer
    // never sees EPIPE).
    use std::path::PathBuf;
    use std::process::{Command as StdCommand, Stdio};

    let tmp = tempdir().expect("tmpdir");
    let block = "### TODO Task {{n}}\n`SCHEDULED: <2026-05-21 Thu>`\nContent line.\n\n";
    // 10 files × 100 tasks ≈ 1k entries ≈ ~200 KB of JSON — comfortably past
    // the typical 64 KiB pipe buffer so the binary observes EPIPE, without
    // making the test slow to generate.
    for i in 0..10 {
        let mut body = String::from("# Notes\n\n");
        for j in 0..100 {
            body.push_str(&block.replace("{{n}}", &format!("{i}_{j}")));
        }
        fs::write(tmp.path().join(format!("notes_{i:03}.md")), body).expect("write fixture file");
    }

    let bin_path: PathBuf = assert_cmd::cargo::cargo_bin("markdown-org-extract");
    let mut child = StdCommand::new(bin_path)
        .args([
            "--dir",
            tmp.path().to_str().unwrap(),
            "--tasks",
            "--format",
            "json",
            "--quiet",
        ])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn binary");

    // Drop the read end of the stdout pipe immediately. The first write
    // from the binary that does not fit in the kernel buffer hits EPIPE.
    drop(child.stdout.take());

    let output = child.wait_with_output().expect("wait");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "binary must exit 0 on broken pipe; got status {:?}, stderr: {}",
        output.status,
        stderr
    );
    assert!(
        !stderr.contains("Broken pipe"),
        "stderr must not surface the broken-pipe error; got: {stderr}"
    );
    assert!(
        !stderr.contains("error:"),
        "stderr must not carry any 'error:' diagnostic for a broken pipe; got: {stderr}"
    );
}

/// End-to-end pin for the `-N<unit>` warning-period cookie on a DEADLINE.
/// At day 5 (outside the 3-day window) the task must not show as
/// upcoming, even though the default 14-day window would include it.
/// At day 2 (inside the 3-day window) the same task must show.
#[test]
fn deadline_warning_cookie_overrides_default_window() {
    let tmp = tempdir().expect("tmpdir");
    fs::write(
        tmp.path().join("notes.md"),
        "### TODO [#A] Cookie task\n`DEADLINE: <2025-12-10 Wed -3d>`\n",
    )
    .expect("write fixture");

    // Day 5 — outside the cookie's 3-day window. The default 14-day
    // window would have included this task, so a non-empty `upcoming`
    // here would mean the cookie is being ignored.
    let out = bin()
        .args([
            "--dir",
            tmp.path().to_str().unwrap(),
            "--current-date",
            "2025-12-05",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "scan must succeed; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let parsed: serde_json::Value =
        serde_json::from_str(&String::from_utf8_lossy(&out.stdout)).expect("valid JSON");
    let upcoming_at_5 = parsed
        .as_array()
        .and_then(|days| days.first())
        .and_then(|d| d.get("upcoming"))
        .and_then(|u| u.as_array())
        .map(|a| a.len())
        .unwrap_or(0);
    assert_eq!(
        upcoming_at_5, 0,
        "DEADLINE with -3d must be silent 5 days out; full output: {parsed}"
    );

    // Day 8 — inside the 3-day window. Task must surface in upcoming.
    let out = bin()
        .args([
            "--dir",
            tmp.path().to_str().unwrap(),
            "--current-date",
            "2025-12-08",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(out.status.success());
    let parsed: serde_json::Value =
        serde_json::from_str(&String::from_utf8_lossy(&out.stdout)).expect("valid JSON");
    let upcoming_at_8 = parsed
        .as_array()
        .and_then(|days| days.first())
        .and_then(|d| d.get("upcoming"))
        .and_then(|u| u.as_array())
        .map(|a| a.len())
        .unwrap_or(0);
    assert_eq!(
        upcoming_at_8, 1,
        "DEADLINE with -3d must surface in upcoming 2 days out; full output: {parsed}"
    );
}

#[test]
fn verbose_saturation_warns_on_vvvv_and_beyond() {
    // `-vvvv` and longer maps to TRACE just like `-vvv` does. Silently
    // accepting it leaves a user who expected "more detail than trace" with
    // no signal that the level is already maxed out. A single warn on the
    // first overflow point is the cheapest acknowledgement that "-vvvv"
    // is the same as "-vvv".
    let out = bin()
        .args(["--dir", "examples", "--current-date", "2025-12-05", "-vvvv"])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "expected success on -vvvv; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("saturated") || stderr.contains("--verbose"),
        "expected verbose saturation message in stderr; got:\n{stderr}"
    );
}

#[test]
fn verbose_at_trace_threshold_does_not_warn() {
    // Negative control: `-vvv` is the documented trace level and must NOT
    // produce the saturation warning. Without this guard a regression that
    // moves the threshold off-by-one would slip through.
    let out = bin()
        .args(["--dir", "examples", "--current-date", "2025-12-05", "-vvv"])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "expected success on -vvv; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !stderr.contains("saturated"),
        "expected no saturation message at -vvv; got:\n{stderr}"
    );
}

#[test]
fn holidays_stdout_ends_with_newline() {
    let out = bin()
        .args(["--holidays", "2026", "--quiet"])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(
        out.stdout.last().copied(),
        Some(b'\n'),
        "--holidays JSON must end with a trailing newline; got tail: {:?}",
        String::from_utf8_lossy(&out.stdout[out.stdout.len().saturating_sub(8)..])
    );
}

#[test]
fn print_summary_aggregates_failed_paths_into_single_warn() {
    // The 2026-05-25 observability review (O5) flagged that
    // `ProcessingStats::print_summary` emitted up to 22 warn-level
    // records in a row (one summary, one header, and one per failed
    // path up to MAX_DIAGNOSTIC_ITEMS=20). This drowned out real
    // warnings on a noisy run. The aggregated form keeps everything
    // in one structured record: jq / grep can still extract the list
    // through a single field instead of stitching together multiple
    // lines.
    let dir = tempdir().unwrap();
    // Two files that pass the grep-searcher pre-filter (they contain
    // a `# TODO` keyword) but fail `std::str::from_utf8` because of an
    // explicit lone 0xFF byte. Both paths land in
    // `ProcessingStats::failed_paths` -> the previous code emitted three
    // separate warn records per path.
    for n in 0..2 {
        let path = dir.path().join(format!("bad{n}.md"));
        let mut bytes = b"# TODO test\n".to_vec();
        bytes.push(0xFF);
        bytes.extend_from_slice(b"\n");
        fs::write(&path, &bytes).unwrap();
    }

    let out = bin()
        .args([
            "--dir",
            dir.path().to_str().unwrap(),
            "--format",
            "json",
            "--current-date",
            "2025-12-05",
        ])
        .output()
        .expect("run");
    let stderr = String::from_utf8_lossy(&out.stderr);

    let summary_lines: Vec<&str> = stderr
        .lines()
        .filter(|l| l.contains("processing summary"))
        .collect();
    assert_eq!(
        summary_lines.len(),
        1,
        "exactly one 'processing summary' warn line expected; stderr was:\n{stderr}"
    );

    assert!(
        !stderr.contains("failed paths (up to first"),
        "the per-list header line must be folded into the summary; stderr:\n{stderr}"
    );

    // Each individual failed_path line in the old format had a literal
    // `failed path` event message with a `path=...` field. The aggregated
    // form uses the plural `failed_paths` field name and emits no
    // standalone records.
    let standalone_path_lines = stderr.matches("\"failed path\"").count()
        + stderr
            .lines()
            .filter(|l| l.ends_with("failed path"))
            .count();
    assert_eq!(
        standalone_path_lines, 0,
        "no per-path 'failed path' records should remain; stderr:\n{stderr}"
    );

    assert!(
        summary_lines[0].contains("bad0.md") || summary_lines[0].contains("bad1.md"),
        "the aggregated summary must surface the failed paths; stderr:\n{stderr}"
    );
}

#[test]
fn per_file_failure_reason_is_logged_at_debug() {
    // m3 (2026-05-25 code / error-handling review): the three per-file
    // failure branches in scan_files (read / search / utf8) used to
    // discard the underlying io::Error / Utf8Error, recording only the
    // path. The error cause is now logged at debug level so `-vv`
    // explains *why* a path failed, while the default warn stream stays
    // aggregated (one summary record, per O5). This pins both halves:
    // the cause is present at -vv and absent at default verbosity.
    let dir = tempdir().unwrap();
    let path = dir.path().join("bad.md");
    // Passes the keyword pre-filter (`# TODO`) but fails str::from_utf8
    // on the lone 0xFF byte, taking the utf8 branch.
    let mut bytes = b"# TODO test\n".to_vec();
    bytes.push(0xFF);
    bytes.extend_from_slice(b"\n");
    fs::write(&path, &bytes).unwrap();

    // At -vv the per-file reason is visible.
    let verbose = bin()
        .args([
            "--dir",
            dir.path().to_str().unwrap(),
            "-vv",
            "--current-date",
            "2025-12-05",
        ])
        .output()
        .expect("run");
    let verbose_stderr = String::from_utf8_lossy(&verbose.stderr);
    assert!(
        verbose_stderr.contains("file is not valid UTF-8; skipping"),
        "at -vv the per-file failure reason must be logged; stderr was:\n{verbose_stderr}"
    );
    assert!(
        verbose_stderr.contains("bad.md"),
        "the per-file debug record must carry the path; stderr was:\n{verbose_stderr}"
    );

    // At default verbosity the per-file debug record is suppressed; the
    // path still appears once, in the aggregated summary warn.
    let quiet = bin()
        .args([
            "--dir",
            dir.path().to_str().unwrap(),
            "--current-date",
            "2025-12-05",
        ])
        .output()
        .expect("run");
    let quiet_stderr = String::from_utf8_lossy(&quiet.stderr);
    assert!(
        !quiet_stderr.contains("file is not valid UTF-8; skipping"),
        "at default verbosity the per-file debug record must be silent; stderr was:\n{quiet_stderr}"
    );
}

#[test]
fn utf8_bom_prefix_does_not_swallow_first_heading() {
    // Files saved by editors such as Windows Notepad or VS Code with the
    // "UTF-8 with BOM" option ship a leading EF BB BF byte sequence
    // (U+FEFF). CommonMark does not strip the BOM, so without explicit
    // handling the first heading line becomes "\u{FEFF}# TODO ..." and
    // the heading downgrades to a paragraph -- silently losing the task.
    // The encoding review (point 1) called this out as a real-world
    // regression for vault files originating on Windows.
    let dir = tempdir().unwrap();
    let path = dir.path().join("bom.md");
    let body = "# TODO BOM-prefixed heading\n\n`SCHEDULED: <2025-12-05 Fri>`\n";
    let mut content = Vec::with_capacity(3 + body.len());
    content.extend_from_slice(b"\xEF\xBB\xBF");
    content.extend_from_slice(body.as_bytes());
    fs::write(&path, &content).unwrap();

    let out = bin()
        .args([
            "--dir",
            dir.path().to_str().unwrap(),
            "--format",
            "json",
            "--current-date",
            "2025-12-05",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("utf-8 stdout");
    assert!(
        stdout.contains("BOM-prefixed heading"),
        "BOM-prefixed first heading must still be extracted; stdout: {stdout}"
    );
    assert!(
        !stdout.contains('\u{FEFF}'),
        "BOM must not leak into the output text; stdout: {stdout}"
    );
    assert!(
        stdout.contains("\"task_type\""),
        "task_type must survive BOM strip; stdout: {stdout}"
    );
    assert!(
        stdout.contains("\"TODO\""),
        "TODO marker must be parsed past the BOM; stdout: {stdout}"
    );
}

#[test]
fn rust_log_env_overrides_verbose_flag() {
    // ADR-0016 pins the precedence: `RUST_LOG` always wins over
    // `--verbose` / `--quiet`. With `-vv` the binary emits
    // `tracing::info!("scan finished")` on stderr; with
    // `RUST_LOG=error` the same level filter is muted.
    let baseline = bin()
        .args([
            "--dir",
            "examples",
            "--format",
            "json",
            "--current-date",
            "2025-12-05",
            "-vv",
        ])
        .env_remove("RUST_LOG")
        .output()
        .expect("baseline run");
    assert!(
        baseline.status.success(),
        "baseline stderr: {}",
        String::from_utf8_lossy(&baseline.stderr)
    );
    let baseline_err = String::from_utf8_lossy(&baseline.stderr);
    assert!(
        baseline_err.contains("scan finished"),
        "baseline -vv must emit info-level 'scan finished'; stderr: {baseline_err}"
    );

    let muted = bin()
        .args([
            "--dir",
            "examples",
            "--format",
            "json",
            "--current-date",
            "2025-12-05",
            "-vv",
        ])
        .env("RUST_LOG", "error")
        .output()
        .expect("muted run");
    assert!(
        muted.status.success(),
        "muted stderr: {}",
        String::from_utf8_lossy(&muted.stderr)
    );
    let muted_err = String::from_utf8_lossy(&muted.stderr);
    assert!(
        !muted_err.contains("scan finished"),
        "RUST_LOG=error must mute the -vv info line; stderr: {muted_err}"
    );
}

// Linux-only: the test must *create* a file whose name is not valid UTF-8,
// which only Linux allows (filenames are arbitrary non-NUL bytes). macOS
// APFS/HFS+ reject a non-Unicode filename at `fs::write`, so the scenario
// cannot even be set up there — exactly the platform analysis ADR-0019
// records (the lossy branch is unreachable on macOS). Windows is already
// excluded by `unix`. Gating macOS out keeps the macOS CI matrix green.
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn non_utf8_path_is_processed_and_warned() {
    // ADR-0019: a file whose name is not valid UTF-8 (legal on Linux, where
    // filenames are arbitrary non-NUL byte sequences) is still read and its
    // tasks emitted — the I/O goes through the OsStr path, not the lossy
    // string. The `file` field is rendered with U+FFFD replacement chars, so
    // the tool warns once per run that the path will not round-trip. The file
    // content itself is valid UTF-8; only the name is not.
    use std::ffi::OsString;
    use std::os::unix::ffi::OsStringExt;

    let dir = tempdir().unwrap();
    // `bad\xFFname.md`: 0xFF is a lone invalid UTF-8 byte; the `.md` suffix is
    // intact so the default `*.md` glob still selects the file.
    let fname = OsString::from_vec(b"bad\xFFname.md".to_vec());
    let path = dir.path().join(&fname);
    fs::write(
        &path,
        "### TODO non utf8 path task\n`SCHEDULED: <2024-12-09 Mon>`\n",
    )
    .unwrap();

    let out = bin()
        .args([
            "--dir",
            dir.path().to_str().unwrap(),
            "--current-date",
            "2024-12-09",
        ])
        .output()
        .expect("run over a non-UTF-8 named file");

    assert!(
        out.status.success(),
        "scan must succeed; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("non utf8 path task"),
        "the task from the non-UTF-8 named file must still be emitted; stdout: {stdout}"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("not valid UTF-8"),
        "a non-UTF-8 path must trigger a warning; stderr: {stderr}"
    );
}

#[test]
fn tasks_json_includes_properties_from_org_properties_block() {
    let dir = tempdir().unwrap();
    let content = "### TODO Ship release\n`SCHEDULED: <2026-06-01 Mon 10:00>`\n```org-properties\nGCAL_EVENT_ID: abc123/primary\nID: 11111111-2222-3333-4444-555555555555\n```\n\nBody.\n";
    fs::write(dir.path().join("t.md"), content).unwrap();

    let out = bin()
        .args([
            "--dir",
            dir.path().to_str().unwrap(),
            "--tasks",
            "--format",
            "json",
        ])
        .assert()
        .success();

    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let task = &parsed.as_array().expect("array of tasks")[0];
    assert_eq!(
        task["properties"]["GCAL_EVENT_ID"], "abc123/primary",
        "properties.GCAL_EVENT_ID must be in the JSON: {stdout}"
    );
    assert_eq!(
        task["properties"]["ID"], "11111111-2222-3333-4444-555555555555",
        "properties.ID must be in the JSON: {stdout}"
    );
}

#[test]
fn tasks_json_omits_properties_when_absent() {
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("t.md"),
        "### TODO No props\n`SCHEDULED: <2026-06-01 Mon>`\n",
    )
    .unwrap();

    let out = bin()
        .args([
            "--dir",
            dir.path().to_str().unwrap(),
            "--tasks",
            "--format",
            "json",
        ])
        .assert()
        .success();

    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    assert!(
        !stdout.contains("properties"),
        "absent properties must not appear in JSON: {stdout}"
    );
}

#[test]
fn tasks_json_emits_fields_required_by_calendar_sync() {
    // Wire-contract guard for the Google Calendar sync consumer
    // (markdown-org-vscode). These fields must stay present in
    // `--tasks --format json`; dropping any of them is a breaking change
    // under ADR-0015. See the coordinator spec
    // 2026-05-27-google-calendar-sync-design.md.
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("t.md"),
        "### TODO Sync me\n`SCHEDULED: <2026-06-01 Mon 10:00-11:00>`\n```org-properties\nID: 11111111-2222-3333-4444-555555555555\n```\n\nBody.\n",
    )
    .unwrap();

    let out = bin()
        .args([
            "--dir",
            dir.path().to_str().unwrap(),
            "--tasks",
            "--format",
            "json",
        ])
        .assert()
        .success();

    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let task = &parsed.as_array().expect("array of tasks")[0];

    assert_eq!(
        task["task_type"], "TODO",
        "task_type must be emitted: {stdout}"
    );
    assert_eq!(
        task["timestamp_active"], true,
        "timestamp_active must be emitted for active SCHEDULED: {stdout}"
    );
    assert_eq!(
        task["timestamp_date"], "2026-06-01",
        "timestamp_date must be emitted: {stdout}"
    );
    assert_eq!(
        task["timestamp_time"], "10:00",
        "timestamp_time must be emitted for a timed task: {stdout}"
    );
    assert_eq!(
        task["timestamp_end_time"], "11:00",
        "timestamp_end_time must be emitted for a time range: {stdout}"
    );
    assert_eq!(
        task["properties"]["ID"], "11111111-2222-3333-4444-555555555555",
        "properties.ID must be emitted (sync matching key): {stdout}"
    );
}

/// Markdown fixture with one TODO and one DONE task, each carrying an active
/// SCHEDULED timestamp and an `org-properties` ID. Shared by the two
/// `--tasks-include-done` tests below.
const TODO_AND_DONE_FIXTURE: &str = "\
### TODO Keep me
`SCHEDULED: <2026-06-01 Mon>`
```org-properties
ID: aaaaaaaa-1111-2222-3333-444444444444
```

### DONE Finished
`SCHEDULED: <2026-06-02 Tue>`
```org-properties
ID: bbbbbbbb-5555-6666-7777-888888888888
```
";

#[test]
fn tasks_flat_list_excludes_done_by_default() {
    // The flat `--tasks` list is TODO-only by default — the documented
    // contract pinned by the wire-contract snapshot tests. A DONE task, even
    // with an active SCHEDULED and an ID, must not appear unless opted in.
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("t.md"), TODO_AND_DONE_FIXTURE).unwrap();

    let out = bin()
        .args([
            "--dir",
            dir.path().to_str().unwrap(),
            "--tasks",
            "--format",
            "json",
        ])
        .assert()
        .success();

    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let arr = parsed.as_array().expect("array of tasks");
    let types: Vec<&str> = arr.iter().filter_map(|t| t["task_type"].as_str()).collect();

    assert!(
        types.contains(&"TODO"),
        "TODO task must be present: {stdout}"
    );
    assert!(
        !types.contains(&"DONE"),
        "DONE task must be absent from --tasks by default: {stdout}"
    );
}

#[test]
fn tasks_include_done_surfaces_done_with_properties() {
    // `--tasks --tasks-include-done` additionally emits DONE tasks, with
    // their `properties` intact, so a consumer (e.g. the Google Calendar sync
    // in markdown-org-vscode) can delete the event for a completed task keyed
    // by its ID. The TODO task stays present too.
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("t.md"), TODO_AND_DONE_FIXTURE).unwrap();

    let out = bin()
        .args([
            "--dir",
            dir.path().to_str().unwrap(),
            "--tasks",
            "--tasks-include-done",
            "--format",
            "json",
        ])
        .assert()
        .success();

    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let arr = parsed.as_array().expect("array of tasks");

    let done = arr
        .iter()
        .find(|t| t["task_type"] == "DONE")
        .unwrap_or_else(|| panic!("DONE task must be present with the flag: {stdout}"));
    assert_eq!(
        done["properties"]["ID"], "bbbbbbbb-5555-6666-7777-888888888888",
        "DONE task must carry its org-properties: {stdout}"
    );
    assert!(
        arr.iter().any(|t| t["task_type"] == "TODO"),
        "TODO task must still be present alongside DONE: {stdout}"
    );
}

#[test]
fn tasks_include_cancelled_surfaces_cancelled() {
    // `--tasks --tasks-include-cancelled` additionally emits CANCELLED tasks so
    // a consumer (Google Calendar sync) can delete the event for a cancelled
    // task. The TODO task stays present; DONE stays absent without its own flag.
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("t.md"),
        "### TODO Keep me\n\n### CANCELLED Drop me\n\n### DONE Finished\n",
    )
    .unwrap();

    let out = bin()
        .args([
            "--dir",
            dir.path().to_str().unwrap(),
            "--tasks",
            "--tasks-include-cancelled",
            "--format",
            "json",
        ])
        .assert()
        .success();

    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let arr = parsed.as_array().expect("array of tasks");

    assert!(
        arr.iter().any(|t| t["task_type"] == "CANCELLED"),
        "CANCELLED task must be present with the flag: {stdout}"
    );
    assert!(
        arr.iter().any(|t| t["task_type"] == "TODO"),
        "TODO task must still be present: {stdout}"
    );
    assert!(
        !arr.iter().any(|t| t["task_type"] == "DONE"),
        "DONE must stay absent without --tasks-include-done: {stdout}"
    );
}

#[test]
fn tasks_include_done_and_cancelled_surfaces_both() {
    // Both opt-in flags together surface TODO + DONE + CANCELLED in the flat
    // list — the combination the README documents for a consumer that needs to
    // act on every closed task (e.g. delete its calendar event), whether it was
    // completed or cancelled.
    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("t.md"),
        "### TODO Keep me\n\n### CANCELLED Drop me\n\n### DONE Finished\n",
    )
    .unwrap();

    let out = bin()
        .args([
            "--dir",
            dir.path().to_str().unwrap(),
            "--tasks",
            "--tasks-include-done",
            "--tasks-include-cancelled",
            "--format",
            "json",
        ])
        .assert()
        .success();

    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let arr = parsed.as_array().expect("array of tasks");

    assert!(
        arr.iter().any(|t| t["task_type"] == "TODO"),
        "TODO must be present: {stdout}"
    );
    assert!(
        arr.iter().any(|t| t["task_type"] == "DONE"),
        "DONE must be present with --tasks-include-done: {stdout}"
    );
    assert!(
        arr.iter().any(|t| t["task_type"] == "CANCELLED"),
        "CANCELLED must be present with --tasks-include-cancelled: {stdout}"
    );
}

// Several `--dir` flags in one run. Notes kept in more than one place are one
// agenda, and the JSON says which root each task came from — the same relative
// path can occur in two of them and mean two different files.

/// A directory holding one note, for the multi-root tests below.
fn vault_with(name: &str, body: &str) -> tempfile::TempDir {
    let dir = tempdir().expect("tmp");
    fs::write(dir.path().join(name), body).expect("write note");
    dir
}

#[test]
fn several_dirs_are_scanned_into_one_task_list() {
    let work = vault_with("notes.md", "# TODO Renew the certificate\n");
    let home = vault_with("notes.md", "# TODO Book the tickets\n");

    let out = bin()
        .args([
            "--dir",
            work.path().to_str().unwrap(),
            "--dir",
            home.path().to_str().unwrap(),
            "--tasks",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let arr = parsed.as_array().expect("array of tasks");
    let headings: Vec<&str> = arr
        .iter()
        .filter_map(|t| t.get("heading").and_then(|h| h.as_str()))
        .collect();
    assert_eq!(
        headings,
        vec!["Renew the certificate", "Book the tickets"],
        "both roots must be in, in the order they were given: {stdout}"
    );
}

#[test]
fn several_dirs_name_the_root_of_every_task() {
    let work = vault_with("notes.md", "# TODO Renew the certificate\n");
    let home = vault_with("notes.md", "# TODO Book the tickets\n");

    let out = bin()
        .args([
            "--dir",
            work.path().to_str().unwrap(),
            "--dir",
            home.path().to_str().unwrap(),
            "--tasks",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");

    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let arr = parsed.as_array().expect("array of tasks");
    let roots: Vec<&str> = arr
        .iter()
        .filter_map(|t| t.get("root").and_then(|r| r.as_str()))
        .collect();
    assert_eq!(roots.len(), 2, "every task carries its root: {stdout}");
    assert_ne!(roots[0], roots[1], "the roots differ: {stdout}");
    assert!(
        arr.iter().all(|t| t["file"].as_str() == Some("notes.md")),
        "the path stays relative to its own root: {stdout}"
    );
}

#[test]
fn one_dir_emits_no_root_field() {
    // The single-directory output is what every existing consumer reads, and
    // it must not grow a field: the caller named the root itself.
    let vault = vault_with("notes.md", "# TODO Renew the certificate\n");

    let out = bin()
        .args([
            "--dir",
            vault.path().to_str().unwrap(),
            "--tasks",
            "--format",
            "json",
            "--quiet",
        ])
        .output()
        .expect("run");

    let stdout = String::from_utf8_lossy(&out.stdout);
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let arr = parsed.as_array().expect("array of tasks");
    assert!(
        arr.iter().all(|t| t.get("root").is_none()),
        "a single root is not named on the tasks: {stdout}"
    );
}

#[test]
fn a_missing_dir_among_several_fails_the_run() {
    let vault = vault_with("notes.md", "# TODO Renew the certificate\n");

    bin()
        .args([
            "--dir",
            vault.path().to_str().unwrap(),
            "--dir",
            "/this/path/should/never/exist_xyz",
            "--tasks",
            "--format",
            "json",
        ])
        .assert()
        .failure()
        .stderr(contains("directory does not exist"));
}