markdown-org-extract 0.5.0

CLI utility for extracting tasks from markdown files with Emacs Org-mode support
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
//! 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_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 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_includes_per_file_span_field() {
    // -vv enables debug-level events. The parser emits a `parsed file` event
    // inside a `file` span carrying `path = ...`. The tracing fmt-layer prints
    // span fields in the message, so stderr must contain a `path=` segment for
    // at least one processed file. Locks the span wrapping in main.rs against
    // accidental removal.
    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("path="),
        "expected `path=` from the file span, got 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()
}

#[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 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}"
    );
}

// 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)..])
    );
}