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
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
//! CLI source-map integration tests (SM-1 .. SM-15).
//!
//! Covers AC-FUNC-01..14 (source map feature surface), plus a determinism /
//! security test (AC-SEC-01), one byte-golden test, and a VLQ decode helper
//! (to verify mappings are parseable and encode known positions).

mod common;
use common::{fixture, make_symlink, mds_bin};
use std::path::Path;

// ── VLQ decode helper (inline; no extra dependency) ──────────────────────────

/// Decode a single base64-VLQ value from `iter`.
///
/// Returns the decoded signed integer or `None` on empty / invalid input.
fn decode_vlq_one(iter: &mut impl Iterator<Item = u8>) -> Option<i64> {
    const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    let mut result: u64 = 0;
    let mut shift: u32 = 0;
    let mut continuation = true;
    while continuation {
        let ch = iter.next()?;
        let digit = B64.iter().position(|&b| b == ch)? as u64;
        continuation = (digit & 0x20) != 0;
        result |= (digit & 0x1f) << shift;
        shift += 5;
        if shift > 30 {
            return None; // Guard against pathological input.
        }
    }
    // LSB is sign bit.
    let value = (result >> 1) as i64;
    if (result & 1) != 0 {
        Some(-value)
    } else {
        Some(value)
    }
}

/// Decode the first segment of a Source Map v3 `mappings` string.
///
/// Skips any leading empty groups (frontmatter lines produce empty groups) to find
/// the first non-empty segment.  Returns `(gen_col, src_idx, orig_line, orig_col)`.
fn decode_first_segment(mappings: &str) -> Option<(i64, i64, i64, i64)> {
    // Groups are separated by ';' (line boundaries). Within a group, segments
    // are separated by ','. Skip empty groups produced by frontmatter padding.
    let first_seg = mappings
        .split(';')
        .filter_map(|group| group.split(',').next())
        .find(|seg| !seg.is_empty())?;
    let mut iter = first_seg.bytes();
    let gen_col = decode_vlq_one(&mut iter)?;
    let src_idx = decode_vlq_one(&mut iter)?;
    let orig_line = decode_vlq_one(&mut iter)?;
    let orig_col = decode_vlq_one(&mut iter)?;
    Some((gen_col, src_idx, orig_line, orig_col))
}

// ── Base64 decode helper (for inline carrier tests) ───────────────────────────

fn base64_decode(input: &str) -> Vec<u8> {
    const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = Vec::with_capacity(input.len() / 4 * 3);
    let bytes: Vec<u8> = input
        .bytes()
        .filter(|&b| b != b'=')
        .map(|b| B64.iter().position(|&x| x == b).unwrap() as u8)
        .collect();
    for chunk in bytes.chunks(4) {
        let n = (chunk[0] as u32) << 18
            | (chunk.get(1).copied().unwrap_or(0) as u32) << 12
            | (chunk.get(2).copied().unwrap_or(0) as u32) << 6
            | (chunk.get(3).copied().unwrap_or(0) as u32);
        out.push(((n >> 16) & 0xff) as u8);
        if chunk.len() > 2 {
            out.push(((n >> 8) & 0xff) as u8);
        }
        if chunk.len() > 3 {
            out.push((n & 0xff) as u8);
        }
    }
    out
}

// ── Helper utilities ──────────────────────────────────────────────────────────

/// Build `mds build <file> [extra_args...]` and return the output.
fn build_file(path: &Path, extra_args: &[&str]) -> std::process::Output {
    mds_bin()
        .arg("build")
        .arg(path)
        .args(extra_args)
        .stderr(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .output()
        .expect("mds binary should run")
}

/// Parse the JSON in a `.map` file and return the `serde_json::Value`.
fn read_map_json(map_path: &Path) -> serde_json::Value {
    let text = std::fs::read_to_string(map_path)
        .unwrap_or_else(|e| panic!("cannot read {}: {e}", map_path.display()));
    serde_json::from_str(&text)
        .unwrap_or_else(|e| panic!("map file is not valid JSON at {}: {e}", map_path.display()))
}

/// Assert that a `sources[]` entry is safe to embed in a shipped source map.
///
/// Verifies that `s` is:
/// 1. Not a Windows `\\?\` verbatim-prefix path.
/// 2. Not drive-qualified (`C:\…`, `C:/…`, or bare `C:`).
/// 3. Not an absolute path (leading `/`).
/// 4. Lexically contained within `root` (resolving against `base` or `root`).
/// 5. Free of every component listed in `forbidden`.
///
/// Sentinels delimited by `<` and `>` (e.g. `<stdin>`) pass through — they are
/// display labels, not filesystem paths, and never need containment checking.
fn assert_source_is_contained(s: &str, root: &Path, base: &Path, forbidden: &[&str]) {
    // Sentinels are display labels — not paths.
    if s.starts_with('<') && s.ends_with('>') {
        return;
    }

    let unified = s.replace('\\', "/");

    // No verbatim prefix.
    assert!(
        !unified.starts_with("//?/"),
        "source must not contain Windows verbatim prefix: {s:?}"
    );

    // No drive-qualified forms (ADR-005 / AC-SEC-01).
    assert!(
        !unified.contains(":\\"),
        "source must not contain backslash-qualified Windows drive: {s:?}"
    );
    assert!(
        !unified.contains(":/"),
        "source must not contain forward-slash-qualified Windows drive: {s:?}"
    );
    let drive_lead = unified.len() >= 2
        && (unified.as_bytes()[0] as char).is_ascii_alphabetic()
        && unified.as_bytes()[1] == b':';
    assert!(
        !drive_lead,
        "source must not start with a bare drive designator: {s:?}"
    );

    // Not absolute.
    assert!(
        !unified.starts_with('/'),
        "source must not be an absolute path: {s:?}"
    );

    // Containment: accept either root-relative OR base-relative resolution.
    // When `base` is outside `root`, core emits root-relative paths; when
    // `base` is inside `root`, it emits base-relative paths.  Normalizing
    // through both anchors lets this helper cover both cases.
    let contained = [root, base].iter().any(|anchor| {
        let joined = anchor.join(&unified);
        let mut comps: Vec<_> = Vec::new();
        for c in joined.components() {
            match c {
                std::path::Component::ParentDir => {
                    comps.pop();
                }
                std::path::Component::CurDir => {}
                other => comps.push(other),
            }
        }
        let norm: std::path::PathBuf = comps.iter().collect();
        norm.starts_with(root)
    });
    assert!(
        contained,
        "source path {s:?} is not contained in root {root:?} \
         (tried root-join and base-join with {base:?})"
    );

    // No forbidden component names.
    for comp in unified.split('/') {
        for &f in forbidden {
            assert_ne!(
                comp, f,
                "source path {s:?} contains forbidden component {f:?}"
            );
        }
    }
}

// ── SM-1: --source-map creates a sidecar file (AC-FUNC-01) ───────────────────

#[test]
fn sm1_source_map_creates_sidecar() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");
    let result = build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "-o", out.to_str().unwrap()],
    );
    assert!(result.status.success(), "build should succeed");
    assert!(out.exists(), "output .md should exist");

    // Sidecar is <output>.map, not <output-without-ext>.map.
    let map_path = dir.path().join("out.md.map");
    assert!(
        map_path.exists(),
        "sidecar map out.md.map should exist next to out.md"
    );
}

// ── SM-2: sidecar is valid JSON with version=3 (AC-FUNC-02) ──────────────────

#[test]
fn sm2_sidecar_is_valid_v3_json() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");
    let result = build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "-o", out.to_str().unwrap()],
    );
    assert!(result.status.success(), "build should succeed");

    let map_path = dir.path().join("out.md.map");
    let v = read_map_json(&map_path);

    assert_eq!(
        v["version"].as_u64(),
        Some(3),
        "version must be 3, got: {:?}",
        v["version"]
    );
    assert!(v["sources"].is_array(), "sources must be an array");
    assert!(v["mappings"].is_string(), "mappings must be a string");
    let mappings = v["mappings"].as_str().unwrap();
    assert!(!mappings.is_empty(), "mappings must be non-empty");
}

// ── SM-3: sources[] entries are relative paths (AC-FUNC-05 / AC-SEC-01) ──────

#[test]
fn sm3_sources_are_relative_not_absolute() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");
    let result = build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "-o", out.to_str().unwrap()],
    );
    assert!(result.status.success(), "build should succeed");

    let map_path = dir.path().join("out.md.map");
    let v = read_map_json(&map_path);

    // Workspace root: two levels up from crates/mds-cli (CARGO_MANIFEST_DIR).
    let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace = crate_dir
        .parent()
        .and_then(|p| p.parent())
        .expect("workspace root must be two levels above crate dir");
    // Forbid the output temp-dir name — it must never appear as a path component.
    let dir_name = dir
        .path()
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("");

    for src in v["sources"].as_array().unwrap() {
        let s = src.as_str().unwrap();
        assert_source_is_contained(s, workspace, workspace, &[dir_name]);
    }
}

// ── SM-4: `file` field is the output basename (AC-FUNC-06) ───────────────────

#[test]
fn sm4_file_field_is_output_basename() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");
    let result = build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "-o", out.to_str().unwrap()],
    );
    assert!(result.status.success(), "build should succeed");

    let map_path = dir.path().join("out.md.map");
    let v = read_map_json(&map_path);

    assert_eq!(
        v["file"].as_str(),
        Some("out.md"),
        "file must be the output basename 'out.md', got: {:?}",
        v["file"]
    );
}

// ── SM-5: --no-source-map suppresses map generation (AC-FUNC-03) ─────────────

#[test]
fn sm5_no_source_map_suppresses_generation() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");

    // Build with --source-map first, then rebuild with --no-source-map.
    build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "-o", out.to_str().unwrap()],
    );
    let map_path = dir.path().join("out.md.map");
    assert!(
        map_path.exists(),
        "pre-condition: map should exist after first build"
    );

    // Rebuild without --source-map (no flag at all) — stale map should be cleaned up.
    let result = build_file(&fixture("sm_basic.mds"), &["-o", out.to_str().unwrap()]);
    assert!(
        result.status.success(),
        "rebuild without --source-map should succeed"
    );

    // The stale sidecar should have been removed by verify-then-delete.
    assert!(
        !map_path.exists(),
        "stale map should be removed when --source-map is omitted"
    );
}

// ── SM-6: --inline embeds carrier in output (AC-FUNC-08) ─────────────────────

#[test]
fn sm6_inline_embeds_carrier_in_output() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");
    let result = build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "--inline", "-o", out.to_str().unwrap()],
    );
    assert!(
        result.status.success(),
        "build with --inline should succeed"
    );

    let content = std::fs::read_to_string(&out).unwrap();
    assert!(
        content.contains("<!--# sourceMappingURL=data:application/json;base64,"),
        "inline output must contain the sourceMappingURL carrier, got:\n{content}"
    );

    // Sidecar must NOT exist when using --inline.
    let map_path = dir.path().join("out.md.map");
    assert!(
        !map_path.exists(),
        "--inline must not create a sidecar .map file"
    );
}

// ── SM-7: carrier comment is well-formed and decodable (AC-FUNC-08) ──────────

#[test]
fn sm7_inline_carrier_is_decodable_v3() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");
    build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "--inline", "-o", out.to_str().unwrap()],
    );

    let content = std::fs::read_to_string(&out).unwrap();

    // Extract the base64 payload from the carrier comment.
    let prefix = "<!--# sourceMappingURL=data:application/json;base64,";
    let suffix = " -->";
    let start = content
        .find(prefix)
        .expect("carrier prefix not found in inline output");
    let rest = &content[start + prefix.len()..];
    let end = rest.find(suffix).expect("carrier suffix ' -->' not found");
    let b64 = &rest[..end];

    // Base64 payload must be non-empty and decode to valid JSON with version=3.
    assert!(!b64.is_empty(), "base64 payload must be non-empty");
    let decoded = base64_decode(b64);
    let json: serde_json::Value =
        serde_json::from_slice(&decoded).expect("decoded carrier must be valid JSON");
    assert_eq!(
        json["version"].as_u64(),
        Some(3),
        "decoded carrier version must be 3"
    );
    assert!(json["sources"].is_array(), "sources must be array");
    assert!(json["mappings"].is_string(), "mappings must be string");
}

// ── SM-8: --embed-sources includes sourcesContent (AC-FUNC-09) ───────────────

#[test]
fn sm8_embed_sources_includes_sources_content() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");
    let result = build_file(
        &fixture("sm_basic.mds"),
        &[
            "--source-map",
            "--embed-sources",
            "-o",
            out.to_str().unwrap(),
        ],
    );
    assert!(
        result.status.success(),
        "build with --embed-sources should succeed"
    );

    let map_path = dir.path().join("out.md.map");
    let v = read_map_json(&map_path);

    let sources_content = v["sourcesContent"]
        .as_array()
        .expect("sourcesContent must be present when --embed-sources is set");
    assert!(
        !sources_content.is_empty(),
        "sourcesContent must be non-empty"
    );
    // Each entry is either null or a string.
    for entry in sources_content {
        assert!(
            entry.is_null() || entry.is_string(),
            "each sourcesContent entry must be null or string, got: {entry:?}"
        );
    }
}

// ── SM-9: no --embed-sources → sourcesContent absent (AC-FUNC-09) ────────────

#[test]
fn sm9_no_embed_sources_omits_sources_content() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");
    build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "-o", out.to_str().unwrap()],
    );

    let map_path = dir.path().join("out.md.map");
    let v = read_map_json(&map_path);

    assert!(
        v["sourcesContent"].is_null(),
        "sourcesContent must be absent (null in JSON) when --embed-sources is omitted, got: {:?}",
        v["sourcesContent"]
    );
}

// ── SM-10: messages-mode template degrades to no map (AC-FUNC-07) ────────────

#[test]
fn sm10_messages_mode_degrades_to_no_map() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.json");
    let result = build_file(
        &fixture("sm_message.mds"),
        &["--source-map", "-o", out.to_str().unwrap()],
    );

    // Build itself must succeed (graceful degradation, not an error).
    assert!(
        result.status.success(),
        "messages-mode build with --source-map must succeed (graceful degradation)"
    );

    // No map file should be produced.
    let map_path = dir.path().join("out.json.map");
    assert!(
        !map_path.exists(),
        "no .map should be emitted for a messages-mode template"
    );

    // A warning about degradation should appear on stderr.
    let stderr = String::from_utf8(result.stderr).unwrap();
    let has_warn =
        stderr.contains("messages") || stderr.contains("source_map") || stderr.contains("None");
    assert!(
        has_warn,
        "stderr must contain a degradation warning for messages-mode, got: {stderr:?}"
    );
}

// ── SM-11: stale-map reconciliation: no-map build removes prior sidecar ───────

#[test]
fn sm11_stale_map_removed_on_no_map_rebuild() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");

    // Step 1: build with --source-map → creates sidecar.
    let r1 = build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "-o", out.to_str().unwrap()],
    );
    assert!(
        r1.status.success(),
        "initial source-map build should succeed"
    );

    let map_path = dir.path().join("out.md.map");
    assert!(map_path.exists(), "sidecar must exist after step 1");

    // Step 2: rebuild without --source-map → stale sidecar should be removed.
    let r2 = build_file(&fixture("sm_basic.mds"), &["-o", out.to_str().unwrap()]);
    assert!(
        r2.status.success(),
        "rebuild without --source-map should succeed"
    );

    assert!(
        !map_path.exists(),
        "stale map must be removed when rebuilding without --source-map (AC-FUNC-10)"
    );
}

// ── SM-12: rebuild with --source-map overwrites existing sidecar ─────────────

#[test]
fn sm12_sidecar_overwritten_on_rebuild() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");

    // Build twice with --source-map — second should overwrite, not error.
    let r1 = build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "-o", out.to_str().unwrap()],
    );
    assert!(r1.status.success(), "first source-map build should succeed");

    let map_path = dir.path().join("out.md.map");
    let map1 = std::fs::read_to_string(&map_path).unwrap();

    let r2 = build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "-o", out.to_str().unwrap()],
    );
    assert!(
        r2.status.success(),
        "second source-map build should succeed"
    );

    let map2 = std::fs::read_to_string(&map_path).unwrap();
    // Content is deterministic: same input → same map.
    assert_eq!(
        map1, map2,
        "map should be deterministic across identical builds"
    );
}

// ── SM-13: --inline build removes stale sidecar from prior build (AC-FUNC-10)

#[test]
fn sm13_inline_build_removes_stale_sidecar() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");

    // Step 1: sidecar build.
    let r1 = build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "-o", out.to_str().unwrap()],
    );
    assert!(r1.status.success(), "initial sidecar build should succeed");

    let map_path = dir.path().join("out.md.map");
    assert!(map_path.exists(), "sidecar must exist after step 1");

    // Step 2: rebuild with --inline → stale sidecar removed.
    let r2 = build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "--inline", "-o", out.to_str().unwrap()],
    );
    assert!(r2.status.success(), "inline rebuild should succeed");

    assert!(
        !map_path.exists(),
        "stale sidecar must be removed when switching to --inline (AC-FUNC-10)"
    );

    // Output must now contain the inline carrier.
    let content = std::fs::read_to_string(&out).unwrap();
    assert!(
        content.contains("<!--# sourceMappingURL=data:"),
        "output must contain inline carrier after --inline rebuild"
    );
}

// ── SM-14: stdin with --source-map --inline produces carrier (AC-FUNC-12) ────

#[test]
fn sm14_stdin_source_map_inline_produces_carrier() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("stdin_out.md");

    let mut child = mds_bin()
        .args([
            "build",
            "-",
            "--source-map",
            "--inline",
            "-o",
            out.to_str().unwrap(),
        ])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("mds binary should spawn");

    use std::io::Write as _;
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"---\nname: World\n---\nHello {{name}}!\n")
        .unwrap();

    let result = child.wait_with_output().unwrap();
    assert!(
        result.status.success(),
        "stdin --source-map --inline should succeed"
    );

    let content = std::fs::read_to_string(&out).unwrap();
    assert!(
        content.contains("<!--# sourceMappingURL=data:application/json;base64,"),
        "stdin inline output must contain carrier"
    );

    // Decode the carrier and verify sources label is <stdin> (AC-FUNC-12).
    let prefix = "<!--# sourceMappingURL=data:application/json;base64,";
    let suffix = " -->";
    let start = content.find(prefix).unwrap();
    let rest = &content[start + prefix.len()..];
    let end = rest.find(suffix).unwrap();
    let b64 = &rest[..end];
    let decoded = base64_decode(b64);
    let json: serde_json::Value = serde_json::from_slice(&decoded).unwrap();

    let sources = json["sources"].as_array().expect("sources must be array");
    assert!(
        sources.iter().any(|s| s.as_str() == Some("<stdin>")),
        "stdin builds must label source as '<stdin>', got: {sources:?}"
    );
}

// ── SM-15: directory mode with --source-map (AC-FUNC-14) ────────────────────

#[test]
fn sm15_directory_mode_source_map() {
    // Build a directory containing sm_basic.mds with --source-map.
    // We copy just the one file into a temp dir to isolate the test.
    let dir = tempfile::tempdir().unwrap();
    let src_content = std::fs::read_to_string(fixture("sm_basic.mds")).unwrap();
    std::fs::write(dir.path().join("basic.mds"), &src_content).unwrap();

    let out_dir = dir.path().join("out");
    let result = mds_bin()
        .args([
            "build",
            dir.path().to_str().unwrap(),
            "--source-map",
            "--out-dir",
            out_dir.to_str().unwrap(),
        ])
        .stderr(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .output()
        .expect("mds binary should run");

    assert!(
        result.status.success(),
        "directory mode --source-map build should succeed, stderr: {}",
        String::from_utf8_lossy(&result.stderr)
    );

    let out_md = out_dir.join("basic.md");
    let out_map = out_dir.join("basic.md.map");

    assert!(out_md.exists(), "compiled .md should exist in out_dir");
    assert!(
        out_map.exists(),
        "sidecar .md.map should exist in out_dir alongside basic.md"
    );

    let v = read_map_json(&out_map);
    assert_eq!(v["version"].as_u64(), Some(3), "map version must be 3");
}

// ── SM-DET: determinism + security (AC-SEC-01 / AC-FUNC-05) ─────────────────

#[test]
fn sm_det_sources_never_absolute_across_build_dirs() {
    // Build the same fixture from two different output directories.
    // sources[] entries must be relative in both cases (AC-SEC-01).
    let dir_a = tempfile::tempdir().unwrap();
    let dir_b = tempfile::tempdir().unwrap();

    let out_a = dir_a.path().join("out_a.md");
    let out_b = dir_b.path().join("out_b.md");

    build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "-o", out_a.to_str().unwrap()],
    );
    build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "-o", out_b.to_str().unwrap()],
    );

    let map_a = read_map_json(&dir_a.path().join("out_a.md.map"));
    let map_b = read_map_json(&dir_b.path().join("out_b.md.map"));

    let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace = crate_dir
        .parent()
        .and_then(|p| p.parent())
        .expect("workspace root must be two levels above crate dir");

    for (_label, v, dir_path) in [
        ("dir_a", &map_a, dir_a.path()),
        ("dir_b", &map_b, dir_b.path()),
    ] {
        let dir_name = dir_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
        for src in v["sources"].as_array().unwrap() {
            let s = src.as_str().unwrap();
            assert_source_is_contained(s, workspace, workspace, &[dir_name]);
        }
    }

    // mappings must be byte-identical (same source, same output structure).
    assert_eq!(
        map_a["mappings"], map_b["mappings"],
        "mappings must be deterministic regardless of output directory"
    );
}

// ── SM-GOLD: byte-golden test (regen with: UPDATE_GOLDEN=1 cargo test) ───────

/// Golden mappings for sm_basic.mds → {name: World} → "Hello World!\nThis is line two.\n"
///
/// To regenerate this golden value:
///   1. Run the test with UPDATE_GOLDEN=1 to print the current value.
///   2. Copy the printed value into the constant below.
///   3. Commit the updated golden.
///
/// The golden anchors to the first character of the first segment only (column 0,
/// source 0, original line 0, original column 0 → VLQ "AAAA"), which is stable
/// across unrelated changes to later segments.
#[test]
fn sm_gold_mappings_first_segment_is_aaaa() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("gold.md");
    let result = build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "-o", out.to_str().unwrap()],
    );
    assert!(result.status.success(), "golden build should succeed");

    let map_path = dir.path().join("gold.md.map");
    let v = read_map_json(&map_path);
    let mappings = v["mappings"].as_str().unwrap();

    // The first non-empty segment must be "AAGA":
    //   gen_col=0 (first char of first body output line)
    //   src=0     (first source file)
    //   orig_line=3 (body starts at line 3 of sm_basic.mds, after 3 frontmatter lines)
    //   orig_col=0  (first column)
    //
    // VLQ encoding: A=0, A=0, G=+3, A=0 → "AAGA"
    // Frontmatter lines produce leading empty groups before this segment.
    const GOLDEN_FIRST_SEG: &str = "AAGA";

    let first_nonempty_seg = mappings
        .split(';')
        .filter_map(|g| g.split(',').next())
        .find(|s| !s.is_empty())
        .unwrap_or("");

    if std::env::var("UPDATE_GOLDEN").is_ok() {
        eprintln!("UPDATE_GOLDEN: first nonempty segment = {first_nonempty_seg:?}");
        eprintln!("UPDATE_GOLDEN: full mappings = {mappings:?}");
    }

    assert_eq!(
        first_nonempty_seg, GOLDEN_FIRST_SEG,
        "first non-empty segment must be {GOLDEN_FIRST_SEG:?} \
         (gen_col=0,src=0,orig_line=3,orig_col=0 for sm_basic.mds), got: {first_nonempty_seg:?}"
    );
}

// ── SM-VLQ: VLQ decode test ───────────────────────────────────────────────────

#[test]
fn sm_vlq_decoder_known_values() {
    // Verify the inline VLQ decoder against known values from the spec:
    //   0  → "A"
    //   1  → "C"
    //   -1 → "D"
    //   2  → "E"
    // Four-value sequence [0, 0, 0, 0] → "AAAA"
    let mut iter_a = b"A".iter().copied();
    assert_eq!(decode_vlq_one(&mut iter_a), Some(0), "A → 0");

    let mut iter_c = b"C".iter().copied();
    assert_eq!(decode_vlq_one(&mut iter_c), Some(1), "C → 1");

    let mut iter_d = b"D".iter().copied();
    assert_eq!(decode_vlq_one(&mut iter_d), Some(-1), "D → -1");

    let mut iter_e = b"E".iter().copied();
    assert_eq!(decode_vlq_one(&mut iter_e), Some(2), "E → 2");

    // "AAAA" = [0, 0, 0, 0] — the all-zero segment.
    let seg = decode_first_segment("AAAA").expect("AAAA must decode");
    assert_eq!(seg, (0, 0, 0, 0), "AAAA must decode to all-zero offsets");

    // "CCCC" = [1, 1, 1, 1]
    let seg2 = decode_first_segment("CCCC").expect("CCCC must decode");
    assert_eq!(seg2, (1, 1, 1, 1), "CCCC must decode to all-one offsets");
}

// ── helpers: multi-source attribution ────────────────────────────────────────

/// Return `true` if the mappings string contains at least one 4-field segment
/// whose accumulated `src_idx` is > 0 after applying all deltas.
///
/// Implements the SMv3 state-machine: gen_col resets at each `;`, but all
/// other fields (src_idx, orig_line, orig_col) accumulate across the entire
/// mapping string.  A src_idx > 0 means the segment references a source file
/// other than the primary entry (index 0 in sources[]).
fn mappings_reference_multiple_sources(mappings: &str) -> bool {
    let mut src_idx: i64 = 0;
    for group in mappings.split(';') {
        for seg in group.split(',') {
            if seg.is_empty() {
                continue;
            }
            let mut iter = seg.bytes();
            // First field: gen_col delta — consume but ignore.
            if decode_vlq_one(&mut iter).is_none() {
                continue;
            }
            // Second field: src_idx delta — accumulate and test.
            if let Some(delta) = decode_vlq_one(&mut iter) {
                src_idx = src_idx.saturating_add(delta);
                if src_idx > 0 {
                    return true;
                }
            }
        }
    }
    false
}

// ── SM-17: @include multi-file source attribution (TEST-3) ───────────────────

/// Compile a parent template that `@import`s a partial and verify that the
/// generated source map attributes output lines to BOTH source files.
///
/// Acceptance criteria (TEST-3):
///   1. sources[] contains at least 2 entries.
///   2. One entry refers to the parent (sm_include_parent.mds).
///   3. One entry refers to the included file (_sm_partial.mds).
///   4. The mappings contain a segment that references src_idx > 0
///      (i.e., at least one output line is attributed to the included file).
#[test]
fn sm17_include_multi_file_attribution() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");
    let result = build_file(
        &fixture("sm_include_parent.mds"),
        &["--source-map", "-o", out.to_str().unwrap()],
    );
    assert!(
        result.status.success(),
        "build of @include fixture should succeed, stderr: {}",
        String::from_utf8_lossy(&result.stderr)
    );

    let map_path = dir.path().join("out.md.map");
    assert!(map_path.exists(), "sidecar .md.map must exist");

    let v = read_map_json(&map_path);

    // (1) sources[] must have at least 2 entries.
    let sources = v["sources"].as_array().expect("sources must be an array");
    assert!(
        sources.len() >= 2,
        "sources[] must have ≥ 2 entries for a template that @imports another, got: {:?}",
        sources
    );

    // (2) At least one source must identify the parent file.
    let has_parent = sources
        .iter()
        .any(|s| s.as_str().is_some_and(|p| p.contains("sm_include_parent")));
    assert!(
        has_parent,
        "sources[] must include the parent file (sm_include_parent), got: {:?}",
        sources
    );

    // (3) At least one source must identify the imported partial.
    let has_partial = sources
        .iter()
        .any(|s| s.as_str().is_some_and(|p| p.contains("_sm_partial")));
    assert!(
        has_partial,
        "sources[] must include the imported file (_sm_partial), got: {:?}",
        sources
    );

    // (4) The VLQ mappings must attribute at least one output segment to a
    //     source other than the primary entry (src_idx > 0).
    let mappings = v["mappings"].as_str().unwrap();
    assert!(
        mappings_reference_multiple_sources(mappings),
        "mappings must contain a segment referencing the imported source (src_idx > 0); \
         got sources: {:?}, mappings: {:?}",
        sources,
        mappings
    );
}

// ── SM-18: an @include of an extending chain names relative sources (#412) ──

/// #412 (on disk): an importer in `src/` that `@include`s a three-level
/// extending chain in `lib/`, built into `build/`, lists every chain file in its
/// sidecar map with its text, each relative to the map and contained in the project —
/// never an absolute path.
#[test]
fn sm18_include_of_extending_chain_sources_are_relative() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    std::fs::write(root.join(".mdsroot"), "").unwrap();
    for sub in ["src", "lib", "build"] {
        std::fs::create_dir(root.join(sub)).unwrap();
    }
    let files = [
        (
            "lib/a.mds",
            "A-HEAD\n@block b1:\nA-ONE\n@end\n@block b2:\nA-TWO\n@end\nA-TAIL\n",
        ),
        (
            "lib/b.mds",
            "@extends \"./a.mds\"\n@block b1:\nB-ONE\n@end\n",
        ),
        (
            "lib/c.mds",
            "@extends \"./b.mds\"\n@block b2:\nC-TWO\n@end\n",
        ),
        (
            "src/main.mds",
            "@import \"../lib/c.mds\" as c\nMAIN-HEAD\n@include c\n",
        ),
    ];
    for (name, text) in files {
        std::fs::write(root.join(name), text).unwrap();
    }
    // Positive control (PF-013): the chain's canonical paths are absolute, so the
    // containment checks below fail if one reaches the map.
    assert!(root.join("lib/a.mds").canonicalize().unwrap().is_absolute());

    // Relative arguments from the project root: the map's directory then resolves
    // the way the root does, so the sources anchor at the map (`../…`).
    let result = mds_bin()
        .current_dir(root)
        .args(["build", "src/main.mds", "--source-map", "--embed-sources"])
        .args(["-o", "build/out.md"])
        .output()
        .expect("mds binary should run");
    assert!(
        result.status.success(),
        "build should succeed, stderr: {}",
        String::from_utf8_lossy(&result.stderr)
    );
    assert_eq!(
        std::fs::read_to_string(root.join("build").join("out.md")).unwrap(),
        "MAIN-HEAD\nA-HEAD\nB-ONE\nC-TWO\nA-TAIL\n"
    );

    let v = read_map_json(&root.join("build").join("out.md.map"));
    let sources: Vec<&str> = v["sources"]
        .as_array()
        .expect("sources must be an array")
        .iter()
        .map(|s| s.as_str().expect("each source is a string"))
        .collect();
    // Map-relative (`../…`): `build/` resolves inside the project root as the root
    // itself does. On Windows a working directory reached through an 8.3 short name can
    // resolve `build/` outside the root's spelling, and the sources are then
    // root-relative, also a correct anchor (ADR-005), so there the anchor is read off
    // the first source. Either way every file of the chain is listed after the importer.
    #[cfg(not(windows))]
    let anchor = "../";
    #[cfg(windows)]
    let anchor = if sources.first() == Some(&"../src/main.mds") {
        "../"
    } else {
        ""
    };
    let files_in_order = ["src/main.mds", "lib/a.mds", "lib/b.mds", "lib/c.mds"];
    assert_eq!(
        sources,
        files_in_order.map(|file| format!("{anchor}{file}")),
        "the importer, then every file of the included chain"
    );
    for source in &sources {
        assert_source_is_contained(source, root, &root.join("build"), &[]);
    }
    let contents: Vec<&str> = v["sourcesContent"]
        .as_array()
        .expect("--embed-sources keeps sourcesContent")
        .iter()
        .map(|s| s.as_str().expect("each entry is a string"))
        .collect();
    let expected: Vec<&str> = files_in_order
        .iter()
        .map(|name| files.iter().find(|(file, _)| file == name).unwrap().1)
        .collect();
    assert_eq!(contents, expected, "sourcesContent must align with sources");
}

// ── SM-VLQ-INT: VLQ integration test with actual map output ──────────────────

#[test]
fn sm_vlq_actual_map_first_segment_decodes() {
    // Build sm_basic.mds and verify the first segment of the map decodes
    // to plausible positions (all values >= 0, source index 0).
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");
    let result = build_file(
        &fixture("sm_basic.mds"),
        &["--source-map", "-o", out.to_str().unwrap()],
    );
    assert!(result.status.success(), "build should succeed");

    let map_path = dir.path().join("out.md.map");
    let v = read_map_json(&map_path);
    let mappings = v["mappings"].as_str().unwrap();

    let (gen_col, src_idx, orig_line, orig_col) =
        decode_first_segment(mappings).expect("first segment must decode");

    assert_eq!(src_idx, 0, "first segment must reference source index 0");
    assert!(gen_col >= 0, "generated column must be >= 0");
    assert!(orig_line >= 0, "original line must be >= 0");
    assert!(orig_col >= 0, "original column must be >= 0");
}

// ── SM-16: hand-authored non-SMv3 map preserved with warning (AC-FUNC-10) ───

/// A hand-authored `.map` file that is NOT a valid SMv3 tool-generated sidecar
/// must be left in place (preserved) and must trigger a warning on stderr.
/// With `--quiet`, the warning is suppressed but the file is still preserved.
#[test]
fn sm16_stale_map_not_smv3_preserved_with_warning() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");
    let map_path = dir.path().join("out.md.map");

    // Place a hand-authored map that is NOT valid SMv3 (version=2, wrong file field).
    std::fs::write(&map_path, r#"{"version":2,"file":"WRONG.md"}"#).unwrap();

    // Build WITHOUT --source-map; this triggers stale-map reconciliation.
    let result = build_file(&fixture("sm_basic.mds"), &["-o", out.to_str().unwrap()]);
    assert!(result.status.success(), "build should succeed");

    // (i) The hand-authored map must still exist (preserved, not deleted).
    assert!(
        map_path.exists(),
        "hand-authored non-SMv3 map must be preserved (not deleted)"
    );

    // (ii) A warning must appear on stderr.
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        stderr.contains("warning: kept stale map")
            && stderr.contains("out.md.map: not proven to be written by mds"),
        "expected a warning about keeping the non-SMv3 map, got stderr: {stderr:?}"
    );

    // With --quiet the warning must be suppressed (but the file is still preserved).
    // Re-write the map (build above may have recreated or left it).
    std::fs::write(&map_path, r#"{"version":2,"file":"WRONG.md"}"#).unwrap();
    let quiet_result = build_file(
        &fixture("sm_basic.mds"),
        &["-o", out.to_str().unwrap(), "--quiet"],
    );
    assert!(quiet_result.status.success(), "quiet build should succeed");
    assert!(
        map_path.exists(),
        "hand-authored non-SMv3 map must be preserved even with --quiet"
    );
    let quiet_stderr = String::from_utf8_lossy(&quiet_result.stderr);
    assert!(
        !quiet_stderr.contains("warning:"),
        "--quiet must suppress the warning; got stderr: {quiet_stderr:?}"
    );
}

// ── SM-16c: the stale-map check deletes only a sidecar mds wrote (#428) ───────

/// Run `mds <args>` in `dir` and return `(exit code, stderr)`. Bounded: a run still going
/// after 20 s — blocked opening a FIFO, say — is killed, and reported with no exit code.
fn run_bounded(dir: &Path, args: &[&str]) -> (Option<i32>, String) {
    use std::io::Read as _;
    let mut child = mds_bin()
        .current_dir(dir)
        .args(args)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("mds binary should spawn");
    let mut pipe = child.stderr.take().unwrap();
    let drain = std::thread::spawn(move || {
        let mut text = String::new();
        let _ = pipe.read_to_string(&mut text);
        text
    });
    // Bounded: at most 20 s / 10 ms iterations.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
    let status = loop {
        if let Some(status) = child.try_wait().unwrap() {
            break status;
        }
        if std::time::Instant::now() >= deadline {
            let _ = child.kill();
            let _ = child.wait();
            let stderr = drain.join().unwrap();
            return (None, format!("killed: still running after 20 s; {stderr}"));
        }
        std::thread::sleep(std::time::Duration::from_millis(10));
    };
    (status.code(), drain.join().unwrap())
}

/// #428: a build without `--source-map` deletes the sidecar an earlier `--source-map`
/// build wrote (the control), and leaves anything else at `<output>.map` in place with
/// a warning: for a regular file that is no sidecar — a hand-formatted map with the same
/// fields, a 64 MiB file of anything else (only a sidecar's first bytes are read) —
/// `kept stale map <path>: not proven to be written by mds`; and for what is no regular
/// file, on Unix a FIFO, which is never opened — opening one with no writer blocks — and
/// a directory, `kept stale map <path>: not a regular file` (#160).
#[test]
fn sm16c_stale_map_check_leaves_anything_but_a_sidecar_in_place() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("page.mds"), "Hi\n").unwrap();
    let map = dir.path().join("out.md.map");
    let rebuild = ["build", "page.mds", "-o", "out.md"];
    let warning = "warning: kept stale map out.md.map: not proven to be written by mds";
    #[cfg(unix)]
    let not_a_file = "warning: kept stale map out.md.map: not a regular file";

    let (code, stderr) = run_bounded(
        dir.path(),
        &["build", "page.mds", "--source-map", "-o", "out.md"],
    );
    assert_eq!(code, Some(0), "source-map build: {stderr}");
    assert!(map.is_file(), "the sidecar is written");
    let (code, stderr) = run_bounded(dir.path(), &rebuild);
    assert_eq!(code, Some(0), "control rebuild: {stderr}");
    assert!(
        !map.exists(),
        "control: the sidecar is deleted; stderr: {stderr}"
    );
    assert!(
        stderr.contains("Removed stale map out.md.map"),
        "control: {stderr}"
    );

    let mut mismatches = Vec::new();
    let hand_formatted =
        b"{ \"version\": 3, \"file\": \"out.md\", \"sources\": [], \"names\": [], \"mappings\": \"\" }"
            .to_vec();
    for (label, bytes) in [
        ("hand-formatted, same fields", hand_formatted),
        ("64 MiB of x", vec![b'x'; 64 * 1024 * 1024]),
    ] {
        std::fs::write(&map, &bytes).unwrap();
        let (code, stderr) = run_bounded(dir.path(), &rebuild);
        let kept = std::fs::read(&map).is_ok_and(|now| now == bytes);
        if code != Some(0) || !kept || !stderr.lines().any(|l| l == warning) {
            mismatches.push(format!(
                "{label}: exit {code:?}, left in place: {kept}; stderr: {stderr}"
            ));
        }
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::FileTypeExt as _;
        std::fs::remove_file(&map).unwrap();
        let made = std::process::Command::new("mkfifo")
            .arg(&map)
            .status()
            .expect("mkfifo runs");
        assert!(made.success(), "mkfifo out.md.map");
        let (code, stderr) = run_bounded(dir.path(), &rebuild);
        let fifo = std::fs::symlink_metadata(&map).is_ok_and(|m| m.file_type().is_fifo());
        if code != Some(0) || !fifo || !stderr.lines().any(|l| l == not_a_file) {
            mismatches.push(format!(
                "FIFO: exit {code:?}, left in place: {fifo}; stderr: {stderr}"
            ));
        }

        // A directory is no regular file either; it is not opened, and says so. Unix-only
        // with the FIFO: what opening a directory by path does is not the same on Windows.
        std::fs::remove_file(&map).unwrap();
        std::fs::create_dir(&map).unwrap();
        let (code, stderr) = run_bounded(dir.path(), &rebuild);
        if code != Some(0) || !map.is_dir() || !stderr.lines().any(|l| l == not_a_file) {
            mismatches.push(format!(
                "directory: exit {code:?}, left in place: {}; stderr: {stderr}",
                map.is_dir()
            ));
        }
    }
    assert!(mismatches.is_empty(), "{mismatches:#?}");
}

// ── SM-14b: stdin --source-map sidecar relabels source to <stdin> ────────────
//
// After the STRING_SOURCE_MAP_LABEL fix, stdin builds emit "input.mds" in
// sources[0].  relativize_source_path Rule 1 must relabel it to "<stdin>"
// (AC-FUNC-12).  Verifies both the relabeling AND that "input.mds" / "<source>"
// never leak into the sidecar map.

#[test]
fn sm14b_stdin_source_map_sidecar_relabels_source_to_stdin() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("stdin_out.md");
    let map_path = dir.path().join("stdin_out.md.map");

    let mut child = mds_bin()
        .args(["build", "-", "--source-map", "-o", out.to_str().unwrap()])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("mds binary should spawn");

    use std::io::Write as _;
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"---\nname: World\n---\nHello {{name}}!\n")
        .unwrap();

    let result = child.wait_with_output().unwrap();
    assert!(
        result.status.success(),
        "stdin --source-map sidecar should succeed"
    );

    let map_json = read_map_json(&map_path);
    let sources = map_json["sources"]
        .as_array()
        .expect("sources must be array");

    // Must use "<stdin>" — never "input.mds" or "<source>".
    assert!(
        sources.iter().any(|s| s.as_str() == Some("<stdin>")),
        "stdin sidecar must label source as \"<stdin>\"; got: {sources:?}"
    );
    assert!(
        !sources.iter().any(|s| s.as_str() == Some("input.mds")),
        "\"input.mds\" must not leak into stdin sidecar sources[]; got: {sources:?}"
    );
    assert!(
        !sources.iter().any(|s| s.as_str() == Some("<source>")),
        "\"<source>\" must not appear in stdin sidecar sources[]; got: {sources:?}"
    );
}

// ── SM-16: --inline -o - (stdout) produces relativized map, no absolute paths─
//
// Before the relativize_source_map_fields fix, the early return on None
// output bypassed relativization entirely, leaking absolute filesystem paths
// into inline data-URI source maps.  After the fix, map_dir = PathBuf::new()
// so paths are relativized against CWD unconditionally.

/// SM-16a: file input + --inline + -o - → stdout carrier has no absolute paths.
#[test]
fn sm16a_file_inline_stdout_no_absolute_paths() {
    // Run the binary against a real fixture with --inline -o -
    let result = mds_bin()
        .args([
            "build",
            fixture("sm_basic.mds").to_str().unwrap(),
            "--source-map",
            "--inline",
            "-o",
            "-",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .expect("mds binary should run");

    assert!(
        result.status.success(),
        "file --inline -o - must succeed; stderr: {}",
        String::from_utf8_lossy(&result.stderr)
    );

    let stdout = String::from_utf8_lossy(&result.stdout);
    // Extract and decode the inline data-URI carrier.
    let prefix = "<!--# sourceMappingURL=data:application/json;base64,";
    let suffix = " -->";
    let start = stdout
        .find(prefix)
        .expect("stdout must contain inline source-map carrier");
    let rest = &stdout[start + prefix.len()..];
    let end = rest
        .find(suffix)
        .expect("carrier must be closed with \" -->\"");
    let b64 = &rest[..end];
    let decoded = base64_decode(b64);
    let json: serde_json::Value = serde_json::from_slice(&decoded).unwrap();

    let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace = crate_dir
        .parent()
        .and_then(|p| p.parent())
        .expect("workspace root must be two levels above crate dir");
    let cwd = std::env::current_dir().unwrap_or_else(|_| workspace.to_path_buf());
    let home = std::env::var("HOME").unwrap_or_default();
    let home_name = std::path::Path::new(&home)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("");

    let sources = json["sources"].as_array().expect("sources must be array");
    for src in sources {
        let s = src.as_str().expect("source must be string");
        assert_source_is_contained(s, workspace, &cwd, &[home_name]);
    }

    // `file` field must be absent for stdout output (no output filename).
    assert!(
        json.get("file").map(|v| v.is_null()).unwrap_or(true),
        "`file` field must be absent or null for stdout inline map; got: {:?}",
        json.get("file")
    );
}

/// SM-16b: stdin + --inline + -o - → previously rejected, now allowed.
///
/// The false rejection "--inline cannot be used with -o -" was deleted.
/// The inline carrier embeds in the output stream identically to file input.
#[test]
fn sm16b_stdin_inline_stdout_now_allowed() {
    let mut child = mds_bin()
        .args(["build", "-", "--source-map", "--inline", "-o", "-"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("mds binary should spawn");

    use std::io::Write as _;
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"Hello World!\n")
        .unwrap();

    let result = child.wait_with_output().unwrap();
    assert!(
        result.status.success(),
        "stdin --inline -o - must succeed after removing the false rejection; \
         stderr: {}",
        String::from_utf8_lossy(&result.stderr)
    );

    let stdout = String::from_utf8_lossy(&result.stdout);
    // Must contain an inline carrier.
    assert!(
        stdout.contains("<!--# sourceMappingURL=data:application/json;base64,"),
        "stdin --inline -o - must embed a source-map carrier in stdout; stdout: {stdout:?}"
    );

    // Decode and verify no absolute paths in sources.
    let prefix = "<!--# sourceMappingURL=data:application/json;base64,";
    let suffix = " -->";
    let start = stdout.find(prefix).unwrap();
    let rest = &stdout[start + prefix.len()..];
    let end = rest.find(suffix).unwrap();
    let decoded = base64_decode(&rest[..end]);
    let json: serde_json::Value = serde_json::from_slice(&decoded).unwrap();
    let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace = crate_dir
        .parent()
        .and_then(|p| p.parent())
        .expect("workspace root must be two levels above crate dir");
    let cwd = std::env::current_dir().unwrap_or_else(|_| workspace.to_path_buf());
    let home = std::env::var("HOME").unwrap_or_default();
    let home_name = std::path::Path::new(&home)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("");

    let sources = json["sources"].as_array().expect("sources must be array");
    // Stdin source must be relabeled to "<stdin>" by apply_source_map_file_label.
    assert!(
        sources.iter().any(|s| s.as_str() == Some("<stdin>")),
        "stdin --inline stdout must label source as \"<stdin>\"; got: {sources:?}"
    );
    for src in sources {
        let s = src.as_str().expect("source must be string");
        // "<stdin>" is a sentinel — assert_source_is_contained returns early for it.
        assert_source_is_contained(s, workspace, &cwd, &[home_name]);
    }
}

// ── SM-SEC3: `..`-escape guard — deepCWD/output dir must not leak path layout ──

/// Regression gate for the SEC-3 fix (ADR-005 / AC-SEC-01 / avoids PF-004).
///
/// Before the fix, `relativize_source_path` only guarded against paths that were
/// still ABSOLUTE after relativization (starts with `/` or Windows drive form).
/// A source file that lives OUTSIDE the map directory produces a `../`-escaping
/// relative path whose `..` chain grows with the nesting depth — reconstructing
/// the full absolute path and leaking USERNAME + directory layout.
///
/// Covers BOTH output modes to prevent the per-mode divergence PF-004 describes:
/// - sidecar map: `map_dir = effective_parent(out_path)` (absolute, deep)
/// - inline stdout: `map_dir = CWD` (process runs from a deep directory)
///
/// Assertion: no source entry contains `../` components, and no entry contains
/// the random source-tempdir name that would confirm path reconstruction.
#[test]
fn sm_sec3_dotdot_escape_falls_back_to_basename() {
    let src_dir = tempfile::tempdir().unwrap();
    let out_dir = tempfile::tempdir().unwrap();

    // Record the random dir-name; if it appears in sources[] the path escaped.
    let src_dir_name = src_dir
        .path()
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();

    // Source file is in src_dir — completely separate from the output tree.
    let src_path = src_dir.path().join("input.mds");
    std::fs::write(&src_path, "Hello SEC-3!\n").unwrap();

    // Deep output directory — enough levels that the old relative_path() call
    // produces a long `../../../...` chain back to src_dir under the old code.
    let deep_out_dir = out_dir.path().join("a/b/c/d/e/f/g/h/i/j");
    std::fs::create_dir_all(&deep_out_dir).unwrap();
    let out_path = deep_out_dir.join("out.md");

    // ── sidecar case ─────────────────────────────────────────────────────────
    // map_dir = effective_parent(out_path) = deep_out_dir (absolute).
    // relative_path(deep_out_dir, src_path) escapes via `../` under the old code.
    let result = mds_bin()
        .arg("build")
        .arg(&src_path)
        .arg("--source-map")
        .arg("-o")
        .arg(&out_path)
        .output()
        .expect("mds build (sidecar) should run");
    assert!(
        result.status.success(),
        "sidecar build should succeed; stderr: {}",
        String::from_utf8_lossy(&result.stderr)
    );

    let map_path = deep_out_dir.join("out.md.map");
    let v = read_map_json(&map_path);
    let sidecar_sources = v["sources"].as_array().expect("sources must be array");

    for src in sidecar_sources {
        let s = src.as_str().expect("source must be string");
        // SEC-3: must NOT start with `../` — the `..`-escape guard must have fired.
        assert!(
            !s.starts_with("../"),
            "sidecar sources[] must not contain a `..`-escaping path \
             (SEC-3 guard must fire); got: {s:?}"
        );
        assert_ne!(s, "..", "sidecar sources[] must not be bare `..`");
        // Pre-existing guard: must NOT be an absolute path.
        assert!(
            !s.starts_with('/'),
            "sidecar sources[] must not be absolute; got: {s:?}"
        );
        // Key assertion: the random src-tempdir name must NOT appear.  If it does,
        // the `..` chain reconstructed the filesystem path — the exact leak the
        // PR description claimed was fixed but was not.
        assert!(
            !s.contains(src_dir_name.as_str()),
            "sidecar sources[] must not contain the source tempdir name \
             (path reconstruction leak); dir={src_dir_name:?} entry={s:?}"
        );
    }

    // ── inline stdout case ────────────────────────────────────────────────────
    // map_dir = CWD when -o - is used (PathBuf::new() → abs_map_dir = current_dir).
    // Running from deep_out_dir makes CWD == deep_out_dir, so the relative path
    // from CWD to src_path escapes via `../` under the old code.
    let inline_result = mds_bin()
        .current_dir(&deep_out_dir)
        .arg("build")
        .arg(&src_path)
        .args(["--source-map", "--inline", "-o", "-"])
        .output()
        .expect("mds build --inline should run");
    assert!(
        inline_result.status.success(),
        "inline build should succeed; stderr: {}",
        String::from_utf8_lossy(&inline_result.stderr)
    );

    let stdout = String::from_utf8_lossy(&inline_result.stdout);
    let prefix = "<!--# sourceMappingURL=data:application/json;base64,";
    let suffix = " -->";
    let start = stdout
        .find(prefix)
        .expect("stdout must contain inline source-map carrier");
    let rest = &stdout[start + prefix.len()..];
    let end = rest
        .find(suffix)
        .expect("carrier must be closed with \" -->\"");
    let decoded = base64_decode(&rest[..end]);
    let inline_json: serde_json::Value = serde_json::from_slice(&decoded).unwrap();
    let inline_sources = inline_json["sources"]
        .as_array()
        .expect("inline sources must be array");

    for src in inline_sources {
        let s = src.as_str().expect("source must be string");
        assert!(
            !s.starts_with("../"),
            "inline sources[] must not contain a `..`-escaping path \
             (SEC-3 guard must fire); got: {s:?}"
        );
        assert_ne!(s, "..", "inline sources[] must not be bare `..`");
        assert!(
            !s.starts_with('/'),
            "inline sources[] must not be absolute; got: {s:?}"
        );
        assert!(
            !s.contains(src_dir_name.as_str()),
            "inline sources[] must not contain the source tempdir name \
             (path reconstruction leak); dir={src_dir_name:?} entry={s:?}"
        );
    }
}

// ── SM-18: explicit --source-map without -o → hard error (C2/F3) ─────────────

/// `mds build <file> --source-map -o -` (sidecar + stdout) must fail with a clear
/// message explaining that sidecar mode requires an output file path (C2/F3 explicit-flag case).
///
/// `-o -` routes output to stdout so `output_path` is `None`; without it, builds
/// write next to the source file and no error fires.
#[test]
fn sm18_explicit_sidecar_flag_without_output_hard_errors() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "# Hello\n").unwrap();

    // -o - routes output to stdout, making output_path=None and triggering the hard error.
    let result = mds_bin()
        .args(["build", "--source-map", "-o", "-"])
        .arg(&src)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .expect("mds binary should run");

    assert!(
        !result.status.success(),
        "explicit --source-map -o - must fail (sidecar cannot write to stdout); stderr: {}",
        String::from_utf8_lossy(&result.stderr)
    );
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        stderr.contains("sidecar") || stderr.contains("output file") || stderr.contains("-o"),
        "error must mention sidecar / output-file / -o; got: {stderr:?}"
    );
    // Must also mention alternatives so the user knows what to do.
    assert!(
        stderr.contains("--inline") || stderr.contains("--no-source-map"),
        "error must mention --inline or --no-source-map as alternatives; got: {stderr:?}"
    );
}

// ── SM-19: config source_map without -o → warning + stdout (C2/F3) ───────────

/// `mds build <file> -o -` with `mds.json` setting `source_map=true` must degrade
/// gracefully: write compiled content to stdout, emit a warning on stderr naming the
/// config file, and exit 0 (C2/F3 config-sourced case).
///
/// `-o -` routes output to stdout, making `output_path=None` and triggering the
/// config-degrade path. Without `-o -`, a file build writes next to the source.
#[test]
fn sm19_config_source_map_sidecar_without_output_degrades_with_warning() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "# Hello\n").unwrap();
    // Place an mds.json that sets source_map=true in the same directory.
    std::fs::write(
        dir.path().join("mds.json"),
        r#"{"build": {"source_map": true}}"#,
    )
    .unwrap();

    let result = mds_bin()
        .args(["build", "-o", "-"]) // -o - routes to stdout (output_path=None)
        .arg(&src)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .expect("mds binary should run");

    assert!(
        result.status.success(),
        "config-sourced source_map with -o - must exit 0 (degrade gracefully); \
         stderr: {}",
        String::from_utf8_lossy(&result.stderr)
    );
    // Compiled content should appear on stdout.
    let stdout = String::from_utf8_lossy(&result.stdout);
    assert!(
        !stdout.is_empty(),
        "compiled content must be written to stdout; stdout was empty"
    );
    // A degradation warning must appear on stderr.
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        stderr.contains("source_map") || stderr.contains("mds.json"),
        "warning must mention source_map or mds.json; got: {stderr:?}"
    );
    assert!(
        stderr.contains("warning") || stderr.contains("no effect"),
        "output must look like a warning, not an error; got: {stderr:?}"
    );
}

// ── SM-19q: same but --quiet suppresses the warning ──────────────────────────

/// Same as SM-19 but with `--quiet`: content goes to stdout, no warning emitted.
#[test]
fn sm19q_config_source_map_without_output_quiet_no_warning() {
    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": {"source_map": true}}"#,
    )
    .unwrap();

    let result = mds_bin()
        .args(["build", "--quiet", "-o", "-"]) // -o - routes to stdout
        .arg(&src)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .expect("mds binary should run");

    assert!(
        result.status.success(),
        "--quiet config-sourced source_map with -o - must exit 0; stderr: {}",
        String::from_utf8_lossy(&result.stderr)
    );
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        stderr.is_empty(),
        "--quiet must suppress the degradation warning; got: {stderr:?}"
    );
}

// ── SM-20: --embed-sources without --source-map → warning (C3/D6) ────────────

/// When `mds.json` sets `embed_sources=true` but `source_map` is not enabled
/// (neither in config nor via `--source-map`), the build must warn that embed_sources
/// has no effect and still succeed (C3/D6).
///
/// Note: the CLI `--embed-sources` flag requires `--source-map` (Clap enforces this),
/// so the only way embed_sources can be active without source_map is via the config file.
#[test]
fn sm20_embed_sources_without_source_map_warns() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    let out = dir.path().join("out.md");
    std::fs::write(&src, "# Hello\n").unwrap();
    // Config has embed_sources=true but no source_map=true.
    std::fs::write(
        dir.path().join("mds.json"),
        r#"{"build": {"embed_sources": true}}"#,
    )
    .unwrap();

    let result = mds_bin()
        .args(["build", "-o"])
        .arg(&out)
        .arg(&src)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .expect("mds binary should run");

    assert!(
        result.status.success(),
        "config embed_sources without source_map must still succeed (warning only); \
         stderr: {}",
        String::from_utf8_lossy(&result.stderr)
    );
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        stderr.contains("embed_sources") && stderr.contains("no effect"),
        "stderr must warn that embed_sources has no effect without source maps; got: {stderr:?}"
    );
    assert!(
        stderr.contains("warning: embed_sources has no effect without source maps;"),
        "the quiet run below must suppress this exact warning; got: {stderr:?}"
    );

    let quiet_out = dir.path().join("quiet.md");
    let result = mds_bin()
        .args(["build", "--quiet", "-o"])
        .arg(&quiet_out)
        .arg(&src)
        .output()
        .expect("mds binary should run");
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(result.status.success(), "{stderr}");
    assert_eq!(std::fs::read_to_string(quiet_out).unwrap(), "# Hello\n");
    assert_eq!(stderr, "", "quiet file build must not warn");
}

/// Config `embed_sources=true` WITH `source_map=true` must NOT emit the embed_sources
/// warning (the combination is valid and should produce sourcesContent in the map).
#[test]
fn sm20b_embed_sources_with_source_map_no_warning() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    let out = dir.path().join("out.md");
    std::fs::write(&src, "# Hello\n").unwrap();
    // Both embed_sources and source_map are true — no warning expected.
    std::fs::write(
        dir.path().join("mds.json"),
        r#"{"build": {"embed_sources": true, "source_map": true}}"#,
    )
    .unwrap();

    let result = mds_bin()
        .args(["build", "-o"])
        .arg(&out)
        .arg(&src)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .expect("mds binary should run");

    assert!(
        result.status.success(),
        "config embed_sources+source_map must succeed; stderr: {}",
        String::from_utf8_lossy(&result.stderr)
    );
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        !stderr.contains("no effect"),
        "embed_sources+source_map must NOT warn about no effect; got: {stderr:?}"
    );
}

// ── Atomic `.map` sidecars (#227) ────────────────────────────────────────────
//
// Both sidecar writers — the single-file `-o` path and the stdin `-o` path — go through
// `crate::output::atomic_write_file`, so a symlink at `<out>.map` is refused instead of
// being written through. These two tests are the only way to tell the sites apart from
// the CLI: they differ only in how the source reaches the compiler.

/// T-S1: single-file `--source-map` refuses a symlinked sidecar path.
#[test]
fn build_source_map_sidecar_symlink_target_rejected() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("in.mds");
    std::fs::write(&src, "Hello sidecar!\n").unwrap();
    let out = dir.path().join("out.md");
    let real = dir.path().join("real.map");
    std::fs::write(&real, "OLD").unwrap();
    if !make_symlink(&real, &dir.path().join("out.md.map")) {
        return;
    }

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

    let stderr = String::from_utf8_lossy(&result.stderr).into_owned();
    assert_ne!(
        result.status.code(),
        Some(0),
        "a symlinked sidecar path must fail the build; stderr: {stderr}"
    );
    assert!(
        stderr.contains("symlink"),
        "the refusal must say why; got: {stderr:?}"
    );
    assert!(
        out.exists(),
        "the compiled artifact itself is written before the sidecar and must survive"
    );
    assert_eq!(
        std::fs::read_to_string(&real).unwrap(),
        "OLD",
        "the symlink target must not be written through"
    );
}

/// T-S2: the stdin `--source-map` sidecar writer is a second, distinct site — it must
/// refuse a symlinked sidecar path too.
#[test]
fn build_stdin_source_map_sidecar_symlink_target_rejected() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.md");
    let real = dir.path().join("real.map");
    std::fs::write(&real, "OLD").unwrap();
    if !make_symlink(&real, &dir.path().join("out.md.map")) {
        return;
    }

    let mut child = mds_bin()
        .args(["build", "-", "--source-map", "-o", out.to_str().unwrap()])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("mds binary should spawn");

    use std::io::Write as _;
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"---\nname: World\n---\nHello {{name}}!\n")
        .unwrap();

    let result = child.wait_with_output().unwrap();
    let stderr = String::from_utf8_lossy(&result.stderr).into_owned();
    assert_ne!(
        result.status.code(),
        Some(0),
        "a symlinked sidecar path must fail the stdin build; stderr: {stderr}"
    );
    assert!(
        stderr.contains("symlink"),
        "the refusal must say why; got: {stderr:?}"
    );
    assert!(
        out.exists(),
        "the compiled artifact itself is written before the sidecar and must survive"
    );
    assert_eq!(
        std::fs::read_to_string(&real).unwrap(),
        "OLD",
        "the symlink target must not be written through"
    );
}