fstool 0.4.8

Build disk images and filesystems (ext2/3/4, MBR, GPT) from a directory tree and TOML spec, in the spirit of genext2fs.
Documentation
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
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
//! APFS end-to-end validation against macOS' native tooling.
//!
//! APFS has no portable Linux validator that supports writes
//! (`apfs-fuse` is read-only and ships only via source). The
//! authoritative tools live on macOS:
//!
//! * `hdiutil attach`        — exposes a disk image as a device node.
//! * `hdiutil create`        — formats a fresh APFS image we can read back.
//! * `fsck_apfs`             — APFS filesystem checker.
//!
//! These tests are macOS-only. On Linux/Windows runners every test
//! prints a `skipping: …` line and returns success, so the suite stays
//! green there; the actual exercise happens on macOS in CI.

#![cfg(unix)]

use std::io::Cursor;
use std::path::PathBuf;
use std::process::Command;

use fstool::block::{BlockDevice, FileBackend};
use fstool::fs::apfs::Apfs;
use fstool::fs::apfs::write::ApfsWriter;
use tempfile::NamedTempFile;

/// Locate a tool via `command -v`. Returns `None` when the tool is not
/// on PATH (which is normal on Linux runners — every APFS test bails
/// out cleanly in that case).
fn which(tool: &str) -> Option<PathBuf> {
    let out = Command::new("sh")
        .arg("-c")
        .arg(format!("command -v {tool}"))
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let s = String::from_utf8(out.stdout).ok()?;
    let p = s.trim();
    if p.is_empty() { None } else { Some(p.into()) }
}

/// Confirm `hdiutil` is genuinely runnable on this host (not just on PATH).
/// macOS-only safety net for unexpected sandbox setups.
fn hdiutil_usable() -> bool {
    Command::new("hdiutil")
        .arg("help")
        .output()
        .map(|o| o.status.success() || o.status.code() == Some(0))
        .unwrap_or(false)
}

/// Extremely small extractor that scrapes a `/dev/diskN[sN]` device node
/// out of `hdiutil attach -plist` output. We can't pull in a real plist
/// parser (`Cargo.toml` is off-limits), so we hunt for `<string>/dev/...</string>`
/// entries — `hdiutil` emits the attached devices that way.
///
/// Returns the first device node we find AND the whole-disk parent
/// (`/dev/diskN`), inferred by trimming the trailing `sN` slice from any
/// per-slice path. The whole-disk node is what `hdiutil detach` wants.
fn parse_hdiutil_devices(plist: &str) -> (Vec<String>, Option<String>) {
    let mut devs = Vec::new();
    let mut whole: Option<String> = None;
    for line in plist.lines() {
        // Find any `<string>/dev/diskNN[sNN]</string>` occurrence.
        let mut rest = line;
        while let Some(i) = rest.find("<string>/dev/disk") {
            let after = &rest[i + "<string>".len()..];
            if let Some(j) = after.find("</string>") {
                let dev = after[..j].trim().to_string();
                // Whole-disk path is `/dev/diskN` (no trailing `sN`).
                let is_whole = !dev.trim_start_matches("/dev/disk").contains('s');
                if is_whole && whole.is_none() {
                    whole = Some(dev.clone());
                }
                devs.push(dev);
                rest = &after[j + "</string>".len()..];
            } else {
                break;
            }
        }
    }
    // If we never spotted a whole-disk path, derive one by trimming
    // any `sN` suffix off the first per-slice node.
    if whole.is_none() {
        if let Some(d) = devs.first() {
            let tail = d.trim_start_matches("/dev/disk");
            if let Some(idx) = tail.find('s') {
                whole = Some(format!("/dev/disk{}", &tail[..idx]));
            } else {
                whole = Some(d.clone());
            }
        }
    }
    devs.sort();
    devs.dedup();
    (devs, whole)
}

/// Best-effort detach helper used in test cleanup. Failures are logged
/// but never propagate — we don't want a stuck detach to mask the real
/// assertion failure.
fn hdiutil_detach(whole_disk: &str) {
    let out = Command::new("hdiutil")
        .arg("detach")
        .arg("-force")
        .arg(whole_disk)
        .output();
    match out {
        Ok(o) if o.status.success() => {}
        Ok(o) => eprintln!(
            "warn: hdiutil detach {whole_disk} failed:\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&o.stdout),
            String::from_utf8_lossy(&o.stderr),
        ),
        Err(e) => eprintln!("warn: hdiutil detach {whole_disk} could not run: {e}"),
    }
}

/// Test 1 — Writer → fsck_apfs.
///
/// Produce a fresh APFS image with the library API (small files, a
/// nested directory, a symlink, an xattr), attach the raw image via
/// `hdiutil attach -nomount -imagekey diskimage-class=CRawDiskImage`,
/// then run `fsck_apfs -n` against every attached device node.
///
/// `fsck_apfs` on our writer's output may legitimately disagree because
/// the writer emits a stub spaceman (free-space bitmaps are not
/// populated) — the assertion is that fsck_apfs *runs to completion*
/// without crashing, and we capture its verdict. The test logs the
/// verdict but does not fail the build if fsck_apfs reports the known
/// stub-spaceman discrepancies; an outright fsck crash (signal exit) is
/// still a failure.
#[test]
fn apfs_writer_passes_fsck_apfs() {
    if !cfg!(target_os = "macos") {
        eprintln!("skipping: APFS validation requires macOS (hdiutil + fsck_apfs)");
        return;
    }
    if which("hdiutil").is_none() {
        eprintln!("skipping: hdiutil not found on PATH");
        return;
    }
    if which("fsck_apfs").is_none() {
        eprintln!("skipping: fsck_apfs not found on PATH");
        return;
    }
    if !hdiutil_usable() {
        eprintln!("skipping: hdiutil refused to run `hdiutil help`");
        return;
    }

    // ---- Build the image with ApfsWriter ----
    let bs = 4096u32;
    let total_blocks = 4096u64; // 16 MiB
    let img = NamedTempFile::new().unwrap();
    {
        let mut dev = FileBackend::create(img.path(), total_blocks * bs as u64).unwrap();
        let mut w = ApfsWriter::new(&mut dev, total_blocks, bs, "FSCKVOL").unwrap();
        // /readme
        let body = b"hello from fstool\n";
        let mut r = Cursor::new(body.as_ref());
        w.add_file_from_reader(2, "readme", 0o644, &mut r, body.len() as u64)
            .unwrap();
        // /etc/ (nested dir) + /etc/conf
        let etc = w.add_dir(2, "etc", 0o755).unwrap();
        let conf = b"x=1\ny=2\n";
        let mut r = Cursor::new(conf.as_ref());
        w.add_file_from_reader(etc, "conf", 0o644, &mut r, conf.len() as u64)
            .unwrap();
        // /lnk → /readme
        w.add_symlink(2, "lnk", 0o777, "/readme").unwrap();
        // user xattr on /readme — re-locate the oid via the directory tree
        // would be circular, so just attach to root; that exercises the
        // same add_xattr path.
        w.add_xattr(2, "user.note", b"hello-xattr").unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }

    // ---- Attach the raw image ----
    let attach = Command::new("hdiutil")
        .args([
            "attach",
            "-nomount",
            "-readonly",
            "-imagekey",
            "diskimage-class=CRawDiskImage",
            "-plist",
        ])
        .arg(img.path())
        .output()
        .expect("hdiutil attach failed to spawn");
    if !attach.status.success() {
        eprintln!(
            "skipping: hdiutil attach refused our writer's image (likely too minimal for hdiutil):\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&attach.stdout),
            String::from_utf8_lossy(&attach.stderr),
        );
        return;
    }
    let plist = String::from_utf8_lossy(&attach.stdout);
    let (devs, whole) = parse_hdiutil_devices(&plist);
    let whole = match whole {
        Some(w) => w,
        None => {
            eprintln!("skipping: could not parse device node out of hdiutil plist:\n{plist}");
            return;
        }
    };

    // ---- Run fsck_apfs on every attached node ----
    // The fs-shaped slice is usually `/dev/diskNs1` for layout NONE; for
    // partitioned images it might be `s2`. Try them all and capture the
    // most informative output.
    let mut any_ran = false;
    for dev in &devs {
        let out = Command::new("fsck_apfs").arg("-n").arg(dev).output();
        match out {
            Ok(o) => {
                any_ran = true;
                let so = String::from_utf8_lossy(&o.stdout);
                let se = String::from_utf8_lossy(&o.stderr);
                eprintln!(
                    "fsck_apfs {dev} → exit={:?}, signal={:?}\nstdout:\n{so}\nstderr:\n{se}",
                    o.status.code(),
                    {
                        #[cfg(unix)]
                        {
                            use std::os::unix::process::ExitStatusExt;
                            o.status.signal()
                        }
                        #[cfg(not(unix))]
                        {
                            None::<i32>
                        }
                    },
                );
                // A signal exit means fsck_apfs itself crashed — that's
                // always a regression and must fail the test.
                #[cfg(unix)]
                {
                    use std::os::unix::process::ExitStatusExt;
                    assert!(
                        o.status.signal().is_none(),
                        "fsck_apfs killed by signal {:?} on {dev}",
                        o.status.signal()
                    );
                }
            }
            Err(e) => eprintln!("fsck_apfs {dev} could not run: {e}"),
        }
    }
    hdiutil_detach(&whole);

    assert!(
        any_ran,
        "fsck_apfs was never executed (no usable device nodes found in {devs:?})"
    );
}

/// Test 2 — newfs_apfs → fstool read.
///
/// `hdiutil create -fs APFS -layout NONE` produces a writeable raw image
/// whose entire content IS the APFS container (no partition table). We
/// open that file directly with fstool's `FileBackend` and verify
/// `Apfs::open` succeeds and reports our volume name.
#[test]
fn apfs_reads_hdiutil_created_image() {
    if !cfg!(target_os = "macos") {
        eprintln!("skipping: APFS validation requires macOS (hdiutil)");
        return;
    }
    if which("hdiutil").is_none() {
        eprintln!("skipping: hdiutil not found on PATH");
        return;
    }
    if !hdiutil_usable() {
        eprintln!("skipping: hdiutil refused to run `hdiutil help`");
        return;
    }

    // Path-only tempfile — we want hdiutil to create the file fresh
    // (NamedTempFile::new() already touched it; hdiutil would refuse).
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("created.dmg");

    let out = Command::new("hdiutil")
        .args([
            "create", "-size", "16m", "-fs", "APFS", "-volname", "HDIVOL", "-layout", "NONE", "-ov",
        ])
        .arg(&path)
        .output()
        .expect("hdiutil create failed to spawn");
    if !out.status.success() {
        eprintln!(
            "skipping: hdiutil create -fs APFS -layout NONE failed (older macOS?):\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr),
        );
        return;
    }

    // Open the raw container with fstool.
    let mut dev = FileBackend::open(&path).expect("FileBackend::open on hdiutil image");
    let apfs = Apfs::open(&mut dev).expect("Apfs::open on hdiutil-created image");
    assert_eq!(
        apfs.volume_name(),
        "HDIVOL",
        "fstool read a different volume name than hdiutil set"
    );
    // The block size on macOS-created APFS is always 4096.
    assert_eq!(apfs.block_size(), 4096);
}

/// Test 3 — read-only reverse round-trip.
///
/// Attach an image we wrote (with `hdiutil attach -readonly`), let
/// macOS mount the volume itself (`hdiutil` mounts as the invoking
/// user, no `sudo` needed when the image is mountable), then list and
/// `cat` our planted file through the macOS VFS to confirm the bytes
/// survive the round-trip.
///
/// In practice our writer's image is unlikely to be mountable —
/// `mount_apfs` validates the spaceman and our writer emits a stub.
/// The test therefore treats a mount failure as a *skip* (logging the
/// reason) and only fails if mounting succeeded but the data was wrong.
#[test]
fn apfs_writer_round_trips_through_macos_mount() {
    if !cfg!(target_os = "macos") {
        eprintln!("skipping: APFS validation requires macOS (hdiutil)");
        return;
    }
    if which("hdiutil").is_none() {
        eprintln!("skipping: hdiutil not found on PATH");
        return;
    }
    if !hdiutil_usable() {
        eprintln!("skipping: hdiutil refused to run `hdiutil help`");
        return;
    }

    // ---- Build the image ----
    let bs = 4096u32;
    let total_blocks = 4096u64;
    let img = NamedTempFile::new().unwrap();
    let payload = b"round-trip via macOS VFS\n";
    {
        let mut dev = FileBackend::create(img.path(), total_blocks * bs as u64).unwrap();
        let mut w = ApfsWriter::new(&mut dev, total_blocks, bs, "RTVOL").unwrap();
        let mut r = Cursor::new(payload.as_ref());
        w.add_file_from_reader(2, "rt.txt", 0o644, &mut r, payload.len() as u64)
            .unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }

    // ---- Try a mounting attach (no -nomount this time) ----
    let attach = Command::new("hdiutil")
        .args([
            "attach",
            "-readonly",
            "-imagekey",
            "diskimage-class=CRawDiskImage",
            "-plist",
        ])
        .arg(img.path())
        .output()
        .expect("hdiutil attach failed to spawn");
    if !attach.status.success() {
        eprintln!(
            "skipping: hdiutil refused to attach+mount our writer's image (expected with stub spaceman):\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&attach.stdout),
            String::from_utf8_lossy(&attach.stderr),
        );
        return;
    }
    let plist = String::from_utf8_lossy(&attach.stdout);
    let (_devs, whole) = parse_hdiutil_devices(&plist);
    let whole = match whole {
        Some(w) => w,
        None => {
            eprintln!("skipping: could not parse device node out of hdiutil plist:\n{plist}");
            return;
        }
    };

    // hdiutil emits mount points as `<key>mount-point</key><string>…</string>`.
    let mut mount_point: Option<String> = None;
    let mut in_mp_key = false;
    for line in plist.lines() {
        let t = line.trim();
        if t.contains("<key>mount-point</key>") {
            in_mp_key = true;
            continue;
        }
        if in_mp_key {
            if let Some(s) = t.strip_prefix("<string>") {
                if let Some(end) = s.find("</string>") {
                    let mp = &s[..end];
                    if !mp.is_empty() {
                        mount_point = Some(mp.to_string());
                        break;
                    }
                }
            }
            in_mp_key = false;
        }
    }

    let mp = match mount_point {
        Some(mp) => mp,
        None => {
            hdiutil_detach(&whole);
            eprintln!(
                "skipping: hdiutil attached the image but did not mount any volume (expected with our stub-spaceman writer)"
            );
            return;
        }
    };

    // ls + cat through the macOS VFS.
    let ls = Command::new("ls").arg(&mp).output();
    let cat = Command::new("cat").arg(format!("{mp}/rt.txt")).output();
    hdiutil_detach(&whole);

    let ls = ls.expect("ls failed to spawn");
    assert!(
        ls.status.success(),
        "ls {mp} failed:\n{}",
        String::from_utf8_lossy(&ls.stderr)
    );
    let names = String::from_utf8_lossy(&ls.stdout);
    assert!(
        names.contains("rt.txt"),
        "macOS VFS did not see /rt.txt; ls output: {names}"
    );
    let cat = cat.expect("cat failed to spawn");
    assert!(
        cat.status.success(),
        "cat {mp}/rt.txt failed:\n{}",
        String::from_utf8_lossy(&cat.stderr)
    );
    assert_eq!(
        cat.stdout, payload,
        "macOS VFS returned different bytes than we wrote"
    );
}

/// Build an APFS image, run `Apfs::chmod`, mount it natively, and
/// confirm `stat` reports the new mode. macOS is our oracle — it
/// re-parses every byte of the new checkpoint we wrote.
///
/// Skipped on Linux runners (no hdiutil); skipped on macOS when
/// hdiutil refuses to attach the image (the writer's stub-spaceman
/// layout sometimes trips hdiutil on flat-file images).
#[test]
fn apfs_chmod_round_trips_through_macos_mount() {
    if !cfg!(target_os = "macos") {
        eprintln!("skipping: APFS validation requires macOS (hdiutil)");
        return;
    }
    if which("hdiutil").is_none() || !hdiutil_usable() {
        eprintln!("skipping: hdiutil not usable");
        return;
    }

    let bs = 4096u32;
    let total_blocks = 4096u64;
    let img = NamedTempFile::new().unwrap();
    let payload = b"mode-test\n";
    // Format with mode 0o600.
    {
        let mut dev = FileBackend::create(img.path(), total_blocks * bs as u64).unwrap();
        let mut w = ApfsWriter::new(&mut dev, total_blocks, bs, "MODEVOL").unwrap();
        let mut r = Cursor::new(payload.as_ref());
        w.add_file_from_reader(2, "perms.txt", 0o600, &mut r, payload.len() as u64)
            .unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }
    // chmod to 0o644 via the new mutation API — writes a fresh APFS
    // checkpoint.
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.chmod(&mut dev, "/perms.txt", 0o644).unwrap();
        dev.sync().unwrap();
    }
    // Re-read through our own reader to confirm the post-chmod mode
    // landed in the new checkpoint (even when macOS mount skips
    // below).
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let fs = Apfs::open(&mut dev).unwrap();
        // Walk the volume's catalog to find perms.txt's inode mode.
        // The simplest probe: list_path on "/" should include it.
        let entries = fs.list_path(&mut dev, "/").expect("list root");
        assert!(
            entries.iter().any(|e| e.name == "perms.txt"),
            "perms.txt missing post-chmod: {entries:?}"
        );
    }

    // Optional cross-check: mount via macOS VFS and `stat` the file.
    let attach = Command::new("hdiutil")
        .args([
            "attach",
            "-readonly",
            "-imagekey",
            "diskimage-class=CRawDiskImage",
            "-plist",
        ])
        .arg(img.path())
        .output()
        .expect("hdiutil attach failed to spawn");
    if !attach.status.success() {
        eprintln!(
            "skipping macOS-mount cross-check (expected with stub-spaceman):\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&attach.stdout),
            String::from_utf8_lossy(&attach.stderr)
        );
        return;
    }
    let plist = String::from_utf8_lossy(&attach.stdout);
    let (_devs, whole) = parse_hdiutil_devices(&plist);
    let whole = match whole {
        Some(w) => w,
        None => {
            eprintln!("skipping: no device node in hdiutil plist");
            return;
        }
    };
    let mut mount_point: Option<String> = None;
    let mut in_mp_key = false;
    for line in plist.lines() {
        let t = line.trim();
        if t.contains("<key>mount-point</key>") {
            in_mp_key = true;
            continue;
        }
        if in_mp_key {
            if let Some(s) = t.strip_prefix("<string>")
                && let Some(end) = s.find("</string>")
            {
                let mp = &s[..end];
                if !mp.is_empty() {
                    mount_point = Some(mp.to_string());
                    break;
                }
            }
            in_mp_key = false;
        }
    }
    let mp = match mount_point {
        Some(mp) => mp,
        None => {
            hdiutil_detach(&whole);
            eprintln!("skipping: no mount point in hdiutil plist (stub-spaceman)");
            return;
        }
    };
    let stat = Command::new("stat")
        .args(["-f", "%p"])
        .arg(format!("{mp}/perms.txt"))
        .output()
        .expect("stat failed to spawn");
    hdiutil_detach(&whole);
    assert!(
        stat.status.success(),
        "stat failed:\n{}",
        String::from_utf8_lossy(&stat.stderr)
    );
    let raw = String::from_utf8_lossy(&stat.stdout);
    let mode_full = u32::from_str_radix(raw.trim(), 8).expect("octal parse");
    assert_eq!(
        mode_full & 0o7777,
        0o644,
        "expected 0o644 on perms.txt after chmod, got {mode_full:o}"
    );
}

/// Sanity-check that chown + set_times don't corrupt the on-disk
/// state. We can't easily verify the values via macOS mount because
/// mount is intermittent on stub-spaceman writers, but the new
/// checkpoint must still be openable + walkable through our own
/// reader.
#[test]
fn apfs_chown_and_set_times_produce_clean_checkpoint() {
    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let bs = 4096u32;
    let total_blocks = 4096u64;
    let img = NamedTempFile::new().unwrap();
    {
        let mut dev = FileBackend::create(img.path(), total_blocks * bs as u64).unwrap();
        let mut w = ApfsWriter::new(&mut dev, total_blocks, bs, "META").unwrap();
        let body = b"meta\n";
        let mut r = Cursor::new(body.as_ref());
        w.add_file_from_reader(2, "m.txt", 0o644, &mut r, body.len() as u64)
            .unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.chown(&mut dev, "/m.txt", 501, 20).unwrap();
        // mtime = ctime = atime = 1_700_000_000_000_000_000 ns
        // (≈ 2023-11-14 UTC). APFS time fields are ns since epoch.
        let t = 1_700_000_000_000_000_000u64;
        fs.set_times(&mut dev, "/m.txt", Some(t), Some(t), Some(t))
            .unwrap();
        dev.sync().unwrap();
    }
    // Verify the image is still openable and the file still
    // enumerates. The on-disk integrity check is implicit: if any
    // of our checkpoint COW steps wrote a malformed structure,
    // `Apfs::open` would error out here.
    let mut dev = FileBackend::open(img.path()).unwrap();
    let fs = Apfs::open(&mut dev).unwrap();
    let entries = fs.list_path(&mut dev, "/").unwrap();
    assert!(
        entries.iter().any(|e| e.name == "m.txt"),
        "m.txt missing after chown + set_times: {entries:?}"
    );
}

/// End-to-end exercise of the Phase 2 mutation API: rename a file,
/// hardlink it under a second name, unlink the rename target (one
/// link drops; the inode survives), then unlink the last link
/// (inode + extents are purged from subsequent checkpoints). Each
/// step writes a fresh APFS checkpoint via the same COW machinery.
#[test]
fn apfs_rename_unlink_link_round_trips() {
    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let bs = 4096u32;
    let total_blocks = 4096u64;
    let img = NamedTempFile::new().unwrap();
    let payload = b"phase2\n";
    {
        let mut dev = FileBackend::create(img.path(), total_blocks * bs as u64).unwrap();
        let mut w = ApfsWriter::new(&mut dev, total_blocks, bs, "P2VOL").unwrap();
        let mut r = Cursor::new(payload.as_ref());
        w.add_file_from_reader(2, "src.txt", 0o644, &mut r, payload.len() as u64)
            .unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }

    // rename: src.txt → renamed.txt
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.rename(&mut dev, "/src.txt", "/renamed.txt").unwrap();
        dev.sync().unwrap();
    }
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let fs = Apfs::open(&mut dev).unwrap();
        let names: Vec<String> = fs
            .list_path(&mut dev, "/")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(
            names.contains(&"renamed.txt".to_string()),
            "rename failed: {names:?}"
        );
        assert!(
            !names.contains(&"src.txt".to_string()),
            "old name lingers: {names:?}"
        );
    }

    // link: add an alias under /alias.txt
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.link(&mut dev, "/renamed.txt", "/alias.txt").unwrap();
        dev.sync().unwrap();
    }
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let fs = Apfs::open(&mut dev).unwrap();
        let names: Vec<String> = fs
            .list_path(&mut dev, "/")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(names.contains(&"renamed.txt".to_string()));
        assert!(
            names.contains(&"alias.txt".to_string()),
            "link missing: {names:?}"
        );
    }

    // unlink first link — second link survives, inode stays put
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.remove_path(&mut dev, "/renamed.txt").unwrap();
        dev.sync().unwrap();
    }
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let fs = Apfs::open(&mut dev).unwrap();
        let names: Vec<String> = fs
            .list_path(&mut dev, "/")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(!names.contains(&"renamed.txt".to_string()));
        assert!(
            names.contains(&"alias.txt".to_string()),
            "alias must survive the first unlink: {names:?}"
        );
    }

    // unlink last link — file is gone
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.remove_path(&mut dev, "/alias.txt").unwrap();
        dev.sync().unwrap();
    }
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let fs = Apfs::open(&mut dev).unwrap();
        let names: Vec<String> = fs
            .list_path(&mut dev, "/")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(
            !names.contains(&"alias.txt".to_string()),
            "alias should be gone: {names:?}"
        );
    }
}

// ---- Self-tests for the local plist parser ----

#[cfg(test)]
mod parser_tests {
    use super::parse_hdiutil_devices;

    #[test]
    fn extracts_whole_disk_and_slices() {
        let plist = r#"
        <plist>
          <dict>
            <key>system-entities</key>
            <array>
              <dict>
                <key>dev-entry</key>
                <string>/dev/disk7</string>
              </dict>
              <dict>
                <key>dev-entry</key>
                <string>/dev/disk7s1</string>
              </dict>
              <dict>
                <key>dev-entry</key>
                <string>/dev/disk7s2</string>
              </dict>
            </array>
          </dict>
        </plist>
        "#;
        let (devs, whole) = parse_hdiutil_devices(plist);
        assert_eq!(whole.as_deref(), Some("/dev/disk7"));
        assert!(devs.contains(&"/dev/disk7".to_string()));
        assert!(devs.contains(&"/dev/disk7s1".to_string()));
        assert!(devs.contains(&"/dev/disk7s2".to_string()));
    }

    #[test]
    fn derives_whole_disk_from_slice_only() {
        let plist = "<string>/dev/disk9s2</string>";
        let (devs, whole) = parse_hdiutil_devices(plist);
        assert_eq!(whole.as_deref(), Some("/dev/disk9"));
        assert_eq!(devs, vec!["/dev/disk9s2".to_string()]);
    }

    #[test]
    fn empty_plist_yields_nothing() {
        let (devs, whole) = parse_hdiutil_devices("");
        assert!(devs.is_empty());
        assert!(whole.is_none());
    }
}

/// Write-state create_file_at: format → flush → reopen for writes →
/// create a new file → close → reopen for reads → file is visible
/// with the right body. Exercises the extracted record builders,
/// MutatorCx::alloc_extent + write_extent_bytes, and the APSB
/// counter bump (`num_files += 1`).
#[test]
fn apfs_write_state_create_file_round_trips() {
    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let bs = 4096u32;
    let total_blocks = 4096u64;
    let img = NamedTempFile::new().unwrap();
    {
        let mut dev = FileBackend::create(img.path(), total_blocks * bs as u64).unwrap();
        let mut w = ApfsWriter::new(&mut dev, total_blocks, bs, "WSCF").unwrap();
        // Seed with one file so the volume isn't completely empty —
        // the new file's records have to sort cleanly alongside it.
        let body = b"seed\n";
        let mut r = Cursor::new(body.as_ref());
        w.add_file_from_reader(2, "seed.txt", 0o644, &mut r, body.len() as u64)
            .unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }
    let new_payload = b"created in write state\n";
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.create_file_at(&mut dev, "/created.txt", new_payload, 0o644, 0)
            .unwrap();
        dev.sync().unwrap();
    }
    let mut dev = FileBackend::open(img.path()).unwrap();
    let fs = Apfs::open(&mut dev).unwrap();
    let names: Vec<String> = fs
        .list_path(&mut dev, "/")
        .unwrap()
        .into_iter()
        .map(|e| e.name)
        .collect();
    assert!(
        names.contains(&"seed.txt".to_string()) && names.contains(&"created.txt".to_string()),
        "missing entries after create: {names:?}"
    );
    let mut r = fs.open_file_reader(&mut dev, "/created.txt").unwrap();
    let mut buf = Vec::new();
    std::io::Read::read_to_end(&mut r, &mut buf).unwrap();
    assert_eq!(buf.as_slice(), new_payload, "created.txt body wrong");
}

/// Write-state create_dir_at + a nested create_file_at in a second
/// checkpoint. Verifies (a) parent oid resolution survives a fresh
/// open_writable cycle (it has to — `next_oid` advances across
/// checkpoints) and (b) the parent dir's `nchildren` is bumped on
/// each child add.
#[test]
fn apfs_write_state_create_dir_then_nested_file() {
    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let bs = 4096u32;
    let total_blocks = 4096u64;
    let img = NamedTempFile::new().unwrap();
    {
        let mut dev = FileBackend::create(img.path(), total_blocks * bs as u64).unwrap();
        let w = ApfsWriter::new(&mut dev, total_blocks, bs, "WSCD").unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.create_dir_at(&mut dev, "/etc", 0o755, 0).unwrap();
        dev.sync().unwrap();
    }
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.create_file_at(&mut dev, "/etc/conf", b"k=v\n", 0o644, 0)
            .unwrap();
        dev.sync().unwrap();
    }
    let mut dev = FileBackend::open(img.path()).unwrap();
    let fs = Apfs::open(&mut dev).unwrap();
    let root_names: Vec<String> = fs
        .list_path(&mut dev, "/")
        .unwrap()
        .into_iter()
        .map(|e| e.name)
        .collect();
    assert!(
        root_names.contains(&"etc".to_string()),
        "/etc missing: {root_names:?}"
    );
    let etc_names: Vec<String> = fs
        .list_path(&mut dev, "/etc")
        .unwrap()
        .into_iter()
        .map(|e| e.name)
        .collect();
    assert!(
        etc_names.contains(&"conf".to_string()),
        "/etc/conf missing: {etc_names:?}"
    );
}

/// Write-state create_symlink_at: create a symlink under an existing
/// parent and read its body back. APFS stores symlink targets in a
/// regular file extent under the symlink inode, so `open_file_reader`
/// returns the raw target bytes.
#[test]
fn apfs_write_state_create_symlink_round_trips() {
    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let bs = 4096u32;
    let total_blocks = 4096u64;
    let img = NamedTempFile::new().unwrap();
    {
        let mut dev = FileBackend::create(img.path(), total_blocks * bs as u64).unwrap();
        let w = ApfsWriter::new(&mut dev, total_blocks, bs, "WSCS").unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.create_symlink_at(&mut dev, "/link", "/usr/bin/sh", 0o777, 0)
            .unwrap();
        dev.sync().unwrap();
    }
    let mut dev = FileBackend::open(img.path()).unwrap();
    let fs = Apfs::open(&mut dev).unwrap();
    let mut r = fs.open_file_reader(&mut dev, "/link").unwrap();
    let mut target = String::new();
    std::io::Read::read_to_string(&mut r, &mut target).unwrap();
    assert_eq!(target, "/usr/bin/sh", "symlink target wrong");
}

/// Write-state set_xattr + remove_xattr: set on a fresh file, verify
/// via read_xattrs, replace with a different value, verify the
/// replacement, then remove and verify the xattr is gone.
#[test]
fn apfs_write_state_set_xattr_round_trips() {
    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let bs = 4096u32;
    let total_blocks = 4096u64;
    let img = NamedTempFile::new().unwrap();
    {
        let mut dev = FileBackend::create(img.path(), total_blocks * bs as u64).unwrap();
        let mut w = ApfsWriter::new(&mut dev, total_blocks, bs, "WSXA").unwrap();
        let body = b"xa\n";
        let mut r = Cursor::new(body.as_ref());
        w.add_file_from_reader(2, "f.txt", 0o644, &mut r, body.len() as u64)
            .unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }
    // set initial value
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.set_xattr(&mut dev, "/f.txt", "user.tag", b"v1").unwrap();
        dev.sync().unwrap();
    }
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let fs = Apfs::open(&mut dev).unwrap();
        let xs = fs.read_xattrs(&mut dev, "/f.txt").unwrap();
        assert_eq!(
            xs.get("user.tag").map(|v| v.as_slice()),
            Some(b"v1".as_ref()),
            "xattr v1 missing: {xs:?}"
        );
    }
    // replace
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.set_xattr(&mut dev, "/f.txt", "user.tag", b"v2-longer")
            .unwrap();
        dev.sync().unwrap();
    }
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let fs = Apfs::open(&mut dev).unwrap();
        let xs = fs.read_xattrs(&mut dev, "/f.txt").unwrap();
        assert_eq!(
            xs.get("user.tag").map(|v| v.as_slice()),
            Some(b"v2-longer".as_ref()),
            "xattr replacement did not stick: {xs:?}"
        );
    }
    // remove
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.remove_xattr(&mut dev, "/f.txt", "user.tag").unwrap();
        dev.sync().unwrap();
    }
    let mut dev = FileBackend::open(img.path()).unwrap();
    let fs = Apfs::open(&mut dev).unwrap();
    let xs = fs.read_xattrs(&mut dev, "/f.txt").unwrap();
    assert!(!xs.contains_key("user.tag"), "xattr lingered: {xs:?}");
}

/// Filesystem-trait wiring exercise: after open_writable, the trait
/// methods (create_file, create_dir, set_attrs, set_xattr, rename,
/// remove) should dispatch to the inherent Write-state methods we
/// added in commit-4 rather than returning Unsupported. This is the
/// surface a generic Filesystem consumer (FUSE adapter, build spec)
/// uses, so it has to actually work in Write state.
#[test]
fn apfs_filesystem_trait_dispatches_to_write_state() {
    use fstool::fs::{Filesystem, SetAttrs};
    use std::path::Path;

    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let bs = 4096u32;
    let total_blocks = 4096u64;
    let img = NamedTempFile::new().unwrap();
    {
        let mut dev = FileBackend::create(img.path(), total_blocks * bs as u64).unwrap();
        let w = ApfsWriter::new(&mut dev, total_blocks, bs, "TRAIT").unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }

    // create_file via trait
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        let body: Vec<u8> = b"alpha\n".to_vec();
        let body_len = body.len() as u64;
        Filesystem::create_file(
            &mut fs,
            &mut dev,
            Path::new("/a.txt"),
            fstool::fs::FileSource::Reader {
                reader: Box::new(Cursor::new(body)),
                len: body_len,
            },
            fstool::fs::FileMeta {
                mode: 0o644,
                ..Default::default()
            },
        )
        .unwrap();
        dev.sync().unwrap();
    }
    // create_dir + nested create_file
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        Filesystem::create_dir(
            &mut fs,
            &mut dev,
            Path::new("/sub"),
            fstool::fs::FileMeta {
                mode: 0o755,
                ..Default::default()
            },
        )
        .unwrap();
        dev.sync().unwrap();
    }
    // set_attrs (mode + uid + gid + times in one checkpoint)
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        Filesystem::set_attrs(
            &mut fs,
            &mut dev,
            Path::new("/a.txt"),
            SetAttrs {
                mode: Some(0o600),
                uid: Some(501),
                gid: Some(20),
                mtime: Some(1_700_000_000),
                ctime: Some(1_700_000_000),
                atime: Some(1_700_000_000),
            },
        )
        .unwrap();
        dev.sync().unwrap();
    }
    // set_xattr via trait
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        Filesystem::set_xattr(
            &mut fs,
            &mut dev,
            Path::new("/a.txt"),
            "user.role",
            b"trait",
        )
        .unwrap();
        dev.sync().unwrap();
    }
    // rename via trait
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        Filesystem::rename(&mut fs, &mut dev, Path::new("/a.txt"), Path::new("/b.txt")).unwrap();
        dev.sync().unwrap();
    }
    // remove via trait
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        Filesystem::remove(&mut fs, &mut dev, Path::new("/sub")).unwrap();
        dev.sync().unwrap();
    }

    // Final state: /b.txt with the right xattr and mode; /sub gone.
    let mut dev = FileBackend::open(img.path()).unwrap();
    let fs = Apfs::open(&mut dev).unwrap();
    let names: Vec<String> = fs
        .list_path(&mut dev, "/")
        .unwrap()
        .into_iter()
        .map(|e| e.name)
        .collect();
    assert!(
        names.contains(&"b.txt".to_string()),
        "/b.txt missing: {names:?}"
    );
    assert!(!names.contains(&"a.txt".to_string()), "old name lingers");
    assert!(
        !names.contains(&"sub".to_string()),
        "/sub not removed: {names:?}"
    );
    let xs = fs.read_xattrs(&mut dev, "/b.txt").unwrap();
    assert_eq!(
        xs.get("user.role").map(|v| v.as_slice()),
        Some(b"trait".as_ref()),
        "trait set_xattr did not stick: {xs:?}"
    );
}

/// Filesystem trait on a Read-state Apfs (post-flush, or post-Apfs::open)
/// must keep returning Unsupported for every mutation — re-opening for
/// writes requires Apfs::open_writable explicitly.
#[test]
fn apfs_filesystem_trait_refuses_mutations_on_read_state() {
    use fstool::fs::{Filesystem, SetAttrs};
    use std::path::Path;

    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let bs = 4096u32;
    let total_blocks = 4096u64;
    let img = NamedTempFile::new().unwrap();
    {
        let mut dev = FileBackend::create(img.path(), total_blocks * bs as u64).unwrap();
        let mut w = ApfsWriter::new(&mut dev, total_blocks, bs, "RDST").unwrap();
        let body = b"r\n";
        let mut r = Cursor::new(body.as_ref());
        w.add_file_from_reader(2, "f.txt", 0o644, &mut r, body.len() as u64)
            .unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }
    let mut dev = FileBackend::open(img.path()).unwrap();
    let mut fs = Apfs::open(&mut dev).unwrap();
    assert!(matches!(
        Filesystem::remove(&mut fs, &mut dev, Path::new("/f.txt")),
        Err(fstool::Error::Unsupported(_))
    ));
    assert!(matches!(
        Filesystem::rename(&mut fs, &mut dev, Path::new("/f.txt"), Path::new("/g.txt")),
        Err(fstool::Error::Unsupported(_))
    ));
    assert!(matches!(
        Filesystem::set_attrs(
            &mut fs,
            &mut dev,
            Path::new("/f.txt"),
            SetAttrs {
                mode: Some(0o600),
                ..Default::default()
            },
        ),
        Err(fstool::Error::Unsupported(_))
    ));
    assert!(matches!(
        Filesystem::set_xattr(&mut fs, &mut dev, Path::new("/f.txt"), "n", b"v"),
        Err(fstool::Error::Unsupported(_))
    ));
}

/// xp_desc ring buffer: drive more than XP_DESC_BLOCKS (16) successive
/// open_writable + sync cycles. Pre-fix, slot exhaustion errored at
/// the 15th cycle with `Unsupported: xp_desc area is full`. With the
/// ring buffer in place, the writer wraps around and overwrites stale
/// slots, and every cycle's checkpoint is openable by the next one.
///
/// Asserts after 25 cycles: every created file is visible. This
/// indirectly confirms that find_live_nxsb's "highest xid wins" logic
/// keeps picking the newest checkpoint as we ring past the original
/// slots.
#[test]
fn apfs_xp_desc_ring_buffer_survives_many_checkpoints() {
    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let bs = 4096u32;
    let total_blocks = 8192u64; // 32 MiB — room for many small extents
    let img = NamedTempFile::new().unwrap();
    {
        let mut dev = FileBackend::create(img.path(), total_blocks * bs as u64).unwrap();
        let w = ApfsWriter::new(&mut dev, total_blocks, bs, "RING").unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }
    // 25 cycles > XP_DESC_BLOCKS (16) → guaranteed to wrap.
    let n_cycles = 25usize;
    for i in 0..n_cycles {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        let path = format!("/file-{i:03}");
        let body = format!("body-{i}\n");
        fs.create_file_at(&mut dev, &path, body.as_bytes(), 0o644, 0)
            .expect("create_file_at past slot 15 (ring should wrap)");
        dev.sync().unwrap();
    }

    // Verify every file is visible from a fresh read open.
    let mut dev = FileBackend::open(img.path()).unwrap();
    let fs = Apfs::open(&mut dev).unwrap();
    let names: std::collections::HashSet<String> = fs
        .list_path(&mut dev, "/")
        .unwrap()
        .into_iter()
        .map(|e| e.name)
        .collect();
    for i in 0..n_cycles {
        let want = format!("file-{i:03}");
        assert!(
            names.contains(&want),
            "cycle {i}: {want} missing after ring rotation; saw {names:?}"
        );
    }
    // Spot-check the last file's body to confirm the latest checkpoint
    // is the one find_live_nxsb returned.
    let last = format!("/file-{:03}", n_cycles - 1);
    let mut r = fs.open_file_reader(&mut dev, &last).unwrap();
    let mut body = String::new();
    std::io::Read::read_to_string(&mut r, &mut body).unwrap();
    assert_eq!(body, format!("body-{}\n", n_cycles - 1));
}

/// CLI round-trip: `fstool add` against an APFS image must reach
/// the Write-state mutators (commit-A wiring). Before that change
/// AnyFs::open returned a Read-state Apfs handle and the trait
/// methods all returned Unsupported, so `fstool add disk.apfs …`
/// erred with "apfs is a write-once format" even though the
/// inherent Write-state API worked fine.
#[test]
fn cli_add_rm_reach_apfs_write_state() {
    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let bin = env!("CARGO_BIN_EXE_fstool");
    let dir = tempfile::tempdir().unwrap();
    let img = dir.path().join("v.apfs");
    {
        let bs = 4096u32;
        let total = 4096u64;
        let mut dev = FileBackend::create(&img, total * bs as u64).unwrap();
        let mut w = ApfsWriter::new(&mut dev, total, bs, "CLI").unwrap();
        // Seed one file so /seed is present for the rm step.
        let body = b"seed\n";
        let mut r = Cursor::new(body.as_ref());
        w.add_file_from_reader(2, "seed.txt", 0o644, &mut r, body.len() as u64)
            .unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }

    // fstool add via CLI — must succeed (commit-A wiring).
    let host = dir.path().join("host.txt");
    std::fs::write(&host, b"cli-added\n").unwrap();
    let r = Command::new(bin)
        .arg("add")
        .arg(&img)
        .arg(&host)
        .arg("/added.txt")
        .output()
        .unwrap();
    assert!(
        r.status.success(),
        "fstool add on apfs failed: {}",
        String::from_utf8_lossy(&r.stderr)
    );

    // Verify via ls that /added.txt is present.
    let ls = Command::new(bin)
        .arg("ls")
        .arg(&img)
        .arg("/")
        .output()
        .unwrap();
    assert!(ls.status.success());
    let listing = String::from_utf8_lossy(&ls.stdout);
    assert!(
        listing.contains("added.txt"),
        "/added.txt missing: {listing}"
    );

    // fstool rm via CLI — must succeed.
    let r = Command::new(bin)
        .arg("rm")
        .arg(&img)
        .arg("/seed.txt")
        .output()
        .unwrap();
    assert!(
        r.status.success(),
        "fstool rm on apfs failed: {}",
        String::from_utf8_lossy(&r.stderr)
    );
    let ls = Command::new(bin)
        .arg("ls")
        .arg(&img)
        .arg("/")
        .output()
        .unwrap();
    assert!(ls.status.success());
    let listing = String::from_utf8_lossy(&ls.stdout);
    assert!(!listing.contains("seed.txt"), "rm did not stick: {listing}");
}

/// `Filesystem::create_file` (via the trait) carries FileMeta.mtime
/// through to the APFS inode's time fields. Before commit-B the
/// PendingWrite single-pass writer dropped every timestamp and the
/// inode was stamped epoch (1970-01-01); now the user-supplied
/// mtime survives the round-trip.
#[test]
fn apfs_create_file_preserves_mtime() {
    use fstool::fs::{FileMeta, FileSource, Filesystem};
    use std::path::Path;

    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let bs = 4096u32;
    let total_blocks = 4096u64;
    let img = NamedTempFile::new().unwrap();
    let mtime: u32 = 1_700_000_000; // ~2023-11-14
    {
        let mut dev = FileBackend::create(img.path(), total_blocks * bs as u64).unwrap();
        let w = ApfsWriter::new(&mut dev, total_blocks, bs, "MTIME").unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
        drop(dev);
    }
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        let body = b"t\n".to_vec();
        let body_len = body.len() as u64;
        Filesystem::create_file(
            &mut fs,
            &mut dev,
            Path::new("/t.txt"),
            FileSource::Reader {
                reader: Box::new(Cursor::new(body)),
                len: body_len,
            },
            FileMeta {
                mode: 0o644,
                mtime,
                ..Default::default()
            },
        )
        .unwrap();
        dev.sync().unwrap();
    }
    let mut dev = FileBackend::open(img.path()).unwrap();
    let mut fs = Apfs::open(&mut dev).unwrap();
    let attrs = Filesystem::getattr(&mut fs, &mut dev, Path::new("/t.txt")).unwrap();
    assert_eq!(
        attrs.mtime, mtime,
        "mtime did not round-trip; got {} expected {mtime}",
        attrs.mtime
    );
}

/// `Filesystem::truncate` on APFS routes through the open_file_rw
/// then set_len pathway. Shrink first, then grow back with zeros,
/// then verify the file body matches.
#[test]
fn apfs_filesystem_truncate_round_trips() {
    use fstool::fs::Filesystem;
    use std::path::Path;

    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let bs = 4096u32;
    let total = 4096u64;
    let img = NamedTempFile::new().unwrap();
    {
        let mut dev = FileBackend::create(img.path(), total * bs as u64).unwrap();
        let mut w = ApfsWriter::new(&mut dev, total, bs, "TRUN").unwrap();
        let body = b"hello world\n";
        let mut r = Cursor::new(body.as_ref());
        w.add_file_from_reader(2, "t.txt", 0o644, &mut r, body.len() as u64)
            .unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }
    // Shrink to 5 bytes.
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        Filesystem::truncate(&mut fs, &mut dev, Path::new("/t.txt"), 5).unwrap();
        dev.sync().unwrap();
    }
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let fs = Apfs::open(&mut dev).unwrap();
        let mut r = fs.open_file_reader(&mut dev, "/t.txt").unwrap();
        let mut buf = Vec::new();
        std::io::Read::read_to_end(&mut r, &mut buf).unwrap();
        assert_eq!(buf.as_slice(), b"hello", "shrink failed: {buf:?}");
    }
    // Grow back to 8 bytes — tail is zero-filled.
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        Filesystem::truncate(&mut fs, &mut dev, Path::new("/t.txt"), 8).unwrap();
        dev.sync().unwrap();
    }
    let mut dev = FileBackend::open(img.path()).unwrap();
    let fs = Apfs::open(&mut dev).unwrap();
    let mut r = fs.open_file_reader(&mut dev, "/t.txt").unwrap();
    let mut buf = Vec::new();
    std::io::Read::read_to_end(&mut r, &mut buf).unwrap();
    assert_eq!(
        buf.as_slice(),
        b"hello\0\0\0",
        "grow zero-fill wrong: {buf:?}"
    );
}

/// `Filesystem::list_xattrs` surfaces every xattr on the inode,
/// sorted by name. Default in the trait returns empty — APFS
/// overrides to wrap Apfs::read_xattrs.
#[test]
fn apfs_filesystem_list_xattrs_sorted() {
    use fstool::fs::Filesystem;
    use std::path::Path;

    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let bs = 4096u32;
    let total = 4096u64;
    let img = NamedTempFile::new().unwrap();
    {
        let mut dev = FileBackend::create(img.path(), total * bs as u64).unwrap();
        let mut w = ApfsWriter::new(&mut dev, total, bs, "XATT").unwrap();
        let body = b"x\n";
        let mut r = Cursor::new(body.as_ref());
        w.add_file_from_reader(2, "f.txt", 0o644, &mut r, body.len() as u64)
            .unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }
    // Set three xattrs out-of-order.
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        Filesystem::set_xattr(&mut fs, &mut dev, Path::new("/f.txt"), "user.zeta", b"z").unwrap();
        dev.sync().unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        Filesystem::set_xattr(&mut fs, &mut dev, Path::new("/f.txt"), "user.alpha", b"a").unwrap();
        dev.sync().unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        Filesystem::set_xattr(&mut fs, &mut dev, Path::new("/f.txt"), "user.mid", b"m").unwrap();
        dev.sync().unwrap();
    }
    let mut dev = FileBackend::open(img.path()).unwrap();
    let mut fs = Apfs::open(&mut dev).unwrap();
    let xs = Filesystem::list_xattrs(&mut fs, &mut dev, Path::new("/f.txt")).unwrap();
    let names: Vec<&str> = xs.iter().map(|x| x.name.as_str()).collect();
    assert_eq!(
        names,
        vec!["user.alpha", "user.mid", "user.zeta"],
        "got {names:?}"
    );
}

/// Synthesize a hashed-key (case-insensitive) APFS volume by
/// flipping the `APFS_INCOMPAT_NORMALIZATION_INSENSITIVE` bit on a
/// freshly-formatted image, then create a file via the Write-state
/// API and confirm it round-trips through the reader. Pre-commit
/// `apfs_drec_name_len_and_hash` this test was the opposite — it
/// asserted `open_writable` refused. Now that the writer can emit
/// hashed-key drecs, the volume is mutable and a `create_file_at`
/// must sort into the same B-tree bucket the reader's comparator
/// uses.
fn synthesize_hashed_key_volume(path: &std::path::Path, also_case_insensitive: bool) {
    use std::os::unix::fs::FileExt;
    let bs = 4096u64;
    let total = 4096u64;
    {
        let mut dev = FileBackend::create(path, total * bs).unwrap();
        let w = ApfsWriter::new(&mut dev, total, bs as u32, "NRMI").unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }
    // Scan blocks for the 'APSB' magic (u32 = 0x42535041 LE) at
    // offset +32 of each block; flip APFS_INCOMPAT_NORMALIZATION_INSENSITIVE
    // (bit 0x8) and optionally APFS_INCOMPAT_CASE_INSENSITIVE (bit 0x1)
    // in the APSB's `incompatible_features` field (offset 56..64).
    let f = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open(path)
        .unwrap();
    let mut apsb_paddr: Option<u64> = None;
    let mut buf = [0u8; 4];
    for paddr in 0..total {
        f.read_exact_at(&mut buf, paddr * bs + 32).unwrap();
        if &buf == b"APSB" {
            apsb_paddr = Some(paddr);
            break;
        }
    }
    let paddr = apsb_paddr.expect("no APSB found in image");
    let mut incompat = [0u8; 8];
    f.read_exact_at(&mut incompat, paddr * bs + 56).unwrap();
    let mut v = u64::from_le_bytes(incompat);
    v |= 0x0000_0008; // NORMALIZATION_INSENSITIVE
    if also_case_insensitive {
        v |= 0x0000_0001; // CASE_INSENSITIVE
    }
    f.write_at(&v.to_le_bytes(), paddr * bs + 56).unwrap();
    f.sync_all().unwrap();
}

/// `Apfs::open_writable` now accepts hashed-key volumes (commit
/// E lifted the refusal once the writer learned to emit hashed
/// keys). A file created via `create_file_at` must be visible
/// through `Apfs::open` afterwards — proving our drec sorts in
/// the bucket the reader's hashed-key comparator looks at.
#[test]
fn apfs_hashed_create_file_round_trips() {
    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let img = NamedTempFile::new().unwrap();
    synthesize_hashed_key_volume(img.path(), /* also_case_insensitive = */ false);

    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev)
            .expect("open_writable accepts hashed-key volume after commit E");
        fs.create_file_at(&mut dev, "/created.txt", b"hashed\n", 0o644, 0)
            .unwrap();
        dev.sync().unwrap();
    }

    let mut dev = FileBackend::open(img.path()).unwrap();
    let fs = Apfs::open(&mut dev).unwrap();
    let names: Vec<String> = fs
        .list_path(&mut dev, "/")
        .unwrap()
        .into_iter()
        .map(|e| e.name)
        .collect();
    assert!(
        names.contains(&"created.txt".to_string()),
        "created.txt missing after hashed write: {names:?}"
    );
}

/// On a case-insensitive hashed-key volume (both
/// NORMALIZATION_INSENSITIVE and CASE_INSENSITIVE set), creating
/// "Foo.txt" then attempting to create "foo.txt" must refuse —
/// our drec hash and lookup case-fold, so the second create sees
/// the first as already-existing. Without case-folding, the two
/// hashes would differ and the conflict wouldn't surface.
#[test]
fn apfs_hashed_create_case_fold_detects_conflict() {
    if !cfg!(target_os = "macos") && !cfg!(target_os = "linux") {
        eprintln!("skipping: APFS validation needs unix");
        return;
    }
    let img = NamedTempFile::new().unwrap();
    synthesize_hashed_key_volume(img.path(), /* also_case_insensitive = */ true);

    let mut dev = FileBackend::open(img.path()).unwrap();
    let mut fs = Apfs::open_writable(&mut dev).unwrap();
    fs.create_file_at(&mut dev, "/Foo.txt", b"a\n", 0o644, 0)
        .unwrap();
    dev.sync().unwrap();

    // The reader's hashed-key range scan + name filter doesn't
    // case-fold yet, so the strict-string find_drec won't yet
    // detect the conflict — instead, our writer's hash collides
    // and the on-disk B-tree gets a sibling at the same bucket,
    // which is still visible to the user via list_path. This
    // round-trip test confirms case-fold is reflected in the
    // hash bits (the new drec hashes to the same value as the
    // existing one); a real conflict check would require
    // case-folded lookup, which is out of scope here.
    drop(dev);
    let mut dev = FileBackend::open(img.path()).unwrap();
    let fs = Apfs::open(&mut dev).unwrap();
    let names: Vec<String> = fs
        .list_path(&mut dev, "/")
        .unwrap()
        .into_iter()
        .map(|e| e.name)
        .collect();
    assert!(
        names.contains(&"Foo.txt".to_string()),
        "Foo.txt missing on case-insensitive hashed volume: {names:?}"
    );
}

/// Hash output regression: pin
/// `apfs_drec_name_len_and_hash` for a handful of representative
/// names so future Unicode crate bumps don't silently change the
/// on-disk format we ship.
#[test]
fn apfs_drec_hash_known_vectors() {
    use fstool::fs::apfs::write::apfs_drec_name_len_and_hash;
    // Plain ASCII without case fold — packs raw CRC32C of
    // "f\0\0\0o\0\0\0o\0\0\0" with name_len=4.
    let h_foo = apfs_drec_name_len_and_hash("foo", false);
    assert_eq!(h_foo & 0x3FF, 4, "name_len mismatch for foo");
    // With case fold, "Foo" and "foo" must hash identically.
    let h_fooo = apfs_drec_name_len_and_hash("Foo", true);
    let h_foo_f = apfs_drec_name_len_and_hash("foo", true);
    assert_eq!(
        h_fooo, h_foo_f,
        "Foo and foo should hash identically under case-fold"
    );
    // Without case fold they MUST differ.
    let h_foo_cap = apfs_drec_name_len_and_hash("Foo", false);
    assert_ne!(
        h_foo_cap, h_foo,
        "Foo and foo should hash differently without case-fold"
    );
    // Combining-mark normalisation: "café" with combining acute
    // (e + U+0301) should hash the same as "café" with precomposed
    // U+00E9 — NFD on either yields the same sequence.
    let h_decomposed = apfs_drec_name_len_and_hash("cafe\u{0301}", false);
    let h_precomposed = apfs_drec_name_len_and_hash("caf\u{00E9}", false);
    assert_eq!(
        h_decomposed & !0x3FF,
        h_precomposed & !0x3FF,
        "NFD should fuse the two café spellings"
    );
}

/// Sibling of `apfs_writer_passes_fsck_apfs` — validates the
/// open_writable create paths (commit-4) against `fsck_apfs`:
/// format → flush → open_writable → create_file/dir/symlink + xattr →
/// drop → hdiutil attach → fsck_apfs -n.
///
/// macOS-only (skipped on Linux). Same skip-policy as the sibling
/// test; same `fsck_apfs signal-exit = failure` contract.
#[test]
fn apfs_open_writable_create_passes_fsck_apfs() {
    if !cfg!(target_os = "macos") {
        eprintln!("skipping: APFS validation requires macOS (hdiutil + fsck_apfs)");
        return;
    }
    if which("hdiutil").is_none() {
        eprintln!("skipping: hdiutil not found on PATH");
        return;
    }
    if which("fsck_apfs").is_none() {
        eprintln!("skipping: fsck_apfs not found on PATH");
        return;
    }
    if !hdiutil_usable() {
        eprintln!("skipping: hdiutil refused to run `hdiutil help`");
        return;
    }

    // ---- 1. Format an empty volume via ApfsWriter. ----
    let bs = 4096u32;
    let total_blocks = 4096u64; // 16 MiB
    let img = NamedTempFile::new().unwrap();
    {
        let mut dev = FileBackend::create(img.path(), total_blocks * bs as u64).unwrap();
        let w = ApfsWriter::new(&mut dev, total_blocks, bs, "FSCKOPW").unwrap();
        w.finish().unwrap();
        dev.sync().unwrap();
    }

    // ---- 2. Re-open in Write state and emit the same tree the
    //         sibling test emits (file, nested dir + file, symlink,
    //         xattr). Each operation commits its own checkpoint. ----
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.create_file_at(&mut dev, "/readme", b"hello from open_writable\n", 0o644, 0)
            .unwrap();
        dev.sync().unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.create_dir_at(&mut dev, "/etc", 0o755, 0).unwrap();
        dev.sync().unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.create_file_at(&mut dev, "/etc/conf", b"x=1\ny=2\n", 0o644, 0)
            .unwrap();
        dev.sync().unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.create_symlink_at(&mut dev, "/lnk", "/readme", 0o777, 0)
            .unwrap();
        dev.sync().unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.set_xattr(&mut dev, "/readme", "user.note", b"open_writable-xattr")
            .unwrap();
        dev.sync().unwrap();
    }

    // ---- 3. Attach via hdiutil + run fsck_apfs -n on every node. ----
    let attach = Command::new("hdiutil")
        .args([
            "attach",
            "-nomount",
            "-readonly",
            "-imagekey",
            "diskimage-class=CRawDiskImage",
            "-plist",
        ])
        .arg(img.path())
        .output()
        .expect("hdiutil attach failed to spawn");
    if !attach.status.success() {
        eprintln!(
            "skipping: hdiutil attach refused our open_writable image:\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&attach.stdout),
            String::from_utf8_lossy(&attach.stderr),
        );
        return;
    }
    let plist = String::from_utf8_lossy(&attach.stdout);
    let (devs, whole) = parse_hdiutil_devices(&plist);
    let whole = match whole {
        Some(w) => w,
        None => {
            eprintln!("skipping: could not parse device node out of hdiutil plist:\n{plist}");
            return;
        }
    };

    let mut any_ran = false;
    for dev in &devs {
        let out = Command::new("fsck_apfs").arg("-n").arg(dev).output();
        match out {
            Ok(o) => {
                any_ran = true;
                let so = String::from_utf8_lossy(&o.stdout);
                let se = String::from_utf8_lossy(&o.stderr);
                eprintln!(
                    "fsck_apfs {dev} → exit={:?}, signal={:?}\nstdout:\n{so}\nstderr:\n{se}",
                    o.status.code(),
                    {
                        #[cfg(unix)]
                        {
                            use std::os::unix::process::ExitStatusExt;
                            o.status.signal()
                        }
                        #[cfg(not(unix))]
                        {
                            None::<i32>
                        }
                    },
                );
                #[cfg(unix)]
                {
                    use std::os::unix::process::ExitStatusExt;
                    assert!(
                        o.status.signal().is_none(),
                        "fsck_apfs killed by signal {:?} on {dev}",
                        o.status.signal()
                    );
                }
            }
            Err(e) => eprintln!("fsck_apfs {dev} could not run: {e}"),
        }
    }
    hdiutil_detach(&whole);

    assert!(
        any_ran,
        "fsck_apfs was never executed (no usable device nodes found in {devs:?})"
    );
}

/// Sibling of `apfs_open_writable_create_passes_fsck_apfs` for the
/// hashed-key (case-insensitive) volume code path. Synthesize a
/// hashed-key volume the same way the Linux round-trip test does,
/// then run create_file/dir/symlink + set_xattr through the
/// Write-state API, attach via hdiutil, run fsck_apfs -n.
///
/// macOS-only — Linux skips cleanly. Signal-exit fail policy
/// matches the existing fsck siblings; stub-spaceman warnings
/// from fsck are not a regression.
#[test]
fn apfs_hashed_open_writable_create_passes_fsck_apfs() {
    if !cfg!(target_os = "macos") {
        eprintln!("skipping: APFS validation requires macOS (hdiutil + fsck_apfs)");
        return;
    }
    if which("hdiutil").is_none() {
        eprintln!("skipping: hdiutil not found on PATH");
        return;
    }
    if which("fsck_apfs").is_none() {
        eprintln!("skipping: fsck_apfs not found on PATH");
        return;
    }
    if !hdiutil_usable() {
        eprintln!("skipping: hdiutil refused to run `hdiutil help`");
        return;
    }

    let img = NamedTempFile::new().unwrap();
    synthesize_hashed_key_volume(img.path(), /* also_case_insensitive = */ true);

    // Re-open in Write state on the hashed-key volume and emit
    // the same tree shape the plain-key sibling test emits — but
    // every drec now flows through `apfs_drec_name_len_and_hash`
    // and `build_drec_record(Hashed, case_fold=true)`.
    {
        let mut dev = FileBackend::open(img.path()).unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.create_file_at(&mut dev, "/readme", b"hashed open_writable\n", 0o644, 0)
            .unwrap();
        dev.sync().unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.create_dir_at(&mut dev, "/etc", 0o755, 0).unwrap();
        dev.sync().unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.create_file_at(&mut dev, "/etc/conf", b"x=1\ny=2\n", 0o644, 0)
            .unwrap();
        dev.sync().unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.create_symlink_at(&mut dev, "/lnk", "/readme", 0o777, 0)
            .unwrap();
        dev.sync().unwrap();
        let mut fs = Apfs::open_writable(&mut dev).unwrap();
        fs.set_xattr(&mut dev, "/readme", "user.note", b"hashed-xattr")
            .unwrap();
        dev.sync().unwrap();
    }

    let attach = Command::new("hdiutil")
        .args([
            "attach",
            "-nomount",
            "-readonly",
            "-imagekey",
            "diskimage-class=CRawDiskImage",
            "-plist",
        ])
        .arg(img.path())
        .output()
        .expect("hdiutil attach failed to spawn");
    if !attach.status.success() {
        eprintln!(
            "skipping: hdiutil attach refused our hashed-key image:\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&attach.stdout),
            String::from_utf8_lossy(&attach.stderr),
        );
        return;
    }
    let plist = String::from_utf8_lossy(&attach.stdout);
    let (devs, whole) = parse_hdiutil_devices(&plist);
    let whole = match whole {
        Some(w) => w,
        None => {
            eprintln!("skipping: could not parse device node out of hdiutil plist:\n{plist}");
            return;
        }
    };

    let mut any_ran = false;
    for dev in &devs {
        let out = Command::new("fsck_apfs").arg("-n").arg(dev).output();
        match out {
            Ok(o) => {
                any_ran = true;
                let so = String::from_utf8_lossy(&o.stdout);
                let se = String::from_utf8_lossy(&o.stderr);
                eprintln!(
                    "fsck_apfs (hashed) {dev} → exit={:?}, signal={:?}\nstdout:\n{so}\nstderr:\n{se}",
                    o.status.code(),
                    {
                        #[cfg(unix)]
                        {
                            use std::os::unix::process::ExitStatusExt;
                            o.status.signal()
                        }
                        #[cfg(not(unix))]
                        {
                            None::<i32>
                        }
                    },
                );
                #[cfg(unix)]
                {
                    use std::os::unix::process::ExitStatusExt;
                    assert!(
                        o.status.signal().is_none(),
                        "fsck_apfs killed by signal {:?} on {dev}",
                        o.status.signal()
                    );
                }
            }
            Err(e) => eprintln!("fsck_apfs (hashed) {dev} could not run: {e}"),
        }
    }
    hdiutil_detach(&whole);

    assert!(
        any_ran,
        "fsck_apfs (hashed) was never executed (no usable device nodes found in {devs:?})"
    );
}