mds-cli 0.4.2

MDS (Markdown Script) compiler — command-line interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
//! Integration tests for `mds fmt` (issue #60).
//!
//! Coverage maps to AC-CF-1..8 from the execution plan:
//! - AC-CF-1: file.mds rewrites in place only when content changes, unchanged
//!   keeps mtime, prints Formatted/Unchanged to stderr
//! - AC-CF-2: `-` reads stdin -> stdout, creates no file
//! - AC-CF-3: `.` formats every .mds recursively INCLUDING _partials,
//!   continue-on-error, summary `N formatted, M unchanged, K failed`, exit 1
//!   iff any failed
//! - AC-CF-4: --check exits 0 when clean / 1 when any would change or fails,
//!   NEVER writes
//! - AC-CF-5: --diff prints unified diff to stdout (colorized only on TTY),
//!   writes nothing, exit 0 unless read/parse error -> 1
//! - AC-CF-6: --check --diff prints diffs AND exits non-zero when changes exist
//! - AC-CF-7: no-arg auto-detects single .mds in cwd, errors on zero/many
//! - AC-CF-8: -q/--quiet suppresses status but never errors

mod common;
use common::{fixture, mds_bin};

use std::fs;
use std::path::Path;
use std::time::Duration;

fn read_fixture(name: &str) -> String {
    fs::read_to_string(fixture(name)).expect("read fixture")
}

/// Run `mds fmt <path> <extra_args>`, capturing stdout/stderr separately.
///
/// `mds fmt` dispatches on the filesystem type of `path` (file, dir, or `-`
/// for stdin — see the dedicated `fmt_stdin` helper below), so one helper
/// covers both single-file and directory-mode invocations.
fn fmt_path(path: &Path, extra_args: &[&str]) -> std::process::Output {
    mds_bin()
        .arg("fmt")
        .arg(path)
        .args(extra_args)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap()
}

// ── AC-CF-1: single-file in-place rewrite, mtime, status lines ──────────────

#[test]
fn inplace_rewrites_only_when_changed() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("unformatted.mds");
    fs::write(&target, read_fixture("fmt_unformatted.mds")).unwrap();
    let original = fs::read_to_string(&target).unwrap();

    let output = fmt_path(&target, &[]);
    assert!(
        output.status.success(),
        "fmt should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let after = fs::read_to_string(&target).unwrap();
    assert_ne!(after, original, "content should have changed");
    assert!(!after.contains('\r'), "CRLF should be gone: {after:?}");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("Formatted"),
        "expected a Formatted status line, got: {stderr}"
    );
}

#[test]
fn inplace_unchanged_file_preserves_mtime_and_reports_unchanged() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("clean.mds");
    fs::write(&target, read_fixture("fmt_formatted.mds")).unwrap();

    let before_bytes = fs::read(&target).unwrap();
    let before_mtime = fs::metadata(&target).unwrap().modified().unwrap();
    // Ensure the filesystem clock would visibly move if the file were rewritten.
    std::thread::sleep(Duration::from_millis(1100));

    let output = fmt_path(&target, &[]);
    assert!(
        output.status.success(),
        "fmt should succeed on an already-clean file"
    );

    // Assert both that the mtime is unchanged AND that the bytes are identical:
    // the mtime check alone is not enough to distinguish "same content written"
    // from "write skipped", because some filesystems may round mtime.
    let after_bytes = fs::read(&target).unwrap();
    assert_eq!(
        before_bytes, after_bytes,
        "file bytes must be identical for an already-clean file (no rewrite should occur)"
    );

    let after_mtime = fs::metadata(&target).unwrap().modified().unwrap();
    assert_eq!(
        before_mtime, after_mtime,
        "mtime must not change for an unchanged file"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("Unchanged"),
        "expected an Unchanged status line, got: {stderr}"
    );
}

#[test]
fn format_then_check_is_idempotent() {
    // T2-idem: format a file, then --check it -- must report clean (exit 0).
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("idem.mds");
    fs::write(&target, read_fixture("fmt_unformatted.mds")).unwrap();

    let first = fmt_path(&target, &[]);
    assert!(first.status.success());

    let check = fmt_path(&target, &["--check"]);
    assert!(
        check.status.success(),
        "second pass under --check should report clean; stderr: {}",
        String::from_utf8_lossy(&check.stderr)
    );
}

// ── T1: safety-gate path coverage (Syntax propagation + structural fallback) ──
//
// FormatterInvariant end-to-end is deliberately untested here: triggering it
// requires a formatter bug (the gate fires only when the formatter itself
// diverges from the original output). That cannot be induced without a test
// hook inside formatter.rs, which falls outside the scope of test-only changes.
// The white-box unit tests for `structural_equivalent` inside formatter.rs's
// own `#[cfg(test)]` module cover both branches of that function directly.
//
// What we DO test here:
//   - Syntax propagation: `unclosed_directive_block_exits_one_with_syntax_not_formatter_invariant`
//     (already present above) proves the gate surfaces real syntax errors and
//     leaves the file untouched.
//   - structural_equivalent fallback: the test below proves that a source file
//     referencing an undefined runtime variable (which doesn't compile standalone)
//     is still formatted via the token-comparison fallback, not rejected.

#[test]
fn structural_fallback_formats_file_with_undefined_var() {
    // A source with an undefined runtime variable does not compile standalone,
    // so the safety gate cannot do a real recompile-and-diff. It must fall
    // back to the structural_equivalent token comparison and succeed, because
    // real template files are often written for runtime vars supplied at render
    // time — refusing to format them would make `mds fmt` useless on templates.
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("template.mds");
    let src = "Hello {{undefined_runtime_var}}!\n\n\n\nBye.\n";
    fs::write(&target, src).unwrap();

    let output = fmt_path(&target, &[]);
    assert!(
        output.status.success(),
        "fmt must succeed on a file with undefined runtime var (structural fallback); \
         stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let after = fs::read_to_string(&target).unwrap();
    // Interior-verbatim (#150/#151): blank-line runs pass through verbatim
    // even via the structural fallback; only trailing edge is normalised (R2).
    assert_eq!(
        after, "Hello {{undefined_runtime_var}}!\n\n\n\nBye.\n",
        "interior blank-line runs must be preserved verbatim (interior-verbatim contract)"
    );
}

// ── AC-CF-2: stdin -> stdout, no file created ────────────────────────────────

fn fmt_stdin(input: &str, extra_args: &[&str]) -> std::process::Output {
    use std::io::Write;
    let mut child = mds_bin()
        .arg("fmt")
        .arg("-")
        .args(extra_args)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(input.as_bytes())
        .unwrap();
    child.wait_with_output().unwrap()
}

#[test]
fn stdin_reads_and_writes_stdout_creates_no_file() {
    let dir = tempfile::tempdir().unwrap();
    let before: Vec<_> = fs::read_dir(dir.path()).unwrap().collect();
    assert!(before.is_empty());

    let input = read_fixture("fmt_unformatted.mds");
    let output = mds_bin()
        .current_dir(dir.path())
        .arg("fmt")
        .arg("-")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .and_then(|mut child| {
            use std::io::Write;
            child.stdin.take().unwrap().write_all(input.as_bytes())?;
            child.wait_with_output()
        })
        .unwrap();

    assert!(output.status.success());
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        !stdout.contains('\r'),
        "stdout should be reformatted: {stdout:?}"
    );

    let after: Vec<_> = fs::read_dir(dir.path()).unwrap().collect();
    assert!(after.is_empty(), "fmt - must not create any file in cwd");
}

#[test]
fn stdin_filter_mode_is_idempotent() {
    // T2-filter-idem: pipe formatted output back through `fmt -` -> identical.
    let input = read_fixture("fmt_unformatted.mds");
    let first = fmt_stdin(&input, &[]);
    assert!(first.status.success());
    let once = String::from_utf8(first.stdout).unwrap();

    let second = fmt_stdin(&once, &[]);
    assert!(second.status.success());
    let twice = String::from_utf8(second.stdout).unwrap();

    assert_eq!(once, twice, "stdin filter mode must be idempotent");
}

#[test]
fn stdin_into_closed_pipe_does_not_panic() {
    // Piping into `true` closes the read end almost immediately; writing the
    // formatted result to stdout must handle a broken pipe gracefully.
    use std::io::Write;
    let mut child = mds_bin()
        .arg("fmt")
        .arg("-")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .unwrap();

    // Drop stdout immediately to force a broken pipe on write.
    drop(child.stdout.take());

    let big_input = read_fixture("fmt_unformatted.mds").repeat(1000);
    // Ignore write errors -- the point is the CHILD process must not panic.
    let _ = child.stdin.take().unwrap().write_all(big_input.as_bytes());

    let output = child.wait_with_output().unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("panicked"),
        "must not panic on broken pipe, got stderr: {stderr}"
    );
}

// ── AC-CF-3: directory mode, partials included, continue-on-error, summary ──

#[test]
fn dir_recurse_formats_every_mds_including_partials() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(
        dir.path().join("main.mds"),
        read_fixture("fmt_unformatted.mds"),
    )
    .unwrap();
    fs::write(
        dir.path().join("_partial.mds"),
        read_fixture("_fmt_partial.mds"),
    )
    .unwrap();

    let output = fmt_path(dir.path(), &[]);
    assert!(
        output.status.success(),
        "dir fmt should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let main_after = fs::read_to_string(dir.path().join("main.mds")).unwrap();
    assert!(!main_after.contains('\r'), "main.mds should be reformatted");

    // Partials ARE formatted (deliberate divergence from build/check). The
    // partial's directive lines (@define/@end/@export) and the blank-line run
    // between @end and @export are OUTSIDE the @define body and must be
    // reformatted; the "Hello {x}!\r\n" line INSIDE the @define body
    // deliberately keeps its \r (raw-content exemption -- see formatter.rs's
    // module docs and the `message_body_carriage_return_is_preserved`-style
    // tests in mds-core/tests/fmt.rs), so this asserts the directive-level
    // change rather than a blanket "no \\r anywhere".
    let partial_after = fs::read_to_string(dir.path().join("_partial.mds")).unwrap();
    assert_ne!(
        partial_after,
        read_fixture("_fmt_partial.mds"),
        "_partial.mds should ALSO be reformatted"
    );
    assert!(
        partial_after.contains("@define greet(x):\n"),
        "directive trailing ws/\\r should be stripped even in a partial, got: {partial_after:?}"
    );
    assert!(
        partial_after.contains("@end\n\n\n\n@export"),
        "blank-line run between @end and @export must be preserved verbatim (interior-verbatim), got: {partial_after:?}"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("formatted") && stderr.contains("unchanged") && stderr.contains("failed"),
        "expected a summary with formatted/unchanged/failed counts, got: {stderr}"
    );
}

#[test]
fn dir_continue_on_error_summary_nonzero_exit() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("good.mds"), "Hello, world!\n").unwrap();
    fs::write(dir.path().join("bad.mds"), "```\nunclosed fence\n").unwrap();

    let output = fmt_path(dir.path(), &[]);
    assert!(
        !output.status.success(),
        "dir fmt with a failing file must exit non-zero"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("1 failed") || stderr.contains("failed"),
        "summary must mention the failure, got: {stderr}"
    );
}

#[test]
fn dir_already_formatted_tree_reports_all_unchanged_exit_zero() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(
        dir.path().join("clean.mds"),
        read_fixture("fmt_formatted.mds"),
    )
    .unwrap();

    let output = fmt_path(dir.path(), &[]);
    assert!(output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("1 unchanged"),
        "expected '1 unchanged' in summary, got: {stderr}"
    );
}

// ── AC-CF-9 (EC-9): partial + parent that @includes it stay compile-equivalent ─

#[test]
fn parent_that_includes_partial_compiles_unchanged_after_formatting_both() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(
        dir.path().join("_fmt_partial.mds"),
        read_fixture("_fmt_partial.mds"),
    )
    .unwrap();
    let parent = dir.path().join("parent.mds");
    fs::write(&parent, read_fixture("fmt_parent_includes_partial.mds")).unwrap();

    let before = mds_bin()
        .arg("build")
        .arg(&parent)
        .arg("-o")
        .arg("-")
        .output()
        .unwrap();
    assert!(before.status.success(), "pre-format build should succeed");

    let output = fmt_path(dir.path(), &[]);
    assert!(
        output.status.success(),
        "formatting the dir should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let after = mds_bin()
        .arg("build")
        .arg(&parent)
        .arg("-o")
        .arg("-")
        .output()
        .unwrap();
    assert!(after.status.success(), "post-format build should succeed");
    assert_eq!(
        before.stdout, after.stdout,
        "compiled output must be unchanged after formatting the partial + parent"
    );
}

// ── AC-CF-4: --check exits 0 clean / 1 dirty, never writes ──────────────────

#[test]
fn check_clean_file_exits_zero_no_write() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("clean.mds");
    fs::write(&target, read_fixture("fmt_formatted.mds")).unwrap();
    let before = fs::read_to_string(&target).unwrap();
    let before_mtime = fs::metadata(&target).unwrap().modified().unwrap();

    let output = fmt_path(&target, &["--check"]);
    assert!(output.status.success(), "check on clean file should exit 0");

    assert_eq!(
        fs::read_to_string(&target).unwrap(),
        before,
        "must not write"
    );
    assert_eq!(
        fs::metadata(&target).unwrap().modified().unwrap(),
        before_mtime
    );
}

#[test]
fn check_dirty_file_exits_nonzero_no_write() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("dirty.mds");
    fs::write(&target, read_fixture("fmt_unformatted.mds")).unwrap();
    let before = fs::read_to_string(&target).unwrap();

    let output = fmt_path(&target, &["--check"]);
    assert!(
        !output.status.success(),
        "check on a file that would change must exit non-zero"
    );
    assert_eq!(
        fs::read_to_string(&target).unwrap(),
        before,
        "--check must never write"
    );
}

#[test]
fn dir_check_reports_would_reformat_and_exits_nonzero() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(
        dir.path().join("dirty.mds"),
        read_fixture("fmt_unformatted.mds"),
    )
    .unwrap();

    let output = fmt_path(dir.path(), &["--check"]);
    assert!(
        !output.status.success(),
        "dir --check with dirty files must exit non-zero"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("would reformat"),
        "expected 'would reformat' summary wording under --check, got: {stderr}"
    );

    // No file should have been touched.
    let content = fs::read_to_string(dir.path().join("dirty.mds")).unwrap();
    assert!(
        content.contains('\r'),
        "--check must never write, CRLF should survive"
    );
}

// ── AC-CF-5: --diff prints unified diff, writes nothing ─────────────────────

#[test]
fn diff_prints_unified_diff_to_stdout_writes_nothing() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("dirty.mds");
    fs::write(&target, read_fixture("fmt_unformatted.mds")).unwrap();
    let before = fs::read_to_string(&target).unwrap();

    let output = fmt_path(&target, &["--diff"]);
    assert!(
        output.status.success(),
        "--diff alone should exit 0 even when changes exist"
    );

    let stdout = String::from_utf8(output.stdout).unwrap();
    // `---`/`+++` are the unified diff file headers; `@@` is the hunk header.
    // Checking `@@` is more discriminating than `---` alone, which could be
    // satisfied by frontmatter content that starts with `---`.
    assert!(
        stdout.contains("---"),
        "expected unified diff --- header, got: {stdout:?}"
    );
    assert!(
        stdout.contains("+++"),
        "expected unified diff +++ header, got: {stdout:?}"
    );
    assert!(
        stdout.contains("@@"),
        "expected unified diff @@ hunk header, got: {stdout:?}"
    );
    assert!(
        stdout.lines().any(|l| l.starts_with('-')) || stdout.lines().any(|l| l.starts_with('+')),
        "expected +/- diff lines, got: {stdout:?}"
    );

    assert_eq!(
        fs::read_to_string(&target).unwrap(),
        before,
        "--diff must never write"
    );
}

#[test]
fn diff_on_clean_file_prints_nothing_and_exits_zero() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("clean.mds");
    fs::write(&target, read_fixture("fmt_formatted.mds")).unwrap();

    let output = fmt_path(&target, &["--diff"]);
    assert!(output.status.success());
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        stdout.trim().is_empty(),
        "no diff expected for a clean file, got: {stdout:?}"
    );
}

#[test]
fn diff_on_malformed_file_exits_nonzero() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("bad.mds");
    fs::write(&target, read_fixture("fmt_malformed.mds")).unwrap();

    let output = fmt_path(&target, &["--diff"]);
    assert!(
        !output.status.success(),
        "--diff on unparseable input must exit non-zero"
    );
}

// ── AC-CF-6: --check --diff combined ─────────────────────────────────────────

#[test]
fn check_and_diff_combined_prints_diff_and_exits_nonzero() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("dirty.mds");
    fs::write(&target, read_fixture("fmt_unformatted.mds")).unwrap();

    let output = fmt_path(&target, &["--check", "--diff"]);
    assert!(
        !output.status.success(),
        "--check --diff must exit non-zero when changes exist"
    );
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        stdout.contains("---") && stdout.contains("+++"),
        "expected a diff, got: {stdout:?}"
    );
}

// ── AC-CF-7: no-arg auto-detect ──────────────────────────────────────────────

#[test]
fn autodetect_single_mds_file_in_cwd() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(
        dir.path().join("only.mds"),
        read_fixture("fmt_unformatted.mds"),
    )
    .unwrap();

    let output = mds_bin()
        .current_dir(dir.path())
        .arg("fmt")
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "auto-detect should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let content = fs::read_to_string(dir.path().join("only.mds")).unwrap();
    assert!(
        !content.contains('\r'),
        "auto-detected file should be formatted"
    );
}

#[test]
fn autodetect_errors_on_zero_files() {
    let dir = tempfile::tempdir().unwrap();
    let output = mds_bin()
        .current_dir(dir.path())
        .arg("fmt")
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(
        !output.status.success(),
        "auto-detect with zero .mds files must fail"
    );
}

#[test]
fn autodetect_errors_on_multiple_files() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("a.mds"), "Hello!\n").unwrap();
    fs::write(dir.path().join("b.mds"), "Hello!\n").unwrap();
    let output = mds_bin()
        .current_dir(dir.path())
        .arg("fmt")
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(
        !output.status.success(),
        "auto-detect with multiple .mds files must fail"
    );
}

// ── AC-CF-8: --quiet suppresses status but never errors ─────────────────────

#[test]
fn quiet_suppresses_status_line() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("dirty.mds");
    fs::write(&target, read_fixture("fmt_unformatted.mds")).unwrap();

    let output = mds_bin()
        .arg("--quiet")
        .arg("fmt")
        .arg(&target)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.trim().is_empty(),
        "quiet should suppress status, got: {stderr}"
    );
}

#[test]
fn quiet_does_not_suppress_errors() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("bad.mds");
    fs::write(&target, read_fixture("fmt_malformed.mds")).unwrap();

    let output = mds_bin()
        .arg("--quiet")
        .arg("fmt")
        .arg(&target)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(
        !output.status.success(),
        "malformed input must still fail under --quiet"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.trim().is_empty(),
        "errors must still be printed under --quiet"
    );
}

// ── Malformed input / missing / not-.mds / symlink / oversized / bad-utf8 ───

#[test]
fn malformed_single_file_exits_one_with_diagnostic() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("bad.mds");
    fs::write(&target, read_fixture("fmt_malformed.mds")).unwrap();

    let output = fmt_path(&target, &[]);
    assert_eq!(
        output.status.code(),
        Some(1),
        "syntax error should map to exit 1"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("syntax") || stderr.contains("fence"),
        "expected a diagnostic mentioning the syntax problem, got: {stderr}"
    );
    // Must not have written a garbled file.
    let content = fs::read_to_string(&target).unwrap();
    assert_eq!(
        content,
        read_fixture("fmt_malformed.mds"),
        "malformed file must be untouched"
    );
}

#[test]
fn unclosed_directive_block_exits_one_with_syntax_not_formatter_invariant() {
    // An unclosed `@message` (parse-level malformation, unlike the unclosed
    // code fence in fmt_malformed.mds which fails in the lexer) must be
    // rejected with the real syntax error and leave the file untouched —
    // not silently "formatted" nor reported as a formatter bug.
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("unclosed.mds");
    let src = "@message user:\nHi there\n";
    fs::write(&target, src).unwrap();

    let output = fmt_path(&target, &[]);
    assert_eq!(
        output.status.code(),
        Some(1),
        "unclosed block should map to exit 1"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("syntax") && stderr.contains("@end"),
        "expected a syntax diagnostic about the missing @end, got: {stderr}"
    );
    assert!(
        !stderr.contains("formatter_invariant") && !stderr.contains("file an issue"),
        "author error must not be reported as a formatter bug, got: {stderr}"
    );
    assert_eq!(
        fs::read_to_string(&target).unwrap(),
        src,
        "malformed file must be left untouched"
    );
}

#[test]
fn dir_malformed_file_continues_and_reports_one_failed() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(
        dir.path().join("bad.mds"),
        read_fixture("fmt_malformed.mds"),
    )
    .unwrap();
    fs::write(
        dir.path().join("good.mds"),
        read_fixture("fmt_unformatted.mds"),
    )
    .unwrap();

    let output = fmt_path(dir.path(), &[]);
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("1 failed"),
        "expected '1 failed' in summary, got: {stderr}"
    );

    // good.mds must still have been formatted (continue-on-error).
    let good_after = fs::read_to_string(dir.path().join("good.mds")).unwrap();
    assert!(
        !good_after.contains('\r'),
        "good.mds should still be formatted"
    );
}

#[test]
fn missing_file_exits_two() {
    let output = fmt_path(Path::new("/tmp/no_such_fmt_target_xyz.mds"), &[]);
    assert_eq!(output.status.code(), Some(2));
}

#[test]
fn non_mds_extension_rejected_exits_two() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("notes.txt");
    fs::write(&target, "just some text\n").unwrap();

    let output = fmt_path(&target, &[]);
    assert_eq!(
        output.status.code(),
        Some(2),
        "non-.mds explicit file must be rejected"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("mds") || stderr.contains("extension"),
        "expected a not-an-mds-file diagnostic, got: {stderr}"
    );
}

#[test]
#[cfg(unix)]
fn symlinked_file_rejected() {
    let dir = tempfile::tempdir().unwrap();
    let real = dir.path().join("real.mds");
    fs::write(&real, "Hello!\n").unwrap();
    let link = dir.path().join("link.mds");
    std::os::unix::fs::symlink(&real, &link).unwrap();

    let output = fmt_path(&link, &[]);
    assert!(!output.status.success(), "symlinked file must be rejected");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("symlink"),
        "expected symlink diagnostic, got: {stderr}"
    );
}

#[test]
#[cfg(unix)]
fn symlinked_directory_root_rejected() {
    let real_dir = tempfile::tempdir().unwrap();
    fs::write(real_dir.path().join("page.mds"), "Hello!\n").unwrap();
    let link_parent = tempfile::tempdir().unwrap();
    let link_path = link_parent.path().join("linked");
    std::os::unix::fs::symlink(real_dir.path(), &link_path).unwrap();

    let output = fmt_path(&link_path, &[]);
    assert!(
        !output.status.success(),
        "symlinked directory root must be rejected"
    );
}

#[test]
fn oversized_file_exits_three() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("huge.mds");
    let content = "x".repeat(10 * 1024 * 1024 + 1);
    fs::write(&target, &content).unwrap();

    let output = fmt_path(&target, &[]);
    assert_eq!(
        output.status.code(),
        Some(3),
        "oversized source should map to exit 3"
    );
}

#[test]
#[cfg(unix)]
fn bad_utf8_exits_two() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("bad_utf8.mds");
    std::fs::write(&target, [0xFF, 0xFE, b'\n']).unwrap();

    let output = fmt_path(&target, &[]);
    assert_eq!(
        output.status.code(),
        Some(2),
        "invalid UTF-8 should map to exit 2"
    );
}

// ── Channel discipline: capture stdout/stderr separately ────────────────────

#[test]
fn channels_stdout_only_content_stderr_only_status() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("dirty.mds");
    fs::write(&target, read_fixture("fmt_unformatted.mds")).unwrap();

    // Write mode: nothing on stdout, status on stderr.
    let output = fmt_path(&target, &[]);
    assert!(
        output.stdout.is_empty(),
        "write mode must not print to stdout"
    );
    assert!(
        !output.stderr.is_empty(),
        "write mode should print status to stderr"
    );
}

#[test]
fn channels_diff_goes_to_stdout_summary_to_stderr_in_dir_mode() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(
        dir.path().join("dirty.mds"),
        read_fixture("fmt_unformatted.mds"),
    )
    .unwrap();

    let output = fmt_path(dir.path(), &["--diff"]);
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stdout.contains("---") || stdout.contains("+++"),
        "diff should be on stdout: {stdout}"
    );
    assert!(
        !stderr.contains("---") && !stderr.contains("+++"),
        "diff must not leak to stderr: {stderr}"
    );
}

// ── Config: mds.json `fmt` section ───────────────────────────────────────────

#[test]
fn fmt_config_section_parses_and_pre_existing_configs_still_load() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("dirty.mds");
    fs::write(&target, read_fixture("fmt_unformatted.mds")).unwrap();
    fs::write(
        dir.path().join("mds.json"),
        r#"{"build": {"output_dir": "dist"}, "fmt": {"sort_frontmatter_keys": false}}"#,
    )
    .unwrap();

    let output = fmt_path(&target, &[]);
    assert!(
        output.status.success(),
        "fmt should succeed with a fmt-section config present; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn pre_existing_config_without_fmt_section_still_loads() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("dirty.mds");
    fs::write(&target, read_fixture("fmt_unformatted.mds")).unwrap();
    fs::write(
        dir.path().join("mds.json"),
        r#"{"build": {"output_dir": "dist"}}"#,
    )
    .unwrap();

    let output = fmt_path(&target, &[]);
    assert!(
        output.status.success(),
        "fmt should succeed with a pre-existing (no fmt section) config; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

// ── Walker default exclusion: node_modules ────────────────────────────────────

/// `mds fmt <dir>` must leave files inside `node_modules/` untouched.
/// The summary must not count the `node_modules` file in the formatted/unchanged
/// total — the directory is simply not traversed.
#[test]
fn dir_fmt_skips_node_modules() {
    let dir = tempfile::tempdir().unwrap();
    // One normal file that needs formatting (has \r so it changes).
    fs::write(dir.path().join("main.mds"), "Hello \r\nworld\r\n").unwrap();
    // File inside node_modules — must not be touched.
    let nm = dir.path().join("node_modules");
    std::fs::create_dir(&nm).unwrap();
    fs::write(nm.join("lib.mds"), "lib content\r\n").unwrap();

    let output = fmt_path(dir.path(), &[]);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // The node_modules file must not have been modified.
    let nm_content = fs::read_to_string(nm.join("lib.mds")).unwrap();
    assert_eq!(
        nm_content, "lib content\r\n",
        "node_modules/lib.mds must not be reformatted"
    );

    // Summary must say "1 formatted" (only the root-level main.mds), not "2".
    assert!(
        stderr.contains("1 formatted"),
        "summary must show exactly 1 formatted file (node_modules excluded); got: {stderr}"
    );
    assert!(
        output.status.success(),
        "fmt should succeed; stderr: {stderr}"
    );
}

// ── RELEASE BLOCKER 3: formatter gate must not false-positive on trailing blank ──

/// `mds fmt` on a non-compiling source (undefined variable → structural_equivalent
/// fallback) with a trailing blank line after the final directive must exit 0 and
/// write the formatted file — NOT exit 1 with "formatter_invariant".
///
/// Before the fix, R2's `trim_end()` deleted the trailing Text("\n") token from the
/// formatted output while the source still had it, triggering a spurious
/// FormatterInvariant error in structural_equivalent's token-count guard.
#[test]
fn gate_fallback_no_false_positive_on_trailing_blank_line_exits_zero() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("trailing_blank.mds");
    // Non-compiling source (undefined_var): takes structural_equivalent path.
    // Trailing blank line after @end: was the trigger for the false positive.
    fs::write(&target, "@if undefined_var:\nx\n@end\n\n").unwrap();

    let output = fmt_path(&target, &[]);

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("formatter_invariant") && !stderr.contains("file an issue"),
        "trailing blank line must NOT produce a FormatterInvariant, got: {stderr}"
    );
    assert!(
        output.status.success(),
        "fmt must succeed (exit 0) for a non-compiling source with trailing blank; stderr: {stderr}"
    );

    // The file must have been formatted (trailing blank trimmed).
    let after = fs::read_to_string(&target).unwrap();
    assert_eq!(
        after, "@if undefined_var:\nx\n@end\n",
        "formatted file must have trailing blank removed"
    );
}

// ── format_str_named: file path appears in error output ───────────────────────

/// Single-file mode: when the source has a genuine syntax error (unclosed @if),
/// `mds fmt` must show the file path in stderr so the user can locate the problem.
/// The file name must appear regardless of whether it is a lex- or parse-level error.
#[test]
fn single_file_syntax_error_includes_path_in_stderr() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("broken.mds");
    fs::write(&target, "@if cond:\nHello\n").unwrap(); // unclosed @if -> parse-level Syntax

    let output = fmt_path(&target, &[]);

    assert!(
        !output.status.success(),
        "fmt must fail (exit non-zero) on syntax error"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("broken.mds"),
        "stderr must contain the file name so the user can locate the problem; got: {stderr}"
    );
}

/// Directory mode: each failing file should be identified in stderr.
/// The file path prefix (`{file}: `) must appear before the error so large
/// directory runs show which file triggered each failure.
#[test]
fn dir_mode_format_error_includes_file_prefix_in_stderr() {
    let dir = tempfile::tempdir().unwrap();
    let bad = dir.path().join("bad.mds");
    let good = dir.path().join("good.mds");
    fs::write(&bad, "@if cond:\nHello\n").unwrap(); // unclosed @if -> format error
    fs::write(&good, "Hello!\n").unwrap();

    let output = fmt_path(dir.path(), &[]);

    // Exit non-zero because bad.mds failed.
    assert!(
        !output.status.success(),
        "fmt should exit non-zero when a file in the directory fails"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    // The bad file's name must appear in stderr (either as a {file}: prefix or in the error).
    assert!(
        stderr.contains("bad.mds"),
        "dir-mode stderr must identify the failing file; got: {stderr}"
    );
}

/// `mds fmt --check` summary includes the unchanged count alongside the would-reformat count.
/// New format: `{changed} would reformat, {unchanged} unchanged, {fail} failed`
#[test]
fn dir_check_summary_includes_unchanged_count() {
    let dir = tempfile::tempdir().unwrap();
    // One dirty file (would reformat) + one already-clean file (unchanged).
    fs::write(
        dir.path().join("dirty.mds"),
        read_fixture("fmt_unformatted.mds"),
    )
    .unwrap();
    fs::write(
        dir.path().join("clean.mds"),
        read_fixture("fmt_formatted.mds"),
    )
    .unwrap();

    let output = fmt_path(dir.path(), &["--check"]);
    assert!(
        !output.status.success(),
        "dir --check with a dirty file must exit non-zero"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("would reformat") && stderr.contains("unchanged"),
        "check summary must include both 'would reformat' and 'unchanged'; got: {stderr}"
    );
    // Verify the exact format: "N would reformat, M unchanged, K failed"
    assert!(
        stderr.contains("1 would reformat") && stderr.contains("1 unchanged"),
        "expected '1 would reformat' and '1 unchanged' in summary; got: {stderr}"
    );
}

// ── Bare-filename regression (PF-006) ────────────────────────────────────────

/// A syntax error in a bare-filename source must exit non-zero and propagate
/// the syntax diagnostic.
///
/// Regression for PF-006: `path.parent()` on a bare filename returns `Some("")`.
/// `NativeFs::canonicalize("")` failed with `MdsError::Io`, which the
/// `assert_equivalent` fallback path silently swallowed (fell through to
/// `structural_equivalent`) instead of propagating the `MdsError::Syntax` error.
/// After the `resolve_base_dir` + `effective_parent` fix the syntax error must
/// surface as a non-zero exit.
///
/// Uses `.current_dir(tempdir)` with a bare argument — absolute paths go through
/// a different code path and never triggered the bug.
#[test]
fn fmt_bare_filename_propagates_syntax_error() {
    let dir = tempfile::tempdir().unwrap();
    // An unclosed @message block is a parse-level syntax error (missing @end).
    // This same source is used by unclosed_directive_block_exits_one_with_syntax_not_formatter_invariant
    // (which passes an absolute path); our test exercises the bare-filename path.
    let src = "@message user:\nHi there\n";
    fs::write(dir.path().join("broken.mds"), src).unwrap();

    let output = mds_bin()
        .arg("fmt")
        .arg("broken.mds") // bare filename — the only form that triggered the bug
        .current_dir(dir.path())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "fmt of a bare broken filename must exit non-zero; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("syntax") || stderr.contains("@end"),
        "stderr must name the syntax problem; got: {stderr}"
    );
    // File must be untouched — the formatter must never write garbled output.
    let after = fs::read_to_string(dir.path().join("broken.mds")).unwrap();
    assert_eq!(after, src, "broken file must be left untouched");
}

// ── ESC injection regression — mds fmt (issue #176 / ESC-INJECTION) ──────────

/// Regression gate: `mds fmt <file>` (single-file mode) must not emit raw ESC
/// bytes to stderr when the source file contains a raw ESC byte that reaches
/// `MdsError::Syntax`.
///
/// Single-file fmt errors propagate to `main()` via `?`, which is the
/// last-resort sanitizer boundary at `main.rs`.  This test validates that
/// boundary for the fmt subcommand specifically.
#[test]
fn fmt_single_file_esc_byte_in_syntax_error_is_sanitized_on_stderr() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("esc_fmt.mds");
    fs::write(&path, b"@define \x1bfoo:\nhello\n").unwrap();

    let out = fmt_path(&path, &[]);

    assert_ne!(
        out.status.code(),
        Some(0),
        "fmt with syntax error should fail; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        !out.stderr.contains(&0x1Bu8),
        "raw ESC byte (0x1B) must be sanitized before writing to stderr (fmt single-file); \
         got (hex): {:02x?}",
        &out.stderr[..out.stderr.len().min(512)]
    );
    assert!(
        !out.stdout.contains(&0x1Bu8),
        "raw ESC byte (0x1B) must not appear in stdout (fmt single-file); \
         got (hex): {:02x?}",
        &out.stdout[..out.stdout.len().min(512)]
    );
}

// ── Permission preservation (issue #25 — atomic write regression gate) ──────

/// Regression gate: `mds fmt <file>` (single-file mode) must preserve the
/// original Unix file mode after formatting.
///
/// The write path was changed from bare `std::fs::write` (which truncates the
/// existing file in place, keeping its permissions) to `atomic_write_file` (temp
/// file + rename).  `tempfile::Builder` defaults to mode 0600; without permission
/// preservation the rename would silently turn a 0644 source file into owner-only.
///
/// `atomic_write_file` already handles this (commit c5aa086 hardened the lint
/// path) — this test locks in the same guarantee for the fmt path.
#[cfg(unix)]
#[test]
fn fmt_single_file_preserves_mode_0644() {
    use std::os::unix::fs::PermissionsExt as _;

    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("perm_test.mds");
    // Write unformatted content that fmt will actually rewrite.
    fs::write(&target, read_fixture("fmt_unformatted.mds")).unwrap();
    // Set 0644 explicitly (some systems may default differently).
    fs::set_permissions(&target, fs::Permissions::from_mode(0o644)).unwrap();

    let output = fmt_path(&target, &[]);
    assert!(
        output.status.success(),
        "fmt should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let mode = fs::metadata(&target).unwrap().permissions().mode() & 0o777;
    assert_eq!(
        mode, 0o644,
        "fmt single-file must preserve file mode 0644 after atomic write; got 0{mode:o}"
    );
}

/// Regression gate: `mds fmt <dir>` (directory mode) must preserve the original
/// Unix file mode after formatting.
///
/// Directory mode routes through `format_one_file` → `atomic_write_file`.
/// Same tempfile-0600 hazard as the single-file path above.
#[cfg(unix)]
#[test]
fn fmt_directory_mode_preserves_mode_0644() {
    use std::os::unix::fs::PermissionsExt as _;

    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("perm_dir_test.mds");
    fs::write(&target, read_fixture("fmt_unformatted.mds")).unwrap();
    fs::set_permissions(&target, fs::Permissions::from_mode(0o644)).unwrap();

    // Run fmt on the DIRECTORY — exercises format_one_file, not run_fmt_file.
    let output = fmt_path(dir.path(), &[]);
    assert!(
        output.status.success(),
        "fmt dir should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let mode = fs::metadata(&target).unwrap().permissions().mode() & 0o777;
    assert_eq!(
        mode, 0o644,
        "fmt directory mode must preserve file mode 0644 after atomic write; got 0{mode:o}"
    );
}

/// Regression gate: `mds fmt <dir>` (directory mode) must not emit raw ESC bytes
/// to stderr when a source file contains a raw ESC byte that reaches `MdsError::Syntax`.
///
/// Directory mode routes through `format_one_file`, which previously called
/// `eprintln!("{file_name}: {e:?}")` without sanitization.  That path is now
/// guarded by `crate::output::eprint_error` (avoids PF-004 parallel-path gap).
#[test]
fn fmt_directory_esc_byte_in_syntax_error_is_sanitized_on_stderr() {
    let dir = tempfile::tempdir().unwrap();
    // Raw ESC byte (0x1B) on the error line so miette renders it in the source context frame.
    fs::write(
        dir.path().join("esc_fmt_dir.mds"),
        b"@define \x1bfoo:\nhello\n",
    )
    .unwrap();

    let out = fmt_path(dir.path(), &[]);

    assert_ne!(
        out.status.code(),
        Some(0),
        "fmt dir with syntax error should fail; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        !out.stderr.contains(&0x1Bu8),
        "raw ESC byte (0x1B) must be sanitized before writing to stderr (fmt directory); \
         got (hex): {:02x?}",
        &out.stderr[..out.stderr.len().min(512)]
    );
    assert!(
        !out.stdout.contains(&0x1Bu8),
        "raw ESC byte (0x1B) must not appear in stdout (fmt directory); \
         got (hex): {:02x?}",
        &out.stdout[..out.stdout.len().min(512)]
    );
}

// ── C4/F6: existence-before-extension ordering for fmt ───────────────────────

/// A non-existent path that also lacks the `.mds` extension must report
/// `mds::file_not_found` (exit 2), NOT `mds::not_mds_file` (exit 2).
///
/// Before C4/F6, `ensure_mds_extension` ran before existence was checked, so
/// a user pointing at `/nonexistent.txt` got "not an .mds file" — confusing
/// because the path doesn't exist at all.
#[test]
fn fmt_nonexistent_non_mds_reports_file_not_found_not_extension_error() {
    let dir = tempfile::tempdir().unwrap();
    // Path that does not exist AND has a non-.mds extension.
    let missing = dir.path().join("missing_file_12345.txt");

    let output = fmt_path(&missing, &[]);

    assert_eq!(
        output.status.code(),
        Some(2),
        "non-existent file must exit 2; got: {:?}",
        output.status.code()
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("mds::file_not_found") || stderr.contains("file not found"),
        "error must be file-not-found (not extension error); got: {stderr:?}"
    );
    assert!(
        !stderr.contains("mds::not_mds_file") && !stderr.contains("not an .mds"),
        "must NOT report 'not an .mds file' for a non-existent path; got: {stderr:?}"
    );
}

// ── R3 / CWE-209: fmt raw-read errors name the project-root-relative path ────

#[test]
fn r3_fmt_read_error_names_root_relative_path() {
    // Invalid UTF-8 fails on the raw-read path (fmt.rs read_source_file),
    // which must anchor its display root at the project root so the error
    // message shows "sub/bad.mds" — never a bare basename and never the
    // canonical absolute path (R3 / CWE-209; mirrors lint.rs).
    let dir = tempfile::tempdir().unwrap();
    // Canonical form (macOS: /var → /private/var) — what a leaked key carries.
    let root = dir.path().canonicalize().unwrap();
    // Deterministic project-root walk-up anchor.
    std::fs::write(root.join(".mdsroot"), "").unwrap();
    let sub = root.join("sub");
    fs::create_dir_all(&sub).unwrap();
    let input = sub.join("bad.mds");
    fs::write(&input, b"Hello \xFF\xFE world\n").unwrap();

    let output = fmt_path(&input, &[]);

    assert_eq!(
        output.status.code(),
        Some(2),
        "invalid UTF-8 must exit 2 (I/O class); stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    let root_str = root.to_str().unwrap();
    // Positive control (PF-013): a message carrying the absolute path WOULD be
    // caught by the absence assertion below.
    let planted = format!("invalid UTF-8 in {}: …", input.display());
    assert!(
        planted.contains(root_str),
        "positive control: planted absolute form must match the absence predicate"
    );
    assert!(
        stderr.contains("sub/bad.mds"),
        "fmt read error must show the project-root-relative path; got: {stderr}"
    );
    assert!(
        !stderr.contains(root_str),
        "fmt read error must not leak the absolute path prefix; got: {stderr}"
    );
}