mds-cli 0.7.0

MDS (Markdown Script) compiler — command-line interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
mod common;
use common::{assert_no_control_chars, dup_vars_file_warning, fixture, mds_bin};

#[test]
fn check_collecting_warnings_returns_warnings_for_empty_include() {
    // check_collecting_warnings should succeed (Ok) and surface the empty-@include
    // warning in the returned Vec<String> without printing to stderr.
    let path = fixture("include_empty_body.mds");
    let ((), warnings) = mds::check_collecting_warnings(&path, None)
        .expect("check_collecting_warnings should succeed on a valid file");
    assert!(
        warnings.iter().any(|w| w.contains("empty output")),
        "expected at least one warning about empty @include, got: {warnings:?}"
    );
}

#[test]
fn check_str_collecting_warnings_no_warnings_for_clean_source() {
    // A well-formed source with no warnings should return an empty warnings vec.
    let source = "---\nname: Test\n---\nHello {{name}}!\n";
    let ((), warnings) = mds::check_str_collecting_warnings(source, None, None)
        .expect("check_str_collecting_warnings should succeed on clean source");
    assert!(
        warnings.is_empty(),
        "clean source should produce no warnings, got: {warnings:?}"
    );
}

#[test]
fn check_str_collecting_warnings_errors_on_invalid_source() {
    // check_str_collecting_warnings should return Err for sources with compile errors,
    // independently of CLI argument parsing.
    let source = "{{undefined_variable}}";
    let result = mds::check_str_collecting_warnings(source, None, None);
    assert!(
        result.is_err(),
        "check_str_collecting_warnings should return Err for undefined variable"
    );
}

#[test]
fn warning_cap_at_max_warnings() {
    // Build a template with many @include of modules with no body.
    // Each @include of an empty module produces one warning.
    // We use a subdirectory with a shared empty library module.
    let dir = tempfile::tempdir().unwrap();

    // Create a shared empty module (no body — just a @define with no body text)
    let lib_path = dir.path().join("empty_lib.mds");
    std::fs::write(&lib_path, "@define noop():\n@end\n").unwrap();

    // Build main template: import empty_lib as 'lib' and @include it 1010 times.
    let mut src = String::from("@import \"./empty_lib.mds\" as lib\n");
    for _ in 0..1010 {
        src.push_str("@include lib\n");
    }
    let main_path = dir.path().join("main.mds");
    std::fs::write(&main_path, &src).unwrap();

    let result = mds::compile_collecting_warnings(&main_path, None)
        .expect("template should compile successfully");
    let warnings = result.warnings;

    assert_eq!(
        warnings.len(),
        1000,
        "warnings must be capped at exactly 1000, got {}",
        warnings.len()
    );
}

#[test]
fn check_empty_body_no_warning_in_quiet_mode() {
    // When -q/--quiet is set, the warning from @include of an empty module
    // should be suppressed for `mds check` too (not just `mds build`).
    let output = mds_bin()
        .args([
            "check",
            fixture("include_empty_body.mds").to_str().unwrap(),
            "--quiet",
        ])
        .output()
        .unwrap();
    assert!(output.status.success(), "quiet check should succeed");
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.is_empty(),
        "quiet flag should suppress warnings for check command, got: {stderr}"
    );
}

#[test]
fn include_empty_body_no_warning_in_quiet_mode() {
    // When -q/--quiet is set, the warning should be suppressed.
    let output = mds_bin()
        .args([
            "build",
            fixture("include_empty_body.mds").to_str().unwrap(),
            "-o",
            "-",
            "--quiet",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(output.status.success(), "quiet build should succeed");
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.is_empty(),
        "quiet flag should suppress the empty-include warning, got: {stderr}"
    );
}

#[test]
fn include_empty_body_emits_warning() {
    // Per spec 4.8: @include of a module with no body text should emit a warning
    // to stderr (when not in quiet mode).
    let output = mds_bin()
        .args([
            "build",
            fixture("include_empty_body.mds").to_str().unwrap(),
            "-o",
            "-",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "build should succeed even when include is empty"
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.contains("warning") && stderr.contains("fns"),
        "expected warning about empty @include on stderr, got: {stderr}"
    );
}

// ── I1-I7: duplicate --set / --set-string warnings (issue #200) ──────────────

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

// Pinned warning strings — a USER-FACING CONTRACT.
const DUP_SET_WARNING: &str =
    "warning: variable 'x' is set more than once by --set; the last value wins";
const DUP_SET_STRING_WARNING: &str =
    "warning: variable 'x' is set more than once by --set-string; the last value wins";

#[test]
fn i1_set_duplicate_warns_exactly_once_on_stderr() {
    // I1: mds build with --set x=1 --set x=2 must produce the warning exactly once.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    std::fs::write(&src, "Hello world").unwrap();

    let output = mds_bin()
        .args([
            "build",
            src.to_str().unwrap(),
            "-o",
            "-",
            "--set",
            "x=1",
            "--set",
            "x=2",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "build with duplicate --set must succeed"
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    let count = count_occurrences(&stderr, DUP_SET_WARNING);
    assert_eq!(
        count, 1,
        "I1: expected warning exactly once, found {count} times; stderr:\n{stderr}"
    );
}

#[test]
fn i2_set_string_duplicate_warns_exactly_once_on_stderr() {
    // I2: mds build with --set-string x=a --set-string x=b must produce the warning
    // exactly once.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    std::fs::write(&src, "Hello world").unwrap();

    let output = mds_bin()
        .args([
            "build",
            src.to_str().unwrap(),
            "-o",
            "-",
            "--set-string",
            "x=a",
            "--set-string",
            "x=b",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "build with duplicate --set-string must succeed"
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    let count = count_occurrences(&stderr, DUP_SET_STRING_WARNING);
    assert_eq!(
        count, 1,
        "I2: expected warning exactly once, found {count} times; stderr:\n{stderr}"
    );
}

#[test]
fn i3_quiet_suppresses_duplicate_warning() {
    // I3: --quiet must suppress the duplicate-key warning.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    std::fs::write(&src, "Hello world").unwrap();

    let output = mds_bin()
        .args([
            "build",
            src.to_str().unwrap(),
            "-o",
            "-",
            "--set",
            "x=1",
            "--set",
            "x=2",
            "--quiet",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(output.status.success(), "quiet build must succeed");
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        !stderr.contains(DUP_SET_WARNING),
        "I3: --quiet must suppress duplicate-key warning; got stderr:\n{stderr}"
    );
}

#[test]
fn i4_check_parity_with_build() {
    // I4: mds check must emit the same duplicate-key warning as mds build.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    std::fs::write(&src, "Hello world").unwrap();

    let output = mds_bin()
        .args([
            "check",
            src.to_str().unwrap(),
            "--set",
            "x=1",
            "--set",
            "x=2",
        ])
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "check with duplicate --set must succeed"
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    let count = count_occurrences(&stderr, DUP_SET_WARNING);
    assert_eq!(
        count, 1,
        "I4: check must warn exactly once; found {count} times; stderr:\n{stderr}"
    );
}

#[test]
fn i5_lint_parity_with_build() {
    // I5: mds lint must emit the same duplicate-key warning as mds build.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    std::fs::write(&src, "Hello world").unwrap();

    let output = mds_bin()
        .args([
            "lint",
            src.to_str().unwrap(),
            "--set",
            "x=1",
            "--set",
            "x=2",
        ])
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    // lint exits 0 when no lint findings (content has no issues).
    assert!(
        output.status.success(),
        "lint with duplicate --set must succeed (no lint errors); stderr:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    let count = count_occurrences(&stderr, DUP_SET_WARNING);
    assert_eq!(
        count, 1,
        "I5: lint must warn exactly once; found {count} times; stderr:\n{stderr}"
    );
}

#[test]
fn i6_triple_repeat_warns_exactly_once() {
    // I6: three repetitions of the same key must still produce exactly one warning.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    std::fs::write(&src, "Hello world").unwrap();

    let output = mds_bin()
        .args([
            "build",
            src.to_str().unwrap(),
            "-o",
            "-",
            "--set",
            "x=1",
            "--set",
            "x=2",
            "--set",
            "x=3",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "build with triple --set must succeed"
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    let count = count_occurrences(&stderr, DUP_SET_WARNING);
    assert_eq!(
        count, 1,
        "I6: triple repeat must still produce exactly one warning; found {count}; stderr:\n{stderr}"
    );
}

#[test]
fn i7_hostile_key_is_wire_escaped_in_warning() {
    // I7: a key containing an ESC byte (U+001B) and an RLO (U+202E) must appear in
    // the warning with those codepoints replaced by their \uXXXX escape sequences,
    // never as raw control bytes.
    //
    // PF-018: authoring control-character strings with an LLM agent silently decodes
    // \uXXXX 4-hex sequences to live bytes.  Use Rust braced escapes (\u{1b},
    // \u{202e}) — the editor layer does NOT decode those.
    //
    // The hostile key is: ESC (U+001B) followed by "[31m" followed by RLO (U+202E).
    // Built from char literals to avoid any tool-layer decoding.
    let esc: char = '\u{1b}';
    let rlo: char = '\u{202e}';
    let hostile_key = format!("{esc}[31m{rlo}");

    // The expected ESCAPED forms as literal backslash sequences in the warning.
    // Written as escaped-backslash Rust string literals so the tool layer has no
    // 4-hex sequence to decode.
    let expected_esc_form = "\\u001B"; // six-char: backslash + u001B
    let expected_rlo_form = "\\u202E"; // six-char: backslash + u202E

    let arg_set_first = format!("{hostile_key}=1");
    let arg_set_second = format!("{hostile_key}=2");

    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    std::fs::write(&src, "Hello world").unwrap();

    let output = mds_bin()
        .args([
            "build",
            src.to_str().unwrap(),
            "-o",
            "-",
            "--set",
            &arg_set_first,
            "--set",
            &arg_set_second,
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "build with hostile key must succeed"
    );
    let stderr = String::from_utf8(output.stderr).unwrap();

    // PF-013 NON-VACUITY FIRST: assert the escaped form IS present before asserting
    // absence of raw control bytes.  A test that only asserts absence passes trivially
    // if the feature never ran.
    assert!(
        stderr.contains(expected_esc_form),
        "I7: expected escaped ESC form '{}' in stderr; got:\n{:?}",
        expected_esc_form,
        stderr
    );
    assert!(
        stderr.contains(expected_rlo_form),
        "I7: expected escaped RLO form '{}' in stderr; got:\n{:?}",
        expected_rlo_form,
        stderr
    );

    // Now assert the raw control bytes are absent.
    assert_no_control_chars(&stderr, "I7 stderr");
}

// ── I10-I15: duplicate --vars file key warnings (#326) ───────────────────────

#[test]
fn i10_vars_file_duplicate_key_warns_exactly_once_on_build() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    let vars = dir.path().join("vars.json");
    std::fs::write(&src, "Hello world").unwrap();
    std::fs::write(&vars, r#"{"x": 1, "x": 2}"#).unwrap();

    let output = mds_bin()
        .args([
            "build",
            src.to_str().unwrap(),
            "-o",
            "-",
            "--vars",
            vars.to_str().unwrap(),
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "I10: build with duplicate vars-file key must succeed"
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    let expected = dup_vars_file_warning("x", &vars);
    let count = count_occurrences(&stderr, &expected);
    assert_eq!(
        count, 1,
        "I10: expected warning exactly once, found {count} times; stderr:\n{stderr}"
    );
}

#[test]
fn i11_quiet_suppresses_vars_file_duplicate_warning() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    let vars = dir.path().join("vars.json");
    std::fs::write(&src, "Hello world").unwrap();
    std::fs::write(&vars, r#"{"x": 1, "x": 2}"#).unwrap();

    let output = mds_bin()
        .args([
            "build",
            src.to_str().unwrap(),
            "-o",
            "-",
            "--vars",
            vars.to_str().unwrap(),
            "--quiet",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(output.status.success(), "I11: quiet build must succeed");
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.is_empty(),
        "I11: --quiet must suppress the duplicate vars-file warning, got: {stderr}"
    );
}

#[test]
fn i12_vars_file_duplicate_key_warns_on_check() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    let vars = dir.path().join("vars.json");
    std::fs::write(&src, "Hello world").unwrap();
    std::fs::write(&vars, r#"{"x": 1, "x": 2}"#).unwrap();

    let output = mds_bin()
        .args([
            "check",
            src.to_str().unwrap(),
            "--vars",
            vars.to_str().unwrap(),
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(output.status.success(), "I12: check must succeed");
    let stderr = String::from_utf8(output.stderr).unwrap();
    let expected = dup_vars_file_warning("x", &vars);
    assert_eq!(
        count_occurrences(&stderr, &expected),
        1,
        "I12: check must warn exactly once for a duplicate vars-file key; stderr:\n{stderr}"
    );
}

#[test]
fn i13_vars_file_duplicate_key_warns_on_lint() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    let vars = dir.path().join("vars.json");
    std::fs::write(&src, "Hello world").unwrap();
    std::fs::write(&vars, r#"{"x": 1, "x": 2}"#).unwrap();

    let output = mds_bin()
        .args([
            "lint",
            src.to_str().unwrap(),
            "--vars",
            vars.to_str().unwrap(),
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(output.status.success(), "I13: lint must succeed");
    let stderr = String::from_utf8(output.stderr).unwrap();
    let expected = dup_vars_file_warning("x", &vars);
    assert_eq!(
        count_occurrences(&stderr, &expected),
        1,
        "I13: lint must warn exactly once for a duplicate vars-file key; stderr:\n{stderr}"
    );
}

#[test]
fn i14_vars_file_triple_repeat_warns_once() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    let vars = dir.path().join("vars.json");
    std::fs::write(&src, "Hello world").unwrap();
    std::fs::write(&vars, r#"{"x": 1, "x": 2, "x": 3}"#).unwrap();

    let output = mds_bin()
        .args([
            "build",
            src.to_str().unwrap(),
            "-o",
            "-",
            "--vars",
            vars.to_str().unwrap(),
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(output.status.success(), "I14: build must succeed");
    let stderr = String::from_utf8(output.stderr).unwrap();
    let expected = dup_vars_file_warning("x", &vars);
    assert_eq!(
        count_occurrences(&stderr, &expected),
        1,
        "I14: triple repeat must still produce exactly one warning; stderr:\n{stderr}"
    );
}

#[test]
fn i15_hostile_vars_file_key_is_wire_escaped_in_warning() {
    // Mirrors i7: a key containing an ESC byte (U+001B) and an RLO (U+202E) must
    // appear in the warning with those codepoints replaced by their \uXXXX escape
    // sequences, never as raw control bytes.
    //
    // The vars FILE must spell these as JSON \u escapes (a raw control byte is not
    // legal inside a JSON string). The escape text is built via `format!` with a
    // hex-formatted integer, never as a literal 4-hex \uXXXX sequence in this
    // source file, so the editor tool layer has nothing to decode (PF-018).
    let esc_json_escape = format!("\\u{:04x}", 0x1bu32);
    let rlo_json_escape = format!("\\u{:04x}", 0x202eu32);
    let hostile_key_in_json = format!("{esc_json_escape}[31m{rlo_json_escape}");

    // The expected ESCAPED forms as they appear in the sanitized warning output.
    let expected_esc_form = "\\u001B";
    let expected_rlo_form = "\\u202E";

    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    let vars = dir.path().join("vars.json");
    std::fs::write(&src, "Hello world").unwrap();
    let vars_json = format!(r#"{{"{hostile_key_in_json}": 1, "{hostile_key_in_json}": 2}}"#);
    std::fs::write(&vars, vars_json).unwrap();

    let output = mds_bin()
        .args([
            "build",
            src.to_str().unwrap(),
            "-o",
            "-",
            "--vars",
            vars.to_str().unwrap(),
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "I15: build with hostile vars-file key must succeed"
    );
    let stderr = String::from_utf8(output.stderr).unwrap();

    // PF-013 NON-VACUITY FIRST: assert the escaped form IS present before asserting
    // absence of raw control bytes.
    assert!(
        stderr.contains(expected_esc_form),
        "I15: expected escaped ESC form '{expected_esc_form}' in stderr; got:\n{stderr:?}"
    );
    assert!(
        stderr.contains(expected_rlo_form),
        "I15: expected escaped RLO form '{expected_rlo_form}' in stderr; got:\n{stderr:?}"
    );

    // Now assert the raw control bytes are absent.
    assert_no_control_chars(&stderr, "I15 stderr");
}

#[test]
fn i15b_hostile_vars_file_key_with_newline_is_wire_escaped() {
    // i15 uses ESC (U+001B) and RLO (U+202E), which HUMAN and WIRE escape
    // identically (per sanitize_control_chars_wire/sanitize_control_chars:
    // "everything else escapes identically in both modes" except the newline
    // character) — so i15 cannot tell `safe_inline(key)` apart from a bare
    // `key`; the outer `eprint_warning` HUMAN pass masks the difference. The
    // newline is the one code point where WIRE differs from HUMAN: HUMAN
    // keeps a real newline byte (a forged second stderr line), WIRE escapes
    // it to the 6-character uppercase-hex literal form (see
    // `sanitize_control_chars_wire`'s own doctest, which pins this exact
    // escaped form for a newline). This test pins that WIRE escaping at the
    // interpolation site, independently of whatever the outer eprint_warning
    // pass does.
    //
    // The vars file key is written as a raw string containing the JSON escape
    // sequence \n (two ASCII characters: backslash, n) inside the JSON text —
    // NOT a real newline byte, and never a literal 4-hex \uXXXX sequence in
    // this .rs source (PF-018). serde_json decodes that JSON escape to a real
    // LF byte in the parsed key.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    let vars = dir.path().join("vars.json");
    std::fs::write(&src, "Hello world").unwrap();
    std::fs::write(&vars, r#"{"a\nb": 1, "a\nb": 2}"#).unwrap();

    let output = mds_bin()
        .args([
            "build",
            src.to_str().unwrap(),
            "-o",
            "-",
            "--vars",
            vars.to_str().unwrap(),
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "I15b: build with a newline-in-key vars file must succeed"
    );
    let stderr = String::from_utf8(output.stderr).unwrap();

    // PF-013 NON-VACUITY FIRST: the exact pinned warning line, with the key
    // rendered via the 6-character uppercase-hex escape for the newline
    // (never a real LF byte), appears exactly once. A weaker check such as
    // `stderr.contains("\\u000A")` alone would not be specific enough — this
    // asserts the whole pinned line renders correctly, key and all.
    let escaped_key = "a\\u000Ab";
    let expected = dup_vars_file_warning(escaped_key, &vars);
    assert_eq!(
        count_occurrences(&stderr, &expected),
        1,
        "I15b: expected the exact pinned warning line with the key WIRE-escaped \
         as {escaped_key:?}; got stderr:\n{stderr:?}"
    );

    // If a raw LF reached eprint_warning unescaped, the key's real newline
    // would forge a second stderr line whose text starts with the tail of the
    // key ("b' is set more than once..."). Assert no real-newline-delimited
    // line looks like that forged fragment — this fails if a raw LF were
    // emitted mid-line, independently of the exact-line check above.
    for line in stderr.lines() {
        assert!(
            !line.starts_with("b'"),
            "I15b: a stderr line looks like the forged tail of a raw-LF-split \
             hostile key (line: {line:?}); this would only happen if a raw LF \
             reached eprint_warning unescaped; full stderr:\n{stderr:?}"
        );
    }

    assert_no_control_chars(&stderr, "I15b stderr");
}

// ── R2: @include warning precision ───────────────────────────────────────────

#[test]
fn r2_include_export_hides_prompt_warns_about_export_list() {
    // include_export_hides_prompt.mds imports a module that HAS body text but
    // whose @export list excludes "prompt".  The warning should mention the
    // exports list, NOT say "no body text".
    let output = mds_bin()
        .args([
            "build",
            "-o",
            "-",
            fixture("include_export_hides_prompt.mds").to_str().unwrap(),
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "build of include_export_hides_prompt.mds should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    // Warning should be present.
    assert!(
        stderr.contains("empty output"),
        "R2: expected 'empty output' warning; got: {stderr:?}"
    );
    // WARN-B: mentions the exports list.
    assert!(
        stderr.contains("does not export") || stderr.contains("@export list"),
        "R2: WARN-B must mention the @export list; got: {stderr:?}"
    );
    // WARN-B must NOT say "no body text".
    assert!(
        !stderr.contains("no body text"),
        "R2: WARN-B must NOT say 'no body text'; got: {stderr:?}"
    );
    assert_no_control_chars(&stderr, "R2 warning line");
}