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
//! Integration tests for `mds build <dir>` and `mds check <dir>`.
//!
//! Coverage:
//! - T-CLI-12 (FUNC-16): subtree mirror + intrinsic ext per file with --out-dir
//! - T-CLI-13 (FUNC-17): `_`-prefixed partials produce no output
//! - T-CLI-14 (FUNC-18): continue-on-error: per-file error, summary, non-zero exit
//! - T-CLI-15 (FUNC-19): bare build without --out-dir writes next-to-source
//! - T-CLI-16 (FUNC-20): in-tree symlinked file/dir skipped; symlinked entry root rejected
//! - T-CLI-17 (FUNC-21): one oversized (>10 MiB) file fails while others succeed
//! - T-CLI-20 (FUNC-26): `check <dir>` validates tree, continues on error, non-zero exit on failure
//! - T-CLI-21 (FUNC-16, unit): `output_path_for("json"/"md")` + `..`-containment (AC-M7)
//!   (covered in output.rs unit tests; here we test via CLI)
//! - AC-Q01 (#216): `mds build --quiet <dir>` on all-success tree produces no stderr
//! - AC-Q02 (#216): `mds build --quiet <dir>` with a failing file still prints summary
//! - AC-Q30 (#216): `--quiet` before subcommand and after produce identical results

mod common;
use common::mds_bin;

use std::fs;
use std::path::Path;

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

fn create_plain_mds(dir: &Path, name: &str) {
    // Use no template variables so this always compiles successfully.
    fs::write(dir.join(name), "Hello, world!\n").unwrap();
}

fn create_messages_mds(dir: &Path, name: &str) {
    fs::write(
        dir.join(name),
        "@message system:\nYou are a helpful assistant.\n@end\n@message user:\nHello!\n@end\n",
    )
    .unwrap();
}

/// A syntactically invalid .mds file (undefined variable causes a compile error).
fn create_bad_mds(dir: &Path, name: &str) {
    fs::write(dir.join(name), "{{undefined_var_xyz}}\n").unwrap();
}

fn build_dir(dir: &Path, extra_args: &[&str]) -> std::process::Output {
    mds_bin()
        .arg("build")
        .arg(dir)
        .args(extra_args)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap()
}

fn check_dir(dir: &Path, extra_args: &[&str]) -> std::process::Output {
    mds_bin()
        .arg("check")
        .arg(dir)
        .args(extra_args)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap()
}

// ── T-CLI-12 (FUNC-16): subtree mirror + intrinsic ext per file ───────────────

#[test]
fn dir_build_subtree_mirror_intrinsic_ext() {
    let src = tempfile::tempdir().unwrap();
    let out = tempfile::tempdir().unwrap();

    // Structure: src/plain.mds, src/sub/messages.mds
    fs::create_dir(src.path().join("sub")).unwrap();
    create_plain_mds(src.path(), "plain.mds");
    create_messages_mds(&src.path().join("sub"), "messages.mds");

    let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);

    assert!(
        output.status.success(),
        "dir build should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // plain.mds → out/plain.md (markdown kind)
    let plain_out = out.path().join("plain.md");
    assert!(
        plain_out.exists(),
        "expected out/plain.md to be created; out dir: {:?}",
        fs::read_dir(out.path()).map(|rd| rd
            .filter_map(|e| e.ok().map(|e| e.path()))
            .collect::<Vec<_>>())
    );
    let plain_content = fs::read_to_string(&plain_out).unwrap();
    assert!(
        plain_content.contains("Hello"),
        "plain.md should contain rendered content; got: {plain_content:?}"
    );

    // sub/messages.mds → out/sub/messages.json (messages kind)
    let msg_out = out.path().join("sub").join("messages.json");
    assert!(
        msg_out.exists(),
        "expected out/sub/messages.json to be created"
    );
    let msg_content = fs::read_to_string(&msg_out).unwrap();
    let parsed: serde_json::Value =
        serde_json::from_str(&msg_content).expect("messages.json should be valid JSON");
    assert!(parsed.is_array(), "messages.json should be a JSON array");

    // Summary mentions built count
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("built"),
        "stderr should contain build summary; got: {stderr}"
    );
}

// ── T-CLI-13 (FUNC-17): `_`-prefixed partials produce no output ──────────────

#[test]
fn dir_build_partials_produce_no_output() {
    let src = tempfile::tempdir().unwrap();
    let out = tempfile::tempdir().unwrap();

    // _partial.mds starts with `_` — should be skipped.
    create_plain_mds(src.path(), "_partial.mds");
    // main.mds is a normal file.
    create_plain_mds(src.path(), "main.mds");

    let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);

    assert!(
        output.status.success(),
        "dir build should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // _partial.mds must NOT produce _partial.md
    let partial_out = out.path().join("_partial.md");
    assert!(
        !partial_out.exists(),
        "_partial.md must not be created (partials are skipped)"
    );

    // main.mds MUST produce main.md
    let main_out = out.path().join("main.md");
    assert!(main_out.exists(), "main.md should be created");
}

// ── T-CLI-14 (FUNC-18): continue-on-error, summary, non-zero exit ────────────

#[test]
fn dir_build_continue_on_error_summary_nonzero() {
    let src = tempfile::tempdir().unwrap();
    let out = tempfile::tempdir().unwrap();

    // good.mds compiles fine; bad.mds has an undefined variable.
    create_plain_mds(src.path(), "good.mds");
    create_bad_mds(src.path(), "bad.mds");

    let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);

    // Must exit non-zero because bad.mds failed.
    assert!(
        !output.status.success(),
        "dir build with a failing file must exit non-zero"
    );

    // good.mds MUST still be written (continue-on-error).
    let good_out = out.path().join("good.md");
    assert!(
        good_out.exists(),
        "good.md should still be created despite bad.mds failing"
    );

    // bad.mds should NOT produce output.
    let bad_out = out.path().join("bad.md");
    assert!(
        !bad_out.exists(),
        "bad.md must not be created when compilation fails"
    );

    // Summary must be present in stderr.
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("built") && stderr.contains("failed"),
        "stderr must contain a build summary with 'built' and 'failed'; got: {stderr}"
    );
    // Specifically: "1 built, 1 failed"
    assert!(
        stderr.contains("1 built") && stderr.contains("1 failed"),
        "stderr must show '1 built, 1 failed'; got: {stderr}"
    );
}

// ── T-CLI-15 (FUNC-19): bare build writes next-to-source ─────────────────────

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

    create_plain_mds(src.path(), "page.mds");
    create_messages_mds(src.path(), "chat.mds");

    // No --out-dir: outputs go next to source.
    let output = build_dir(src.path(), &[]);

    assert!(
        output.status.success(),
        "bare dir build should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // plain → same dir, .md
    let page_out = src.path().join("page.md");
    assert!(page_out.exists(), "page.md should appear next to page.mds");

    // messages → same dir, .json
    let chat_out = src.path().join("chat.json");
    assert!(
        chat_out.exists(),
        "chat.json should appear next to chat.mds"
    );

    // Clean up outputs.
    let _ = fs::remove_file(&page_out);
    let _ = fs::remove_file(&chat_out);
}

// ── T-CLI-16 (FUNC-20): in-tree symlinks skipped; symlinked entry root rejected

#[cfg(unix)]
#[test]
fn dir_build_symlinked_file_skipped() {
    let src = tempfile::tempdir().unwrap();
    let out = tempfile::tempdir().unwrap();

    // Create a real file and a symlink to it.
    let real_file = src.path().join("real.mds");
    fs::write(&real_file, "Real content.\n").unwrap();
    let link_file = src.path().join("link.mds");
    std::os::unix::fs::symlink(&real_file, &link_file).unwrap();

    let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);

    assert!(
        output.status.success(),
        "build should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // The symlinked file (link.mds) must NOT produce output.
    let link_out = out.path().join("link.md");
    assert!(
        !link_out.exists(),
        "symlinked .mds file must not produce output"
    );

    // The real file MUST produce output.
    let real_out = out.path().join("real.md");
    assert!(real_out.exists(), "real.md should be created from real.mds");
}

#[cfg(unix)]
#[test]
fn dir_build_symlinked_subdir_skipped() {
    let real_dir = tempfile::tempdir().unwrap();
    let src = tempfile::tempdir().unwrap();
    let out = tempfile::tempdir().unwrap();

    // Place a .mds file in real_dir and make a symlink into src pointing at it.
    fs::write(real_dir.path().join("child.mds"), "Child.\n").unwrap();
    let link_dir = src.path().join("linked_sub");
    std::os::unix::fs::symlink(real_dir.path(), &link_dir).unwrap();

    // Also create a real file at the root so the build isn't empty.
    create_plain_mds(src.path(), "root.mds");

    let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);

    assert!(
        output.status.success(),
        "build should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // The symlinked directory must not be traversed — child.mds in it produces no output.
    let child_out = out.path().join("linked_sub").join("child.md");
    assert!(
        !child_out.exists(),
        "symlinked subdirectory must not be traversed"
    );
}

#[cfg(unix)]
#[test]
fn dir_build_symlinked_entry_root_rejected() {
    let real_dir = tempfile::tempdir().unwrap();
    create_plain_mds(real_dir.path(), "page.mds");

    // Create a symlink pointing at the real dir.
    let link_dir = tempfile::tempdir().unwrap();
    let link_path = link_dir.path().join("linked");
    std::os::unix::fs::symlink(real_dir.path(), &link_path).unwrap();

    let output = build_dir(&link_path, &[]);

    assert!(
        !output.status.success(),
        "build on a symlinked entry root must fail"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("symlink") || stderr.contains("directory"),
        "error must mention symlink; got: {stderr}"
    );
}

// ── T-CLI-17 (FUNC-21): oversized file fails, others succeed ─────────────────

#[test]
fn dir_build_oversized_file_fails_others_succeed() {
    let src = tempfile::tempdir().unwrap();
    let out = tempfile::tempdir().unwrap();

    // Create a good file.
    create_plain_mds(src.path(), "good.mds");

    // Create an oversized file (>10 MiB = > 10 * 1024 * 1024 bytes).
    let big_content = "x".repeat(10 * 1024 * 1024 + 1);
    fs::write(src.path().join("big.mds"), &big_content).unwrap();

    let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);

    // Must exit non-zero because big.mds failed the size cap.
    assert!(
        !output.status.success(),
        "dir build with an oversized file must exit non-zero"
    );

    // good.mds MUST still be written.
    let good_out = out.path().join("good.md");
    assert!(
        good_out.exists(),
        "good.md should still be created despite the oversized file"
    );

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

// ── T-CLI-20 (FUNC-26): `check <dir>` ────────────────────────────────────────

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

    create_plain_mds(src.path(), "page.mds");
    create_messages_mds(src.path(), "chat.mds");

    let output = check_dir(src.path(), &[]);

    assert!(
        output.status.success(),
        "check on a valid tree should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("passed"),
        "stderr should contain check summary; got: {stderr}"
    );
}

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

    create_plain_mds(src.path(), "good.mds");
    create_bad_mds(src.path(), "bad.mds");

    let output = check_dir(src.path(), &[]);

    // Must exit non-zero because bad.mds failed.
    assert!(
        !output.status.success(),
        "check with a failing file must exit non-zero"
    );

    // Summary should show counts.
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("passed") || stderr.contains("failed"),
        "stderr must contain check summary; got: {stderr}"
    );
}

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

    let output = check_dir(src.path(), &[]);

    assert!(
        output.status.success(),
        "check on empty dir should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("No .mds files") || stderr.contains("no .mds"),
        "stderr should mention no files found; got: {stderr}"
    );
}

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

    // Mixed content: text before @message — AC-FUNC-25 / mds::mixed_content error.
    fs::write(
        src.path().join("mixed.mds"),
        "Some text before.\n@message user:\nHello!\n@end\n",
    )
    .unwrap();

    let output = check_dir(src.path(), &[]);

    assert!(
        !output.status.success(),
        "check on a mixed-content file must exit non-zero"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("mixed") || stderr.contains("failed"),
        "error must mention mixed content or failure; got: {stderr}"
    );
}

// ── T-CLI-21 variant: stale-output cleanup on format-flip (dir build) ─────────

#[test]
fn dir_build_stale_output_cleaned_on_format_flip() {
    let src = tempfile::tempdir().unwrap();
    let out = tempfile::tempdir().unwrap();

    // Step 1: Build a plain template → produces page.md
    let mds_path = src.path().join("page.mds");
    fs::write(&mds_path, "Hello, world!\n").unwrap();

    let output1 = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);
    assert!(
        output1.status.success(),
        "first build should succeed; stderr: {}",
        String::from_utf8_lossy(&output1.stderr)
    );
    let md_out = out.path().join("page.md");
    assert!(md_out.exists(), "page.md should be created on first build");

    // Step 2: Rewrite the template to use @message → would produce page.json
    fs::write(&mds_path, "@message user:\nHello!\n@end\n").unwrap();

    let output2 = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);
    assert!(
        output2.status.success(),
        "second build should succeed; stderr: {}",
        String::from_utf8_lossy(&output2.stderr)
    );
    let json_out = out.path().join("page.json");
    assert!(
        json_out.exists(),
        "page.json should be created on second build"
    );

    // Stale page.md from step 1 must be removed.
    assert!(
        !md_out.exists(),
        "stale page.md should be removed after format flip to messages"
    );
}

// ── T-CLI: empty dir build exits zero ────────────────────────────────────────

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

    let output = build_dir(src.path(), &[]);

    assert!(
        output.status.success(),
        "build on empty dir should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("No .mds files") || stderr.contains("no .mds"),
        "stderr should mention no .mds files; got: {stderr}"
    );
}

// ── Additional test helpers for lint/fmt subcommands ─────────────────────────

fn lint_dir(dir: &Path, extra_args: &[&str]) -> std::process::Output {
    mds_bin()
        .arg("lint")
        .arg(dir)
        .args(extra_args)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap()
}

fn fmt_dir(dir: &Path, extra_args: &[&str]) -> std::process::Output {
    mds_bin()
        .arg("fmt")
        .arg(dir)
        .args(extra_args)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap()
}

// ── T-CLI-ALL-EXCLUDED: all candidates in excluded dirs exits non-zero ────────
//
// Covers issue #2: when every .mds file is under a default-excluded directory
// (hidden dir or node_modules), the subcommand must:
//   (a) exit non-zero, not 0 — distinguishing from a genuinely empty tree
//   (b) emit a distinct message carrying the skip count
//   (c) emit the message even under --quiet (the CI guard case)

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

    // .github/prompts/ is a prime template location for prompt-template compilers.
    let hidden = src.path().join(".github");
    fs::create_dir_all(hidden.join("prompts")).unwrap();
    fs::write(hidden.join("prompts").join("system.mds"), "Hello!\n").unwrap();

    let output = build_dir(src.path(), &[]);

    assert!(
        !output.status.success(),
        "build with all candidates in excluded dirs must exit non-zero; exit: {:?}; stderr: {}",
        output.status.code(),
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    // Message must be distinct from "No .mds files found" and carry the skip count.
    assert!(
        stderr.contains("excluded") || stderr.contains("default-excluded"),
        "stderr must mention excluded directories; got: {stderr}"
    );
    assert!(
        stderr.contains('1'),
        "stderr must carry the skip count (1 file excluded); got: {stderr}"
    );
}

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

    let nm = src.path().join("node_modules");
    fs::create_dir(&nm).unwrap();
    fs::write(nm.join("lib.mds"), "Hello!\n").unwrap();
    fs::write(nm.join("other.mds"), "World!\n").unwrap();

    // --quiet must NOT suppress the all-excluded diagnostic — this is the exact
    // CI invocation where a silent green pass is the danger.
    let output = build_dir(src.path(), &["--quiet"]);

    assert!(
        !output.status.success(),
        "build with all candidates excluded must exit non-zero even under --quiet"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.is_empty(),
        "stderr must not be empty under --quiet when all candidates are excluded"
    );
    assert!(
        stderr.contains("excluded") || stderr.contains("default-excluded"),
        "all-excluded diagnostic must appear under --quiet; got: {stderr}"
    );
    // Skip count must appear in message.
    assert!(
        stderr.contains('2'),
        "stderr must report 2 skipped files; got: {stderr}"
    );
}

#[test]
fn dir_build_genuinely_empty_still_exits_zero() {
    // Regression guard: a genuinely empty directory (no .mds files anywhere)
    // must still exit 0 — only the all-excluded case exits non-zero.
    let src = tempfile::tempdir().unwrap();

    let output = build_dir(src.path(), &[]);

    assert!(
        output.status.success(),
        "genuinely empty dir must still exit 0; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    // Message must be the original "no files" message, not the excluded diagnostic.
    assert!(
        stderr.contains("No .mds files") || stderr.contains("no .mds"),
        "empty-dir message should mention no .mds files; got: {stderr}"
    );
    assert!(
        !stderr.contains("excluded"),
        "empty-dir must NOT show the excluded diagnostic; got: {stderr}"
    );
}

#[test]
fn dir_build_mixed_excluded_and_normal_processes_normal() {
    // Non-excluded files must still be processed even when some are in excluded dirs.
    let src = tempfile::tempdir().unwrap();
    let out = tempfile::tempdir().unwrap();

    // Normal file — must be built.
    create_plain_mds(src.path(), "normal.mds");

    // Excluded file — must be skipped.
    let hidden = src.path().join(".prompts");
    fs::create_dir(&hidden).unwrap();
    fs::write(hidden.join("excluded.mds"), "Hello!\n").unwrap();

    let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);

    // The build must succeed since normal.mds was found and processed.
    assert!(
        output.status.success(),
        "build with mixed excluded+normal files must succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // normal.mds → out/normal.md
    assert!(
        out.path().join("normal.md").exists(),
        "normal.md must be built"
    );

    // .prompts/excluded.md must NOT exist (excluded subdir was skipped).
    assert!(
        !out.path().join(".prompts").join("excluded.md").exists(),
        "excluded.md must not be built"
    );
}

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

    let hidden = src.path().join(".claude");
    fs::create_dir(&hidden).unwrap();
    fs::write(hidden.join("prompt.mds"), "Hello!\n").unwrap();

    let output = check_dir(src.path(), &[]);

    assert!(
        !output.status.success(),
        "check with all candidates in excluded dirs must exit non-zero; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("excluded") || stderr.contains("default-excluded"),
        "stderr must mention excluded directories; got: {stderr}"
    );
    assert!(
        stderr.contains('1'),
        "stderr must carry the skip count; got: {stderr}"
    );
}

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

    let hidden = src.path().join(".cursor");
    fs::create_dir_all(hidden.join("rules")).unwrap();
    fs::write(hidden.join("rules").join("rule.mds"), "Hello!\n").unwrap();

    let output = check_dir(src.path(), &["--quiet"]);

    assert!(
        !output.status.success(),
        "check with all candidates excluded must exit non-zero even under --quiet"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.is_empty() && (stderr.contains("excluded") || stderr.contains("default-excluded")),
        "all-excluded diagnostic must appear under --quiet; got: {stderr:?}"
    );
}

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

    let nm = src.path().join("node_modules");
    fs::create_dir(&nm).unwrap();
    fs::write(nm.join("template.mds"), "Hello!\n").unwrap();

    let output = lint_dir(src.path(), &[]);

    assert!(
        !output.status.success(),
        "lint with all candidates in excluded dirs must exit non-zero; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("excluded") || stderr.contains("default-excluded"),
        "stderr must mention excluded directories; got: {stderr}"
    );
}

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

    let hidden = src.path().join(".github");
    fs::create_dir(&hidden).unwrap();
    fs::write(hidden.join("workflow.mds"), "Hello!\n").unwrap();

    let output = lint_dir(src.path(), &["--quiet"]);

    assert!(
        !output.status.success(),
        "lint with all candidates excluded must exit non-zero even under --quiet"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.is_empty() && (stderr.contains("excluded") || stderr.contains("default-excluded")),
        "all-excluded diagnostic must appear under --quiet; got: {stderr:?}"
    );
}

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

    let hidden = src.path().join(".prompts");
    fs::create_dir(&hidden).unwrap();
    fs::write(hidden.join("system.mds"), "Hello!\n").unwrap();

    let output = fmt_dir(src.path(), &[]);

    assert!(
        !output.status.success(),
        "fmt with all candidates in excluded dirs must exit non-zero; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("excluded") || stderr.contains("default-excluded"),
        "stderr must mention excluded directories; got: {stderr}"
    );
}

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

    let nm = src.path().join("node_modules");
    fs::create_dir(&nm).unwrap();
    fs::write(nm.join("component.mds"), "Hello!\n").unwrap();

    let output = fmt_dir(src.path(), &["--quiet"]);

    assert!(
        !output.status.success(),
        "fmt with all candidates excluded must exit non-zero even under --quiet"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.is_empty() && (stderr.contains("excluded") || stderr.contains("default-excluded")),
        "all-excluded diagnostic must appear under --quiet; got: {stderr:?}"
    );
}

// ── AC-Q01: quiet build on all-success tree produces no stderr ────────────────
//
// Positive control: the identical tree without --quiet MUST still print the summary,
// proving the absence assertion under --quiet cannot pass vacuously.
// (PF-013/ADR-009: every absence assertion needs a paired positive control.)
//
// Scope: depth <= 64, no pre-existing stale sibling outputs (AC-Q05: two ungated
// warning writers in output.rs fire above MAX_DEPTH=64 or on a stale-unlink failure;
// documentation words those cases as "no output on a *successful* build", not absolute
// silence — see run_build_directory doc block).

#[test]
fn dir_build_quiet_suppresses_summary_on_success() {
    // Both the quiet run and the positive control run need their own tempdir so
    // build outputs from the first run do not affect the second.
    let src1 = tempfile::tempdir().unwrap();
    create_plain_mds(src1.path(), "a.mds");
    create_plain_mds(src1.path(), "b.mds");

    let quiet_out = build_dir(src1.path(), &["--quiet"]);

    assert_eq!(
        quiet_out.status.code(),
        Some(0),
        "quiet build over an all-success tree must exit 0; stderr: {}",
        String::from_utf8_lossy(&quiet_out.stderr)
    );
    let quiet_stderr = String::from_utf8_lossy(&quiet_out.stderr);
    assert!(
        quiet_stderr.is_empty(),
        "AC-Q01: --quiet build with no failures must produce empty stderr; got: {quiet_stderr:?}"
    );

    // Positive control: without --quiet the summary MUST appear.
    // (Proves the `is_empty` assertion above is not vacuously passing on a broken check.)
    let src2 = tempfile::tempdir().unwrap();
    create_plain_mds(src2.path(), "a.mds");
    create_plain_mds(src2.path(), "b.mds");

    let control_out = build_dir(src2.path(), &[]);
    let control_stderr = String::from_utf8_lossy(&control_out.stderr);
    assert!(
        control_stderr.contains("2 built"),
        "positive control: non-quiet run must print '2 built' so the quiet absence assertion \
         is non-vacuous; got: {control_stderr:?}"
    );
}

// ── AC-Q02: quiet build with a failing file still prints the summary ──────────
//
// When any file fails, the summary is always printed under --quiet so the
// non-zero exit is explained.  Exit codes are unaffected (AD-216-2).

#[test]
fn dir_build_quiet_still_prints_summary_on_failure() {
    let src = tempfile::tempdir().unwrap();
    create_plain_mds(src.path(), "good.mds");
    create_bad_mds(src.path(), "bad.mds");

    let output = build_dir(src.path(), &["--quiet"]);

    assert_eq!(
        output.status.code(),
        Some(1),
        "quiet build with a failing file must exit 1; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("1 built"),
        "AC-Q02: --quiet build with failures must print summary so non-zero exit is explained; \
         got: {stderr:?}"
    );
    assert!(
        stderr.contains("1 failed"),
        "AC-Q02: summary must include '1 failed'; got: {stderr:?}"
    );
}

// ── AC-Q30 (build half): --quiet in both argument positions (global flag) ─────
//
// --quiet is declared `global = true` (main.rs:31), so `mds --quiet build <dir>`
// and `mds build <dir> --quiet` must behave identically.

#[test]
fn dir_build_quiet_works_in_pre_subcommand_position() {
    let src = tempfile::tempdir().unwrap();
    create_plain_mds(src.path(), "a.mds");
    create_plain_mds(src.path(), "b.mds");

    // --quiet after subcommand (post-subcommand position).
    let post = build_dir(src.path(), &["--quiet"]);

    // --quiet before subcommand (pre-subcommand, global position).
    let pre = mds_bin()
        .arg("--quiet")
        .arg("build")
        .arg(src.path())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert_eq!(
        pre.status.code(),
        post.status.code(),
        "pre-subcommand --quiet must produce the same exit code as post-subcommand --quiet"
    );
    assert_eq!(
        pre.stderr, post.stderr,
        "pre-subcommand --quiet must produce the same stderr as post-subcommand --quiet"
    );

    // ANCHOR (PF-013): equality alone is vacuous — it holds just as well when BOTH
    // orderings are broken. Verified by mutation: with the `!quiet || fail_count > 0`
    // gate removed from build.rs, the two `assert_eq!`s above still passed while
    // `dir_build_quiet_suppresses_summary_on_success` correctly failed. Pin the
    // absolute value so this test fails too if --quiet stops suppressing.
    assert!(
        post.stderr.is_empty(),
        "AC-Q30 anchor: an all-success tree under --quiet must produce empty stderr in \
         BOTH orderings, not merely equal stderr; got: {}",
        String::from_utf8_lossy(&post.stderr)
    );

    // Paired positive control: the same sources without --quiet DO print the summary.
    let control_src = tempfile::tempdir().unwrap();
    create_plain_mds(control_src.path(), "a.mds");
    create_plain_mds(control_src.path(), "b.mds");
    let control = build_dir(control_src.path(), &[]);
    assert!(
        String::from_utf8_lossy(&control.stderr).contains("2 built, 0 failed"),
        "positive control: the same tree without --quiet must print '2 built, 0 failed'; got: {}",
        String::from_utf8_lossy(&control.stderr)
    );
}

// ── R5 (v0.4.0 dogfood): build summary counts zero-byte outputs ──────────────
//
// A definitions-only module (only @define/@export, no body) compiles
// successfully to ZERO bytes, so "N built" silently implies N useful artifacts
// when some are empty (PF-034-adjacent: a definitions-only @include shipping an
// empty section was normalized as noise).  R5: the summary becomes
// `{ok} built ({empty} empty), {fail} failed` — the clause appears ONLY when
// empty > 0 (zero golden churn otherwise), "empty" is STRICT zero bytes (not
// trim — messages-mode JSON output is never empty), and the summary/quiet gate
// (`!quiet || fail_count > 0`) is unchanged.

fn create_defs_only_mds(dir: &Path, name: &str) {
    // Compiles successfully to zero bytes: @define/@export contribute nothing
    // to the compiled body.
    fs::write(
        dir.join(name),
        "@define greet(name):\n  Hi {{name}}\n@end\n\n@export greet\n",
    )
    .unwrap();
}

#[test]
fn d5_dir_build_summary_reports_empty_outputs() {
    let src = tempfile::tempdir().unwrap();
    create_plain_mds(src.path(), "a.mds");
    create_defs_only_mds(src.path(), "lib.mds");

    let output = build_dir(src.path(), &[]);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "both files compile successfully; stderr: {stderr}"
    );
    // Non-vacuity: the zero-byte artifact must actually exist and be empty.
    let lib_out = src.path().join("lib.md");
    assert_eq!(
        fs::metadata(&lib_out).map(|m| m.len()).ok(),
        Some(0),
        "fixture invariant: lib.md must be a zero-byte output"
    );
    assert!(
        stderr.contains("2 built (1 empty), 0 failed"),
        "R5: summary must count zero-byte outputs; got: {stderr}"
    );
}

#[test]
fn d5_dir_build_summary_omits_empty_clause_when_none() {
    let src = tempfile::tempdir().unwrap();
    create_plain_mds(src.path(), "a.mds");

    let output = build_dir(src.path(), &[]);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("1 built, 0 failed"),
        "summary keeps its historical form when no output is empty; got: {stderr}"
    );
    assert!(
        !stderr.contains("empty"),
        "R5: the empty clause must be ABSENT when every output has content \
         (no golden churn); got: {stderr}"
    );
}

#[test]
fn d5_dir_build_quiet_gate_unchanged_with_empty_outputs() {
    // The summary gate stays `!quiet || fail_count > 0`: empty outputs do NOT
    // force the summary through --quiet on an all-success run.
    let src = tempfile::tempdir().unwrap();
    create_plain_mds(src.path(), "a.mds");
    create_defs_only_mds(src.path(), "lib.mds");

    let output = build_dir(src.path(), &["--quiet"]);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(output.status.success(), "all-success run; stderr: {stderr}");
    assert!(
        !stderr.contains("built"),
        "R5: --quiet must still suppress the summary on an all-success run even \
         when empty outputs exist (gate unchanged); got: {stderr}"
    );
}