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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
mod common;
use common::{
    alias_bomb, assert_no_control_chars, fixture, fm_of_size, make_symlink, mds_bin,
    nested_flow_seq, wrap, MAX_FRONTMATTER_SIZE,
};
use std::collections::HashMap;

#[test]
#[cfg(unix)]
fn check_directory_refuses_a_file_replaced_after_walk() {
    let src = tempfile::tempdir().unwrap();
    std::fs::write(src.path().join("page.mds"), "Original\n").unwrap();
    std::fs::write(src.path().join("good.mds"), "Good\n").unwrap();
    let output = common::run_after_walk(mds_bin().arg("check").arg(src.path()), || {
        std::fs::rename(src.path().join("page.mds"), src.path().join("saved.txt")).unwrap();
        std::fs::write(src.path().join("page.mds"), "Replacement\n").unwrap();
    });
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(output.status.code(), Some(2), "{stderr}");
    assert!(
        stderr.contains("mds::io") && stderr.contains("file changed"),
        "{stderr}"
    );
    assert!(stderr.contains("1 passed, 1 failed"), "{stderr}");
    assert!(output.stdout.is_empty());
}

#[test]
fn check_directory_refuses_a_parent_redirected_after_walk() {
    let src = tempfile::tempdir().unwrap();
    let sub = src.path().join("sub");
    let moved = src.path().join("moved");
    std::fs::create_dir(&sub).unwrap();
    std::fs::write(sub.join("page.mds"), "Original\n").unwrap();
    if !make_symlink(&sub, &src.path().join("probe")) {
        return;
    }
    let output = common::run_after_walk(mds_bin().arg("check").arg(src.path()), || {
        std::fs::rename(&sub, &moved).unwrap();
        assert!(make_symlink(&moved, &sub));
    });
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(output.status.code(), Some(2), "{stderr}");
    assert!(
        stderr.contains("mds::io") && stderr.contains("file changed"),
        "{stderr}"
    );
    assert!(stderr.contains("0 passed, 1 failed"), "{stderr}");
    assert!(output.stdout.is_empty());
}

#[test]
fn check_directory_accepts_an_unchanged_tree_after_walk() {
    let src = tempfile::tempdir().unwrap();
    std::fs::create_dir(src.path().join("sub")).unwrap();
    std::fs::write(src.path().join("sub/page.mds"), "Original\n").unwrap();
    let output = common::run_after_walk(mds_bin().arg("check").arg(src.path()), || {});
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(output.status.success(), "{stderr}");
    assert!(stderr.contains("1 passed, 0 failed"), "{stderr}");
    assert!(output.stdout.is_empty());
}

#[test]
fn file_size_limit_rejects_huge_file() {
    let dir = tempfile::tempdir().unwrap();
    let huge = dir.path().join("huge.mds");
    // Create a file just over 10MB
    let content = "x".repeat(10 * 1024 * 1024 + 1);
    std::fs::write(&huge, &content).unwrap();
    let result = mds::compile(&huge, None);
    assert!(result.is_err());
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("file too large"),
        "Expected 'file too large' error, got: {err}"
    );
}

#[test]
fn path_traversal_import_rejected() {
    let dir = tempfile::tempdir().unwrap();
    let sub = dir.path().join("sub");
    std::fs::create_dir(&sub).unwrap();

    // Create a file outside 'sub' directory
    let outside = dir.path().join("secret.mds");
    std::fs::write(&outside, "Secret content").unwrap();

    // Create a file inside 'sub' that tries to import outside its root
    let child = sub.join("child.mds");
    std::fs::write(&child, "@import \"../secret.mds\" as s\n\n@include s\n").unwrap();

    let result = mds::compile(&child, None);
    assert!(result.is_err(), "Traversal import should be rejected");
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("escapes project directory") || err.contains("import"),
        "Expected path traversal error, got: {err}"
    );
}

#[test]
fn import_depth_limit() {
    let dir = tempfile::tempdir().unwrap();
    // Create a chain of 66 files, each importing the next
    let depth = 66;
    for i in 0..depth {
        let name = format!("mod_{i}.mds");
        let content = if i < depth - 1 {
            let next = format!("mod_{}.mds", i + 1);
            format!("@import \"./{next}\" as m{}\n\nLevel {i}\n", i + 1)
        } else {
            format!("End of chain {i}\n")
        };
        std::fs::write(dir.path().join(&name), content).unwrap();
    }
    let result = mds::compile(dir.path().join("mod_0.mds"), None);
    assert!(result.is_err(), "Deep import chain should be rejected");
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("import depth") || err.contains("64"),
        "Expected import depth error, got: {err}"
    );
}

#[test]
fn stdin_size_limit_rejects_oversized_input() {
    // Feed more than 10 MiB to stdin: the CLI refuses it as a resource limit, exit 3,
    // like a file over the same cap (#157).
    use std::io::Write;

    let oversized: Vec<u8> = vec![b'x'; 10 * 1024 * 1024 + 1];

    let mut child = mds_bin()
        .args(["build", "-"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .unwrap();

    // Write oversized data; ignore broken-pipe errors (process may exit early).
    if let Some(mut stdin) = child.stdin.take() {
        let _ = stdin.write_all(&oversized);
    }

    let output = child.wait_with_output().unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code(),
        Some(3),
        "build from oversized stdin must exit 3; stderr: {stderr}"
    );
    assert!(
        stderr.contains("mds::resource_limit")
            && stderr.contains("stdin input exceeds maximum size of 10 MiB"),
        "error should be mds::resource_limit and mention the size limit, got: {stderr}"
    );
}

#[test]
fn vars_file_size_limit_rejects_oversized_file() {
    let dir = tempfile::tempdir().unwrap();
    let huge_vars = dir.path().join("huge_vars.json");

    // Create a JSON file just over 10 MB (fill a JSON object with long values)
    let mut content = String::from("{\"key\": \"");
    content.push_str(&"x".repeat(10 * 1024 * 1024));
    content.push_str("\"}");
    std::fs::write(&huge_vars, &content).unwrap();

    let result = mds::load_vars_file(&huge_vars);
    assert!(result.is_err(), "oversized vars file must be rejected");
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("exceeds maximum size") || err.contains("vars file"),
        "error should mention vars file size limit, got: {err}"
    );
}

#[test]
fn for_loop_iteration_limit_rejects_huge_array() {
    // Build a source that iterates over an array larger than MAX_LOOP_ITERATIONS (100_000).
    // We construct the array via runtime vars to avoid a huge source string.
    let huge_array: Vec<mds::Value> = (0..100_001)
        .map(|i| mds::Value::String(format!("item{i}")))
        .collect();
    let mut vars = HashMap::new();
    vars.insert("items".to_string(), mds::Value::Array(huge_array));

    let result = mds::compile(fixture("loop.mds"), Some(vars));
    assert!(result.is_err(), "loop over 100_001 items must be rejected");
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("exceeding maximum loop iteration limit")
            || err.contains("100001")
            || err.contains("100_001"),
        "error should mention iteration limit, got: {err}"
    );
}

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

    // Create a real .mds file to be the symlink target
    let real_file = dir.path().join("real.mds");
    std::fs::write(&real_file, "@define greet(name):\nHello {{name}}!\n@end\n").unwrap();

    // Create a symlink pointing to it
    let link_file = dir.path().join("linked.mds");
    if !make_symlink(&real_file, &link_file) {
        return;
    }

    // Create a consumer that imports via the symlink
    let consumer = dir.path().join("consumer.mds");
    std::fs::write(
        &consumer,
        "@import { greet } from \"./linked.mds\"\n{{greet(\"Alice\")}}\n",
    )
    .unwrap();

    let result = mds::compile(&consumer, None);
    assert!(result.is_err(), "import via symlink must be rejected");
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("symlink") || err.contains("not allowed"),
        "error should mention symlink restriction, got: {err}"
    );
}

/// #408: a mismatched spelling of an entry file or an import is resolved the way
/// the OS resolves it — on a case-insensitive volume (default macOS APFS, NTFS on
/// the Windows CI leg) it builds, on a case-sensitive one (Linux) it is a missing
/// file (exit 2). It is never reported as a symlink. The volume is probed, not
/// assumed.
#[test]
fn case_mismatched_entry_and_import_are_not_symlink_errors() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("entry.mds"), "Hello!\n").unwrap();
    std::fs::write(dir.path().join("header.mds"), "@define hi():\nHi\n@end\n").unwrap();
    std::fs::write(
        dir.path().join("main.mds"),
        "@import \"./Header.mds\" as h\n{{h.hi()}}\n",
    )
    .unwrap();
    std::fs::write(dir.path().join("probe.txt"), "").unwrap();
    let insensitive = dir.path().join("PROBE.TXT").exists();

    // (argument, stdout on a case-insensitive volume)
    for (arg, expected) in [("Entry.mds", "Hello!\n"), ("main.mds", "Hi\n")] {
        let out = mds_bin()
            .args(["build", arg, "-o", "-"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            !stderr.contains("symlink"),
            "{arg}: a case mismatch must never be a symlink error: {stderr}"
        );
        if insensitive {
            assert!(out.status.success(), "{arg}: {stderr}");
            assert_eq!(String::from_utf8_lossy(&out.stdout), expected, "{arg}");
        } else {
            assert_eq!(out.status.code(), Some(2), "{arg}: {stderr}");
            assert!(stderr.contains("file not found"), "{arg}: {stderr}");
        }
    }
}

#[test]
fn nested_loop_total_iteration_limit() {
    // Two nested loops of 1001 × 1000 = 1,001,000 total iterations must be rejected.
    // Build the source inline: outer array has 1001 elements, inner has 1000.
    let outer: Vec<String> = (0..1001).map(|i| format!("o{i}")).collect();
    let inner: Vec<String> = (0..1000).map(|i| format!("i{i}")).collect();
    let outer_yaml = outer.join(", ");
    let inner_yaml = inner.join(", ");
    let source = format!(
        "---\nouter: [{outer_yaml}]\ninner: [{inner_yaml}]\n---\n@for x in outer:\n@for y in inner:\n{{x}}-{{y}}\n@end\n@end\n"
    );
    let result = mds::compile_str_with(&source, None, None);
    assert!(
        result.is_err(),
        "nested loops exceeding 1M total iterations must be rejected"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("total loop iterations") || err.contains("1000000"),
        "error should mention total iteration limit, got: {err}"
    );
}

#[test]
fn nested_loop_under_total_iteration_limit() {
    // With unconditional iteration counting, every iteration across all loops counts.
    // 999 outer × 1000 inner = 999,000 inner iterations + 999 outer = 999,999 total.
    // This stays under MAX_TOTAL_ITERATIONS (1,000,000) and must succeed.
    let outer: Vec<String> = (0..999).map(|i| format!("o{i}")).collect();
    let inner: Vec<String> = (0..1000).map(|i| format!("i{i}")).collect();
    let outer_yaml = outer.join(", ");
    let inner_yaml = inner.join(", ");
    let source = format!(
        "---\nouter: [{outer_yaml}]\ninner: [{inner_yaml}]\n---\n@for x in outer:\n@for y in inner:\nx\n@end\n@end\n"
    );
    let result = mds::compile_str_with(&source, None, None);
    assert!(
        result.is_ok(),
        "nested loops under 1M total iterations must succeed, got: {:?}",
        result.unwrap_err()
    );
}

#[test]
fn resolve_source_nonexistent_base_dir_errors() {
    // Passing a non-existent base_dir to compile_str_with must now return an error
    // (previously silently fell back to the raw path).
    let nonexistent_dir = std::path::Path::new("/nonexistent/path/that/does/not/exist");
    let result = mds::compile_str_with(
        "---\nname: World\n---\nHello {{name}}!\n",
        Some(nonexistent_dir),
        None,
    );
    assert!(
        result.is_err(),
        "non-existent base_dir must now return an error"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("cannot resolve base directory") || err.contains("nonexistent"),
        "error should describe the unresolvable base directory, got: {err}"
    );
}

#[test]
fn resolve_source_import_traversal_rejected() {
    // Security invariant (AC-S2): the string + base_dir route must reject a
    // relative `@import` that escapes `base_dir` via `../`, exactly like the
    // file route (`path_traversal_import_rejected` above). Regression guard for
    // PF-003 / #133 / #146 directory-anchored resolution — `ctx.base_dir` still
    // routes through the same path-traversal check (`check_path_traversal`).
    let dir = tempfile::tempdir().unwrap();
    let sub = dir.path().join("sub");
    std::fs::create_dir(&sub).unwrap();

    // Create a file outside the 'sub' base_dir.
    let outside = dir.path().join("secret.mds");
    std::fs::write(&outside, "Secret content").unwrap();

    let source = "@import \"../secret.mds\" as s\n\n@include s\n";
    let result = mds::compile_str_with(source, Some(sub.as_path()), None);
    assert!(
        result.is_err(),
        "string-route traversal import should be rejected"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("escapes project directory") || err.contains("import"),
        "Expected path traversal error, got: {err}"
    );
}

#[test]
fn parser_nesting_depth_limit_rejects_deep_nesting() {
    // Build a template with 65 nested @if blocks (just past MAX_NESTING_DEPTH=64).
    //
    // 65 levels is well within the default 2 MB thread stack, so no enlarged
    // stack is required. The depth limit error must fire before any stack overflow.
    let mut source = String::new();
    source.push_str("---\nflag: true\n---\n");
    for _ in 0..65 {
        source.push_str("@if flag:\n");
    }
    source.push_str("deep\n");
    for _ in 0..65 {
        source.push_str("@end\n");
    }

    let result = mds::compile_str(&source);
    assert!(result.is_err(), "65 nested @if blocks must be rejected");
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("nesting") || err.contains("depth") || err.contains("64"),
        "error should mention nesting depth limit, got: {err}"
    );
}

#[test]
fn build_mds_json_output_dir_path_traversal_rejected() {
    // mds.json with `output_dir` containing `..` components must be rejected
    // by resolve_output_path to prevent writing files outside the project root.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "Hello!\n").unwrap();
    std::fs::write(
        dir.path().join("mds.json"),
        r#"{"build": {"output_dir": "../escaped"}}"#,
    )
    .unwrap();

    let output = mds_bin()
        .arg("build")
        .arg(&src)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    // `mds::io`, exit 2 (#265 moved it from exit 1).
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(output.status.code(), Some(2), "got: {stderr}");
    assert!(stderr.contains("mds::io"), "got: {stderr}");
    assert!(
        stderr.contains("mds.json output_dir '../escaped' must not contain '..' components"),
        "got: {stderr}"
    );
    assert!(!dir.path().parent().unwrap().join("escaped").exists());
}

#[test]
fn config_size_limit_rejects_oversized_mds_json() {
    // mds.json files larger than MAX_CONFIG_SIZE (1 MB) must be rejected to
    // prevent runaway memory use when walking up the directory tree.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "Hello!\n").unwrap();

    // Build a JSON file just over 1 MB by padding the output_dir value.
    let padding = "x".repeat(1024 * 1024);
    let huge_config = format!(r#"{{"build": {{"output_dir": "{padding}"}}}}"#);
    std::fs::write(dir.path().join("mds.json"), &huge_config).unwrap();

    let output = mds_bin()
        .arg("build")
        .arg(&src)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "build with oversized mds.json must fail"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("too large") || stderr.contains("1 MB") || stderr.contains("mds.json"),
        "error should mention config size limit, got: {stderr}"
    );
}

#[test]
fn exit_code_resource_limit() {
    // Trigger MAX_TOTAL_ITERATIONS (1,000,000) via two nested @for loops.
    // Outer array: 1,001 items × inner array: 1,001 items = 1,002,001 iterations.
    // Each individual loop stays well under MAX_LOOP_ITERATIONS (100,000), so
    // only MAX_TOTAL_ITERATIONS fires, producing MdsError::ResourceLimit → exit code 3.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("resource_limit.mds");

    // Build a YAML frontmatter array of 1,001 string items and a nested @for loop.
    let mut source = String::from("---\n");
    source.push_str("outer:\n");
    for i in 0..1001 {
        source.push_str(&format!("  - item{i}\n"));
    }
    source.push_str("inner:\n");
    for i in 0..1001 {
        source.push_str(&format!("  - sub{i}\n"));
    }
    source.push_str("---\n");
    source.push_str("@for x in outer:\n");
    source.push_str("@for y in inner:\n");
    source.push_str("{{x}}-{{y}}\n");
    source.push_str("@end\n");
    source.push_str("@end\n");

    std::fs::write(&src, &source).unwrap();

    let status = mds_bin()
        .args(["build"])
        .arg(&src)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("failed to run mds");

    assert_eq!(
        status.code(),
        Some(3),
        "expected exit code 3 for resource-limit error"
    );
}

/// #415 (a guard, no RED claim): a `@for` whose output crosses the 50 MiB
/// output cap exits 3 with the exact `mds::resource_limit` message and writes nothing.
/// The code and message are the same whether the cap is checked before each append or
/// after the loop, so this pins the CLI's reporting; where the loop stops is pinned in
/// mds-core (`for_loop_output_cap_stops_iterating`).
#[test]
fn for_loop_output_cap_exits_3() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("cap.mds");
    // 100 passes of 1 MiB + 1 bytes (the body line and its newline): the 50th pass
    // crosses 52,428,800 bytes. The source itself is ~1 MiB, under the 10 MiB file cap.
    let items = (0..100)
        .map(|i| i.to_string())
        .collect::<Vec<_>>()
        .join(", ");
    let body = "a".repeat(1024 * 1024);
    std::fs::write(
        &src,
        format!("---\nitems: [{items}]\n---\n@for i in items:\n{body}\n@end\n"),
    )
    .unwrap();

    let output = mds_bin()
        .arg("build")
        .arg(&src)
        .args(["-o", "-"])
        .output()
        .expect("failed to run mds");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(output.status.code(), Some(3), "stderr: {stderr}");
    assert!(
        stderr.contains("mds::resource_limit"),
        "stderr must name the resource limit: {stderr}"
    );
    // miette word-wraps the diagnostic and prefixes continuation lines with `│`; flatten
    // that back to a single line before matching the full message.
    let flat: String = stderr
        .replace('│', " ")
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    assert!(
        flat.contains("output exceeds maximum size of 52428800 bytes"),
        "stderr must name the output cap: {stderr}"
    );
    assert!(
        output.stdout.is_empty(),
        "nothing may be written when the cap fires; got {} bytes",
        output.stdout.len()
    );
}

// ── Frontmatter YAML DoS bounds across the CLI (#162) ────────────────────────
//
// The alias bomb is the sub-1 MiB memory-amplification repro (n = m = 100 000,
// ~700 KB source): the source is under the 1 MiB size cap, so the node budget is what
// rejects it — fast, without materialising the tree. Every rejection is exit code 3
// (`mds::resource_limit`), never echoes the raw hostile bytes (`*a`, the sentinel, or a
// bracket run), and stays free of control characters.

/// The realistic memory-amplification repro, wrapped as a full `.mds` document.
fn bomb_doc() -> String {
    wrap(&alias_bomb(100_000, 100_000))
}

#[test]
fn cli_1_check_stdin_alias_bomb_is_resource_limit() {
    use std::io::Write;
    let mut child = mds_bin()
        .args(["check", "-"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .unwrap();
    if let Some(mut stdin) = child.stdin.take() {
        let _ = stdin.write_all(bomb_doc().as_bytes());
    }
    let output = child.wait_with_output().unwrap();
    assert_eq!(
        output.status.code(),
        Some(3),
        "alias bomb via `check -` must exit 3"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("mds::resource_limit"),
        "stderr must name the resource limit: {stderr}"
    );
    assert!(
        !stderr.contains("*a"),
        "stderr must not echo bomb content: {stderr}"
    );
    assert_no_control_chars(&stderr, "cli_1 check stdin bomb stderr");
}

#[test]
fn cli_2_check_file_alias_bomb_is_resource_limit() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("bomb.mds");
    std::fs::write(&src, bomb_doc()).unwrap();
    let output = mds_bin().arg("check").arg(&src).output().unwrap();
    assert_eq!(
        output.status.code(),
        Some(3),
        "alias bomb via `check <file>` must exit 3"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("mds::resource_limit"),
        "stderr must name the resource limit: {stderr}"
    );
    assert!(
        !stderr.contains("*a"),
        "stderr must not echo bomb content: {stderr}"
    );
    assert_no_control_chars(&stderr, "cli_2 check file bomb stderr");
}

#[test]
fn cli_3_check_over_size_cap_is_resource_limit_no_echo() {
    // Frontmatter one byte over the 1 MiB cap → rejected before any YAML work, and the
    // message must never echo the (arbitrarily large) frontmatter content.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("over.mds");
    std::fs::write(&src, wrap(&fm_of_size(MAX_FRONTMATTER_SIZE + 1))).unwrap();
    let output = mds_bin().arg("check").arg(&src).output().unwrap();
    assert_eq!(
        output.status.code(),
        Some(3),
        "over-cap frontmatter must exit 3"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("mds::resource_limit"),
        "stderr must name the resource limit: {stderr}"
    );
    assert!(
        !stderr.contains("ZZSENTINELZZ"),
        "stderr must not echo the frontmatter content: {stderr}"
    );
    assert_no_control_chars(&stderr, "cli_3 over-cap stderr");
}

#[test]
fn cli_3c_check_at_size_cap_is_accepted() {
    // At-cap control (PF-013): exactly 1 MiB of frontmatter is admitted.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("atcap.mds");
    std::fs::write(&src, wrap(&fm_of_size(MAX_FRONTMATTER_SIZE))).unwrap();
    let status = mds_bin()
        .arg("check")
        .arg(&src)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .unwrap();
    assert_eq!(
        status.code(),
        Some(0),
        "at-cap frontmatter must be accepted"
    );
}

#[test]
fn cli_4_lint_alias_bomb_is_resource_limit() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("bomb.mds");
    std::fs::write(&src, bomb_doc()).unwrap();
    let output = mds_bin().arg("lint").arg(&src).output().unwrap();
    assert_eq!(
        output.status.code(),
        Some(3),
        "lint on the bomb must exit 3"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("mds::resource_limit"),
        "stderr must name the resource limit: {stderr}"
    );
    assert!(
        !stderr.contains("*a"),
        "stderr must not echo bomb content: {stderr}"
    );
    assert_no_control_chars(&stderr, "cli_4 lint bomb stderr");
}

#[test]
fn cli_4c_lint_legit_aliases_is_clean() {
    // Positive control (PF-013): a legitimate anchor/alias with every frontmatter key
    // referenced in the body lints clean (exit 0) — the bounds do not over-reject.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("legit.mds");
    std::fs::write(&src, "---\na: &a [1, 2]\nb: *a\n---\n{{a}} {{b}}\n").unwrap();
    let status = mds_bin()
        .arg("lint")
        .arg(&src)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .unwrap();
    assert_eq!(status.code(), Some(0), "legit aliases must lint clean");
}

#[test]
fn cli_5_fmt_check_alias_bomb_leaves_file_byte_identical() {
    // `mds fmt --check` compiles the source to prove formatting equivalence. Post-fix the
    // compile rejects the bomb cleanly, the formatter falls back and reattaches the
    // frontmatter verbatim, so `--check` reports the file unchanged (exit 0) and the
    // on-disk bytes are untouched.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("bomb.mds");
    let original = bomb_doc();
    std::fs::write(&src, &original).unwrap();
    let status = mds_bin()
        .args(["fmt", "--check"])
        .arg(&src)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .unwrap();
    assert_eq!(
        status.code(),
        Some(0),
        "fmt --check on the bomb must exit 0"
    );
    let after = std::fs::read(&src).unwrap();
    assert_eq!(
        after,
        original.as_bytes(),
        "fmt --check must leave the bomb file byte-identical"
    );
}

#[test]
fn cli_deep_check_deep_flow_nest_is_resource_limit() {
    // The second DoS axis: pure deep flow-nesting (no anchors), a CPU hang in libyaml's
    // flow scanner pre-fix. The pre-parse depth guard rejects depth > 1024 fast, before
    // any scanner work, and the message names the flow-depth limit without echoing the
    // bracket run.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("deep.mds");
    std::fs::write(&src, wrap(&nested_flow_seq(2000))).unwrap();
    let start = std::time::Instant::now();
    let output = mds_bin().arg("check").arg(&src).output().unwrap();
    let elapsed = start.elapsed();
    assert_eq!(output.status.code(), Some(3), "deep flow nest must exit 3");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("mds::resource_limit"),
        "stderr must name the resource limit: {stderr}"
    );
    // miette word-wraps the diagnostic and prefixes continuation lines with `│`; flatten
    // that back to a single line before matching the full message.
    let flat: String = stderr
        .replace('│', " ")
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    assert!(
        flat.contains("flow nesting exceeds maximum depth of 1024"),
        "stderr must name the flow-depth limit: {stderr}"
    );
    assert!(
        !stderr.contains("[[[") && !stderr.contains("]]]"),
        "stderr must not echo the bracket run: {stderr}"
    );
    assert_no_control_chars(&stderr, "cli_deep stderr");
    assert!(
        elapsed < std::time::Duration::from_secs(5),
        "the guard must reject the deep nest pre-parse (fast), took {elapsed:?}"
    );
}

#[test]
fn cli_6_max_frontmatter_in_max_source_build_is_accepted() {
    // Both caps at their boundaries compose: a 1 MiB (at-cap) frontmatter inside a
    // source that is exactly 10 MiB (at MAX_FILE_SIZE) is accepted by `build -`.
    use std::io::Write;
    const MAX_FILE_SIZE: usize = 10 * 1024 * 1024;
    let head = wrap_open(&fm_of_size(MAX_FRONTMATTER_SIZE));
    let body_len = MAX_FILE_SIZE - head.len();
    let mut doc = head;
    doc.push_str(&"H".repeat(body_len - 1));
    doc.push('\n');
    assert_eq!(
        doc.len(),
        MAX_FILE_SIZE,
        "source must be exactly at MAX_FILE_SIZE"
    );

    let mut child = mds_bin()
        .args(["build", "-o", "-", "-"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .unwrap();
    if let Some(mut stdin) = child.stdin.take() {
        let _ = stdin.write_all(doc.as_bytes());
    }
    let status = child.wait().unwrap();
    assert_eq!(
        status.code(),
        Some(0),
        "1 MiB frontmatter inside a 10 MiB source must be accepted at both boundaries"
    );
}

/// `---\n{yaml}---\n` — the fenced header without a body, for size-composition tests.
fn wrap_open(yaml: &str) -> String {
    format!("---\n{yaml}---\n")
}

// ── AC-2: load_vars_file rejects symlinked vars paths (PF-004 fix) ───────────

#[test]
fn load_vars_file_rejects_symlinked_path() {
    // Proves the PF-004 fix: load_vars_file now routes the path through
    // NativeFs::check_symlink before reading, the same guard applied to every
    // other file read in the resolver.
    let dir = tempfile::tempdir().unwrap();

    let real_vars = dir.path().join("real_vars.json");
    std::fs::write(&real_vars, r#"{"name": "Alice"}"#).unwrap();

    let link_vars = dir.path().join("link_vars.json");
    if !make_symlink(&real_vars, &link_vars) {
        return;
    }

    let result = mds::load_vars_file(&link_vars);
    assert!(
        result.is_err(),
        "load_vars_file must reject a symlinked vars path"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("symlink") || err.contains("not allowed"),
        "error must mention symlink restriction; got: {err}"
    );
}

// ── CWE-150: control bytes in the error MESSAGE on the CLI human path (#176) ──
//
// The pre-existing ESC e2e tests in `cli_build.rs` / `cli_fmt.rs` / `cli_lint.rs`
// all use the `@define \x1bfoo:` vector, whose message is the *fixed* string
// "syntax error: @define must have parameter list: @define name(params):" — the
// hostile byte only ever reaches the rendered **source excerpt**, which
// `MdsError::at()` already neutralized. Those tests therefore never exercised the
// message text at all (PF-013: a hostile-input test that cannot fail for the
// reason it claims). The two tests below use vectors that put attacker-controlled
// bytes into the message itself, on both of the CLI's error families:
//
//   1. `MdsError` — `parser.rs` formats the raw alias into
//      `invalid include alias: '{alias}'`.
//   2. CLI-authored `miette::miette!()` — `build.rs`'s `auto_detect_mds_file` formats
//      the raw names of the `.mds` files in the working directory into
//      `multiple .mds files found: {names}`.
//
// Both render through `eprint_error`, the single CLI stderr choke-point.

/// T-ESC-MSG-1 [security-11 / CWE-150 / PF-013 / #176]: an `MdsError` whose message
/// interpolates attacker-controlled template text must reach stderr escaped.
///
/// Non-vacuity guard: the command must actually fail *and* stderr must contain the
/// expected error text, so the escape assertions cannot pass by the build silently
/// succeeding or failing for an unrelated reason.
#[test]
fn build_mds_error_message_escapes_control_bytes() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("inc.mds");
    // ESC (U+001B) and RIGHT-TO-LEFT OVERRIDE (U+202E) inside the include alias.
    // `is_valid_identifier` rejects it, and the raw alias is formatted into the message.
    std::fs::write(&src, "@include \u{1b}[31mBAD\u{202e}alias\n").unwrap();

    let out = mds_bin()
        .arg("build")
        .arg(&src)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    // ── Non-vacuity ──────────────────────────────────────────────────────────
    assert!(
        !out.status.success(),
        "build of an invalid include alias must fail"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("invalid include alias"),
        "non-vacuity: the alias error must be the one rendered; got: {stderr}"
    );

    // ── Negative: no raw hostile bytes survive ───────────────────────────────
    assert!(
        !out.stderr.contains(&0x1Bu8),
        "raw ESC byte (0x1B) must not reach stderr in the error message; got: {stderr}"
    );
    assert_no_control_chars(&stderr, "mds build MdsError message");

    // ── Positive: the escaped literals are present ───────────────────────────
    assert!(
        stderr.contains("\\u001B"),
        "ESC must be rendered as the \\u001B literal in the message; got: {stderr}"
    );
    assert!(
        stderr.contains("\\u202E"),
        "U+202E must be rendered as the \\u202E literal in the message; got: {stderr}"
    );
}

#[test]
fn conditional_syntax_reports_use_fixed_messages_and_safe_source_frames() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("conditional.mds");
    let esc = char::from(0x1b);
    let bidi = char::from_u32(0x202e).unwrap();
    let sample = format!("tag{esc}{bidi}tail");
    let opener = "```js +mds\n";
    let file_key = "---\r\nindented-directives: true\r\n---\r\n";

    for (before, line, after, message) in [
        (
            opener,
            format!("  @end {sample}"),
            "\n```\n",
            "conditional directive needs an open if in this code fence",
        ),
        (
            opener,
            format!("  @if x == \"{sample}\":"),
            "\n```\n",
            "conditional directive must end before the code fence closes",
        ),
        (
            "",
            format!("```js +{sample}"),
            "\n```\n",
            "invalid code fence info word",
        ),
        (
            file_key,
            format!("  {esc}{bidi}@if a:"),
            "\r\n",
            "invalid indent for a conditional directive",
        ),
    ] {
        std::fs::write(&path, format!("{before}{line}{after}")).unwrap();
        let human = mds_bin().arg("lint").arg(&path).output().unwrap();
        let stderr = String::from_utf8(human.stderr).unwrap();
        assert_eq!(human.status.code(), Some(2), "{stderr}");
        assert!(stderr.contains("mds::syntax"), "{stderr}");
        assert!(
            stderr.contains(&format!("syntax error: {message}")),
            "{stderr}"
        );
        let safe_line = line.replace(esc, "?").replace(bidi, "�");
        assert!(stderr.contains(safe_line.trim_start()), "{stderr:?}");
        assert!(!stderr.contains([esc, bidi]), "{stderr:?}");

        // The wire keeps the fixed message and byte span, not the source excerpt.
        let json = mds_bin()
            .args(["lint", "--format", "json"])
            .arg(&path)
            .output()
            .unwrap();
        let wire = String::from_utf8(json.stdout).unwrap();
        assert_eq!(json.status.code(), Some(2), "{wire}");
        assert!(!wire.contains([esc, bidi]), "{wire:?}");
        let document: serde_json::Value = serde_json::from_str(&wire).unwrap();
        assert_eq!(document["version"], 1);
        let error = &document["error"];
        assert_eq!(error["code"], "mds::syntax");
        assert_eq!(error["message"], format!("syntax error: {message}"));
        assert_eq!(error["help"], serde_json::Value::Null);
        assert_eq!(error["span"]["offset"], before.len());
        assert_eq!(error["span"]["length"], line.len());
    }
}

/// T-ESC-MSG-2 [security-11 / CWE-150 / PF-004 / #176]: a CLI-authored
/// `miette::miette!()` error that interpolates attacker-controlled text must reach
/// stderr escaped too.
///
/// This is the PF-004 sibling path: `miette!()` reports do **not** downcast to
/// `MdsError` (see `exit_code`'s rustdoc), so a fix that only handled `MdsError`
/// would leave this vector open while claiming the boundary was closed.
///
/// No `mds.json` value reaches a `miette!()` message raw: a forbidden `output_dir` is
/// refused as `mds::io` (#265, `output_dir_in_mds_json_is_refused_at_load` in
/// `forbidden_paths.rs`), and an unknown lint severity's message names the rule and the
/// value WIRE-escaped as it is built (#175,
/// `mds_json_severity_goes_through_the_one_severity_parser` in `cli_build.rs`). So the
/// vector is a file name: with no argument, `mds build` looks for the one `.mds` file
/// in its working directory, and when there are several its error names them all, as
/// they are on disk.
#[test]
fn build_cli_authored_error_message_escapes_control_bytes() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("a.mds"), "Hello!\n").unwrap();
    // RIGHT-TO-LEFT OVERRIDE (U+202E), and ESC where the OS allows it in a file name
    // (Windows does not). Built at runtime (PF-018).
    let hostile = if cfg!(windows) {
        format!("BAD{}x.mds", '\u{202e}')
    } else {
        format!("{}[31mBAD{}x.mds", '\x1b', '\u{202e}')
    };
    std::fs::write(dir.path().join(&hostile), "Hello!\n").unwrap();

    let out = mds_bin()
        .arg("build")
        .current_dir(dir.path())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    // ── Non-vacuity: the CLI-authored error (exit 1, no `mds::` code) is the one
    //    rendered, and it names both files ────────────────────────────────────
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert_eq!(out.status.code(), Some(1), "got: {stderr}");
    assert!(
        stderr.contains("multiple .mds files found") && stderr.contains("a.mds"),
        "non-vacuity: the auto-detect error must be the one rendered; got: {stderr}"
    );
    assert!(
        !stderr.contains("mds::"),
        "a miette!() error carries no code: {stderr}"
    );

    // ── Negative + positive ──────────────────────────────────────────────────
    assert!(
        !out.stderr.contains(&0x1Bu8),
        "raw ESC byte (0x1B) must not reach stderr from a miette!() message; got: {stderr}"
    );
    assert_no_control_chars(&stderr, "mds build miette!() message");
    assert!(
        stderr.contains("\\u202E"),
        "U+202E must be rendered as the \\u202E literal; got: {stderr}"
    );
    if !cfg!(windows) {
        assert!(
            stderr.contains("\\u001B"),
            "ESC must be rendered as the \\u001B literal; got: {stderr}"
        );
    }
}

// ── S14 / PF-004: the two boundaries the #176 alignment review found still open ──
//
// Both are reproduced-first vectors: on the pre-fix binary each command below emits
// the raw hostile bytes (verified with `od -c`).

/// T-ESC-RULE-1 [security-11 / CWE-150 / PF-004 / PF-013 / #176 / AC-224-4 / AC-224-5]:
/// an unknown lint rule NAME from `mds.json` reaches stderr escaped; lint warns and
/// continues rather than hard-failing.
///
/// Vector: `mds.json` is read from the working tree and its rule names are arbitrary
/// JSON object keys. A JSON `\uXXXX` escape decodes to a real byte, so a repository can
/// carry a rule name containing a raw ESC without the file itself looking hostile.
/// This print site sat on a bare `eprintln!`, bypassing both `eprint_error` and
/// `eprint_warning` — the "sixth warning print" that `eprint_warning`'s own rustdoc
/// claimed was foreclosed.
///
/// `serde_json` writes the ESC as a LOWERCASE-hex JSON escape; the sanitizer emits
/// UPPERCASE. Asserting the uppercase form proves the byte genuinely decoded on the way
/// in and was genuinely escaped on the way out, rather than passing through as literal
/// text.
///
/// The vector also carries **newlines**, and the assertions below include a standalone
/// forged-line check. That combination is deliberate: routing this print through
/// `eprint_warning` closed CWE-150 on this vector (no raw control byte) while leaving
/// CWE-117 wide open, because `eprint_warning` is HUMAN mode and HUMAN mode preserves
/// `\n` by design. The earlier version of this test used a newline-free rule name and
/// `assert_no_control_chars`, which permits `\n` — so it certified the fix while the
/// forgery still worked. A rule name is a JSON object key: never legitimately
/// multi-line, so it is WIRE per the spec §7.5 per-field rule.
///
/// **AC-224-4**: run across multiple terminal widths to prove the warning never wraps
/// (eprint_warning → bare eprintln!, independent of COLUMNS). The multi-width loop
/// produces byte-identical output at all seven column values and empirically confirms
/// the single-line invariant, consistent with the sibling T-ESC-RULE-2 test.
#[test]
fn lint_unknown_rule_name_escapes_control_bytes() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("a.mds"), "Hello!\n").unwrap();

    // One member of each escape sub-class: a C0 byte, a 3-byte bidi control, the 2-byte
    // bidi control (U+061C) that the class originally missed — and newlines carrying two
    // complete forged status lines.
    let rule_name = format!(
        "{}[31mEVIL{}RULE{}ALM\nClean: totally-real.mds\nOK: all-fine.mds",
        '\u{1b}', '\u{202e}', '\u{061c}'
    );
    let mut rules = serde_json::Map::new();
    rules.insert(rule_name, serde_json::Value::String("warn".to_string()));
    let config = serde_json::json!({ "lint": { "rules": rules } });
    std::fs::write(
        dir.path().join("mds.json"),
        serde_json::to_string(&config).unwrap(),
    )
    .unwrap();

    // AC-224-4: run across multiple terminal widths to prove the singular warning
    // never wraps (eprint_warning → bare eprintln!, independent of COLUMNS).
    for columns in [40u32, 60, 80, 100, 120, 160, 200] {
        let out = mds_bin()
            .arg("lint")
            .arg(dir.path())
            .env("COLUMNS", columns.to_string())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .output()
            .unwrap();

        let stderr = String::from_utf8_lossy(&out.stderr);

        // ── Non-vacuity: the warning fired, naming the rule and the recognised list ──
        assert!(
            stderr.contains("unknown lint rule"),
            "COLUMNS={columns}: the unknown-rule warning must be rendered; got: {stderr}"
        );
        assert!(
            stderr.contains("EVIL"),
            "COLUMNS={columns}: the rule name itself must be printed; got: {stderr}"
        );
        assert!(
            stderr.contains("recognised rules are"),
            "COLUMNS={columns}: the recognised-rules list must appear; got: {stderr}"
        );

        // ── Negative: no raw hostile byte survives ───────────────────────────────
        assert!(
            !out.stderr.contains(&0x1Bu8),
            "COLUMNS={columns}: raw ESC byte (0x1B) must not reach stderr from an mds.json rule name; got: {stderr}"
        );
        assert_no_control_chars(&stderr, "mds lint unknown-rule warning");

        // ── Negative: neither forged line appears on a line of its own ───────────
        //
        // `assert_no_control_chars` deliberately permits `\n` so it can be used on HUMAN-mode
        // prose, so it cannot see this. Mirrors T-ESC-FNAME-1's standalone-line assertion.
        // The rule name carries TWO newlines so "Clean: totally-real.mds" lands as a
        // middle segment that would appear standalone if safe_inline were removed — live.
        for forged in ["Clean: totally-real.mds", "OK: all-fine.mds"] {
            assert!(
                !stderr.lines().any(|l| l.trim() == forged),
                "COLUMNS={columns}: an mds.json rule name must not be able to forge the standalone \
                 status line {forged:?}; got: {stderr}"
            );
        }

        // ── Positive: the escaped literals are present ───────────────────────────
        for escaped in ["\\u001B", "\\u202E", "\\u061C"] {
            assert!(
                stderr.contains(escaped),
                "COLUMNS={columns}: {escaped} must appear in the unknown-rule warning; got: {stderr}"
            );
        }
        assert_eq!(
            stderr.matches("\\u000A").count(),
            2,
            "COLUMNS={columns}: both embedded newlines must be escaped to their WIRE literal; got: {stderr}"
        );

        // ── Non-vacuity: the whole rule name landed on ONE line ──────────────────
        //
        // AC-224-4: the multi-width loop proves the warning occupies exactly one line
        // at every terminal width — eprint_warning never wraps.
        let warning_lines: Vec<&str> = stderr
            .lines()
            .filter(|l| l.contains("unknown lint rule"))
            .collect();
        assert_eq!(
            warning_lines.len(),
            1,
            "COLUMNS={columns}: the warning must occupy exactly one line; got: {stderr}"
        );
        assert!(
            warning_lines[0].contains("EVIL")
                && warning_lines[0].contains("recognised rules are")
                && warning_lines[0].ends_with("; ignoring"),
            "COLUMNS={columns}: the single warning line must carry the rule name, the \
             recognised-rules list, and the trailing '; ignoring'; got: {stderr}"
        );
    }
}

/// T-ESC-RULE-2 [security-11-plural / CWE-150 / PF-004 / PF-013 / AC-224-4 / AC-224-5]:
/// two unknown lint rule names containing control bytes — the plural branch of the
/// warning emitter — reach stderr fully escaped; no raw hostile byte survives.
///
/// Companion to T-ESC-RULE-1 which covers the singular path (one unknown name).
/// This test exercises the plural path (two or more unknown names) so that
/// AD-224-3's per-name safe_inline shape is verified for the multi-name loop.
///
/// Both rule names contain control bytes from different escape sub-classes to
/// confirm that each is independently escaped before it is assembled into the
/// comma-separated list.  The multi-width COLUMNS loop proves the plural warning
/// also lands on exactly one line at every terminal width.
#[test]
fn lint_plural_unknown_rule_names_escape_control_bytes() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("a.mds"), "Hello!\n").unwrap();

    // Two distinct hostile rule names — ESC + colour code in the first,
    // RTL-override + Arabic-letter-mark in the second — plus embedded newlines
    // carrying forged status lines in each.
    // Two newlines in rule_a: "Clean: real-a.mds" is the middle segment that would
    // land standalone if safe_inline were removed — makes the forged-line assertion live.
    let rule_a = format!(
        "{}[31mAAA{}RULE\nClean: real-a.mds\nOK: fake-a.mds",
        '\u{1b}', '\u{202e}'
    );
    let rule_b = format!("BBB{}RULE\nOK: real-b.mds", '\u{061c}');
    let mut rules = serde_json::Map::new();
    rules.insert(rule_a, serde_json::Value::String("warn".to_string()));
    rules.insert(rule_b, serde_json::Value::String("warn".to_string()));
    let config = serde_json::json!({ "lint": { "rules": rules } });
    std::fs::write(
        dir.path().join("mds.json"),
        serde_json::to_string(&config).unwrap(),
    )
    .unwrap();

    // AC-224-4: run across multiple terminal widths to prove the plural warning
    // never wraps (eprint_warning → bare eprintln!, independent of COLUMNS).
    for columns in [40u32, 60, 80, 100, 120, 160, 200] {
        let out = mds_bin()
            .arg("lint")
            .arg(dir.path())
            .env("COLUMNS", columns.to_string())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .output()
            .unwrap();

        let stderr = String::from_utf8_lossy(&out.stderr);

        // ── Non-vacuity: the plural warning fired ────────────────────────────
        assert!(
            stderr.contains("unknown lint rules"),
            "COLUMNS={columns}: plural unknown-rule warning must be rendered; got: {stderr}"
        );
        assert!(
            stderr.contains("AAA"),
            "COLUMNS={columns}: first hostile rule prefix must appear; got: {stderr}"
        );
        assert!(
            stderr.contains("BBB"),
            "COLUMNS={columns}: second hostile rule prefix must appear; got: {stderr}"
        );
        assert!(
            stderr.contains("recognised rules are"),
            "COLUMNS={columns}: recognised-rules list must appear; got: {stderr}"
        );

        // ── Negative: no raw hostile byte survives ───────────────────────────
        assert!(
            !out.stderr.contains(&0x1Bu8),
            "COLUMNS={columns}: raw ESC byte (0x1B) must not reach stderr; got: {stderr}"
        );
        assert_no_control_chars(&stderr, "mds lint plural unknown-rule warning");

        // ── Negative: no forged standalone line ──────────────────────────────
        for forged in ["Clean: real-a.mds", "OK: real-b.mds"] {
            assert!(
                !stderr.lines().any(|l| l.trim() == forged),
                "COLUMNS={columns}: rule name must not forge standalone line {forged:?}; \
                 got: {stderr}"
            );
        }

        // ── Positive: escaped literals are present for both names ────────────
        assert!(
            stderr.contains("\\u001B"),
            "COLUMNS={columns}: ESC in first name must be escaped to \\u001B; got: {stderr}"
        );
        assert!(
            stderr.contains("\\u202E"),
            "COLUMNS={columns}: RTL-override in first name must be escaped to \\u202E; \
             got: {stderr}"
        );
        assert!(
            stderr.contains("\\u061C"),
            "COLUMNS={columns}: Arabic-letter-mark in second name must be escaped to \
             \\u061C; got: {stderr}"
        );
        // Three embedded newlines total: two from rule_a, one from rule_b.
        assert_eq!(
            stderr.matches("\\u000A").count(),
            3,
            "COLUMNS={columns}: all embedded newlines (2 from first name, 1 from second) \
             must be escaped to \\u000A; got: {stderr}"
        );

        // ── Non-vacuity: the plural warning occupies exactly ONE line ────────
        let warning_lines: Vec<&str> = stderr
            .lines()
            .filter(|l| l.contains("unknown lint rules"))
            .collect();
        assert_eq!(
            warning_lines.len(),
            1,
            "COLUMNS={columns}: plural warning must occupy exactly one line; got: {stderr}"
        );
        assert!(
            warning_lines[0].ends_with("; ignoring"),
            "COLUMNS={columns}: warning line must end with '; ignoring'; got: {stderr}"
        );
    }
}

/// T-ESC-FNAME-1 [S14 / CWE-117 / PF-013 / #176 / #265]: a filename containing newlines
/// is refused at the input boundary and cannot forge CLI status lines.
///
/// Vector: POSIX permits a newline inside a filename and the user never types the name
/// — `mds build <dir>` discovers it by directory walk. Before #265 the file was built and
/// its name reached a status line, where only escaping stood between the two embedded
/// newlines and two forged `Clean:`/`OK:` lines. Since #265 the name is refused before
/// anything is read: the walker still collects it, and that one file fails with
/// `mds::io` naming U+000A while its sibling builds.
///
/// Positive controls (PF-013): the refusal names the codepoint, the displayed name shows
/// exactly the two escaped newlines, the genuine summary is pinned, and `ok.mds` really
/// was built — so a run that silently skipped the hostile file, or built nothing, fails.
///
/// Unix-only: Windows filesystems reject a newline in a filename outright.
#[cfg(unix)]
#[test]
fn build_refuses_a_newline_in_a_filename_and_builds_its_sibling() {
    let dir = tempfile::tempdir().unwrap();
    let hostile = "evil.mds\nClean: real.mds\nOK: all-fine.mds";
    std::fs::write(dir.path().join(hostile), "Hello!\n").unwrap();
    std::fs::write(dir.path().join("ok.mds"), "Sibling!\n").unwrap();
    let out_dir = dir.path().join("out");

    let out = mds_bin()
        .current_dir(dir.path())
        .args(["build", ".", "--out-dir"])
        .arg(&out_dir)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );

    // ── The hostile file is refused, per file: the refusal is `mds::io`, so the
    //    directory run exits 2 (`N built, M failed`, #157) ────────────────────────
    assert_eq!(out.status.code(), Some(2), "got: {combined}");
    assert!(
        combined.contains("mds::io"),
        "refusal is mds::io; got: {combined}"
    );
    assert!(
        combined.contains("U+000A") && combined.contains("forbidden"),
        "the refusal must name U+000A; got: {combined}"
    );
    assert!(
        combined.lines().any(|l| l.trim() == "1 built, 1 failed"),
        "genuine summary; got: {combined}"
    );

    // ── Positive: the displayed name carries exactly its two newlines, escaped ──
    let escaped_lf = format!("\\u{:04X}", 0x0A);
    assert_eq!(
        combined.matches(escaped_lf.as_str()).count(),
        2,
        "both embedded newlines must be shown escaped, once; got: {combined}"
    );
    assert_no_control_chars(&combined, "mds build refusal");

    // ── Negative: neither forged line appears on a line of its own ───────────
    for forged in ["Clean: real.mds", "OK: all-fine.mds"] {
        assert!(
            !combined.lines().any(|l| l.trim() == forged),
            "a filename must not be able to forge the standalone status line \
             {forged:?}; got: {combined}"
        );
    }

    // ── The sibling still builds ────────────────────────────────────────────
    assert_eq!(
        std::fs::read_to_string(out_dir.join("ok.md")).unwrap(),
        "Sibling!\n",
        "the sibling must be built; got: {combined}"
    );
    assert_eq!(
        std::fs::read_dir(&out_dir).unwrap().count(),
        1,
        "nothing is written for the refused file"
    );
}

/// T-ESC-FNAME-2 [S14 / PF-004 / #176 / #265]: the `Clean:` status line printer — which
/// sanitized its filename inline rather than through `safe_path` — can no longer be
/// reached by a hostile name at all: `mds lint <file>` refuses the path (`mds::io`,
/// exit 2) before it reads the file, so no `Clean:` line is printed.
///
/// The vector also carries U+061C, the bidi control the escape class originally
/// missed, and the refusal message must show both characters escaped.
///
/// Unix-only: Windows filesystems reject a newline in a filename outright.
#[cfg(unix)]
#[test]
fn lint_refuses_a_newline_in_a_filename_without_a_clean_line() {
    let dir = tempfile::tempdir().unwrap();
    let hostile = "ok.mds\nClean: real\u{061c}.mds";
    let path = dir.path().join(hostile);
    std::fs::write(&path, "Hello!\n").unwrap();

    let out = mds_bin()
        .arg("lint")
        .arg(&path)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);

    // ── Refused: mds::io, exit 2, naming U+000A ─────────────────────────────
    assert_eq!(out.status.code(), Some(2), "got: {stderr}");
    assert!(stderr.contains("mds::io"), "got: {stderr}");
    assert!(
        stderr.contains("U+000A") && stderr.contains("forbidden"),
        "the refusal must name U+000A; got: {stderr}"
    );

    // ── Negative: no Clean: line at all, no raw hostile codepoint ───────────
    assert!(
        !stderr.lines().any(|l| l.trim().starts_with("Clean:")),
        "a refused file must print no Clean: line; got: {stderr}"
    );
    assert_no_control_chars(&stderr, "mds lint refusal");

    // ── Positive: the name is shown with the newline and U+061C escaped ─────
    for cp in [0x0A_u32, 0x061C] {
        let esc = format!("\\u{cp:04X}");
        assert!(stderr.contains(&esc), "{esc} must be shown; got: {stderr}");
    }

    // Control: the same content under a clean name lints clean.
    let clean = dir.path().join("clean.mds");
    std::fs::write(&clean, "Hello!\n").unwrap();
    let out = mds_bin()
        .arg("lint")
        .arg(&clean)
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(out.status.success(), "control lints clean");
    assert!(String::from_utf8_lossy(&out.stderr).contains("Clean: "));
}

/// T-ESC-WALK-1 [security-11 / CWE-150 / CWE-117 / PF-004 / PF-013 / #176]: the shared
/// walker's depth-limit warning escapes the directory name it interpolates.
///
/// Vector: `collect_mds_files_inner` in `mds-cli/src/output.rs` warns when recursion
/// exceeds `MAX_DEPTH` (64) and names the directory it stopped at. The name is
/// *discovered by the walk* — the user never types it — and every directory-mode
/// subcommand shares this walker, so one hostile directory name reached `mds build`,
/// `check`, `fmt`, `lint` and `watch` at once.
///
/// This print sat on a bare `eprintln!` inside `output.rs` itself: it was neither one of
/// the `*_collecting_warnings` sites nor `watch.rs`, so two rounds of "route the warning
/// prints through `eprint_warning`" walked straight past it while the CHANGELOG claimed
/// no raw control byte reached human stderr on any warning path.
///
/// The vector carries all three sub-classes at once — a C0 byte (ESC), a 3-byte bidi
/// control (U+202E), and a newline that forges a complete status line. The ESC goes into
/// the directory name as a RAW byte and is asserted on the way out as the uppercase
/// six-character literal, which proves a genuine decode-then-escape rather than literal
/// passthrough.
///
/// Unix-only: Windows filesystems reject a newline in a path component outright.
#[cfg(unix)]
#[test]
fn walker_depth_limit_warning_cannot_be_forged_by_a_hostile_directory_name() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("root");
    std::fs::create_dir(&root).unwrap();
    std::fs::write(root.join("a.mds"), "Hello!\n").unwrap();

    // MAX_DEPTH is 64; the warning fires on the first directory at depth 65.
    let mut deep = root.clone();
    for i in 1..=64 {
        deep = deep.join(format!("d{i}"));
    }
    let hostile = format!(
        "evil{}[31m{}dir\nClean: totally-real.mds",
        '\u{1b}', '\u{202e}'
    );
    deep = deep.join(&hostile);
    std::fs::create_dir_all(&deep).unwrap();
    std::fs::write(deep.join("deep.mds"), "Hello!\n").unwrap();

    // The walker is shared, so assert on all three directory-mode subcommands rather
    // than trusting that one of them stands in for the others (PF-004).
    for subcommand in ["lint", "check", "fmt"] {
        let out = mds_bin()
            .arg(subcommand)
            .arg(&root)
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .output()
            .unwrap();
        let stderr = String::from_utf8_lossy(&out.stderr);
        let label = format!("mds {subcommand} depth-limit warning");

        // ── Non-vacuity: the warning actually fired and named the directory ──
        assert!(
            stderr.contains("directory depth limit"),
            "non-vacuity [{label}]: the depth-limit warning must fire; got: {stderr}"
        );
        assert!(
            stderr.contains("evil"),
            "non-vacuity [{label}]: the directory name must be printed; got: {stderr}"
        );

        // ── Negative: no raw hostile byte, no forged standalone line ─────────
        assert!(
            !out.stderr.contains(&0x1Bu8),
            "raw ESC byte (0x1B) must not reach stderr from a directory name [{label}]; \
             got: {stderr}"
        );
        assert_no_control_chars(&stderr, &label);
        assert!(
            !stderr
                .lines()
                .any(|l| l.trim() == "Clean: totally-real.mds"),
            "a directory name must not be able to forge a standalone status line \
             [{label}]; got: {stderr}"
        );

        // ── Positive: each hostile codepoint appears in escaped form ─────────
        for escaped in ["\\u001B", "\\u202E", "\\u000A"] {
            assert!(
                stderr.contains(escaped),
                "{escaped} must appear in the depth-limit warning [{label}]; got: {stderr}"
            );
        }
    }
}

// ── R3 / CWE-209: analysis-failure JSON carries no absolute path ─────────────

#[test]
fn r3_lint_json_analysis_failure_message_has_no_absolute_path() {
    // Invalid UTF-8 fails on the raw-read path (lint.rs read_source_file),
    // which must anchor its display root at the project root so the
    // `--format json` analysis-failure `error.message` shows "sub/bad.mds" —
    // never a bare basename and never the canonical absolute path (R3 /
    // CWE-209). The vector is proven reachable: it produces the analysis
    // envelope asserted below (PF-013 non-vacuity).
    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");
    std::fs::create_dir_all(&sub).unwrap();
    let input = sub.join("bad.mds");
    std::fs::write(&input, b"Hello \xFF\xFE world\n").unwrap();

    let output = mds_bin()
        .args(["lint", "--format", "json", input.to_str().unwrap()])
        .output()
        .unwrap();

    assert_eq!(
        output.status.code(),
        Some(2),
        "invalid UTF-8 is an analysis failure (exit 2); stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8(output.stdout).unwrap();
    let v: serde_json::Value =
        serde_json::from_str(&stdout).expect("analysis-failure envelope must be valid JSON");
    let msg = v["error"]["message"]
        .as_str()
        .expect("envelope must carry error.message");

    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!(
        msg.contains("sub/bad.mds"),
        "error.message must show the project-root-relative path; got: {msg}"
    );
    assert!(
        !msg.contains(root_str),
        "error.message must not leak the absolute path prefix; got: {msg}"
    );
}