kernal-api 0.1.14

Async OS HAL, profiling, symbolization, and allocator instrumentation
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
1952
1953
1954
1955
1956
1957
1958
1959
1960
//! Runtime-artifact identity, permissions, secure-open, replacement, and
//! directory primitives, plus advisory locking, modification-time, reflink
//! copy, parallel directory walking, and glob matching.
//!
//! Callers name the *role* a directory plays for their product -- ephemeral
//! runtime artifacts, persistent state, per-run scratch. Which location on this
//! host plays that role, and how two accounts are kept apart there, is decided
//! here. Callers still own their own layout beneath it: leaf names, extensions,
//! and subdirectories are product conventions, not host mechanics.
//!
//! The rest of this module is one capability, not several, even though it
//! groups locking, timestamps, copying, walking, and matching: every one of
//! them is a place the supported hosts genuinely diverge (advisory-lock
//! semantics, reflink support, filesystem-specific mtime granularity) and a
//! wrapper crate exists only to paper over that divergence. Locking and
//! modification-time setting are implemented natively per host, matching the
//! rest of this file; reflink copy, parallel walking, and glob matching wrap
//! a maintained backend privately, because there is no std equivalent and a
//! hand-rolled reflink ioctl is not something to get wrong silently.

#[cfg(feature = "fs")]
mod temporary;
#[cfg(feature = "fs")]
pub use temporary::{TemporaryDirectory, MAX_TEMP_PREFIX_BYTES};

/// A descriptor the caller already owns and has asked us to write to.
///
/// Deliberately opaque. Callers hold host-specific things -- a `RawFd` on
/// Unix, a `RawHandle` on Windows -- and there is no honest neutral spelling
/// for *what they hold*, so the conversion into this type is host-specific
/// and stays at the caller's edge. What is not host-specific is everything
/// after: writing all of a buffer to it, retrying the partial writes and the
/// interruptions that every host has in its own dialect.
///
/// This borrows. It does not close the descriptor, and it does not extend its
/// lifetime: the caller who opened it still decides when it goes away, and
/// using this after that is the same mistake as using the raw value would be.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RawDescriptor(usize);

impl RawDescriptor {
    /// Wrap a host descriptor value. Host trees call this; callers do not.
    pub(crate) fn from_value(value: usize) -> Self {
        Self(value)
    }

    /// The underlying host value, for the host tree that will use it.
    pub(crate) fn value(self) -> usize {
        self.0
    }
}

pub use crate::fs_write_all_to_descriptor as write_all_to_descriptor;

/// Private ownership of a scratch directory, anchored independently of its
/// pathname. Cleanup remains attached when an ancestor is renamed. Concurrent
/// renames during removal are not guaranteed atomic by the private backend.
#[cfg(feature = "wasm-sketch-worker")]
pub(crate) struct OwnedScratchDirectory {
    directory: Option<crate::ScratchDirectoryAnchor>,
    path: std::path::PathBuf,
}

#[cfg(feature = "wasm-sketch-worker")]
impl OwnedScratchDirectory {
    pub(crate) fn create_in(parent: &std::path::Path) -> std::io::Result<Self> {
        let temporary = tempfile::Builder::new()
            .prefix(".kernal-worker-output-")
            .tempdir_in(parent)?;
        let directory = crate::ScratchDirectoryAnchor::open(temporary.path())?;
        // Transfer cleanup ownership only after acquiring the handle. Never
        // let TempDir's pathname-based Drop remove a replacement directory.
        let path = temporary.keep();
        Ok(Self {
            directory: Some(directory),
            path,
        })
    }

    pub(crate) fn path(&self) -> &std::path::Path {
        &self.path
    }

    pub(crate) fn close(mut self) -> std::io::Result<()> {
        self.directory
            .take()
            .expect("scratch owner is live")
            .remove()
    }
}

#[cfg(feature = "wasm-sketch-worker")]
impl Drop for OwnedScratchDirectory {
    fn drop(&mut self) {
        if let Some(directory) = self.directory.take() {
            let _ = directory.remove();
        }
    }
}

#[cfg(feature = "fs")]
mod async_io;
#[cfg(feature = "fs")]
pub use async_io::AsyncFileIo;

/// Resolve the current user's home directory using native account conventions.
///
/// On Unix, a nonempty `HOME` overrides the account database; missing or empty
/// `HOME` falls back to the account's home. On Windows, uses the user-profile
/// known folder. Returns `None` when the host cannot resolve a home; does not
/// create directories or invent a temporary fallback. Unlike
/// [`super::host::home_dir`], this is not an environment-only host fact.
#[cfg(feature = "fs")]
pub fn user_home_dir() -> Option<std::path::PathBuf> {
    dirs::home_dir()
}

#[cfg(feature = "fs")]
pub use crate::{
    fs_create_dir_all_private as create_dir_all_private,
    fs_create_private_file as create_private_file, fs_decode_path_bytes as decode_path_bytes,
    fs_encode_path_bytes as encode_path_bytes, fs_ensure_dir_private as ensure_dir_private,
    fs_file_identity as file_identity, fs_is_lock_conflict as is_lock_conflict,
    fs_open_lock_file as open_lock_file, fs_open_shared_append as open_shared_append,
    fs_path_identity as path_identity, fs_replace_file as replace_file,
    fs_sync_directory as sync_directory, fs_user_config_dir as user_config_dir,
    fs_user_data_dir as user_data_dir, fs_user_run_data_root as user_run_data_root,
    fs_user_runtime_dir as user_runtime_dir, fs_user_state_dir as user_state_dir,
    FsFileIdentity as FileIdentity,
};

/// Largest byte limit accepted by [`read_private_regular_file_bounded`].
///
/// This is deliberately a hard ceiling as well as a caller-selected limit:
/// this convenience operation returns one allocation rather than a stream.
#[cfg(feature = "fs")]
pub const MAX_PRIVATE_REGULAR_FILE_BYTES: usize = 64 * 1024 * 1024;

/// Largest byte limit accepted by [`read_context_regular_file_bounded`].
///
/// Context collection returns one allocation, so this is a hard facade cap as
/// well as a caller-selected bound.
#[cfg(feature = "fs")]
pub const MAX_CONTEXT_REGULAR_FILE_BYTES: usize = 64 * 1024 * 1024;

/// The final path component's kind, observed without following a link.
#[cfg(feature = "fs")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ContextPathKind {
    /// An ordinary regular file.
    RegularFile,
    /// A directory.
    Directory,
    /// A symbolic link or Windows reparse point.
    Symlink,
    /// A FIFO, device, socket, or another non-regular native object.
    Other,
}

/// Portable metadata for a context path or a coherently-read regular file.
///
/// `identity` is absent for a standalone non-following path observation:
/// obtaining a portable identity there would require opening the path and can
/// change its meaning. A successful bounded read always supplies the identity
/// of its final open handle.
#[cfg(feature = "fs")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContextPathMetadata {
    /// The final component's observed kind.
    pub kind: ContextPathKind,
    /// Length for a regular file; absent for all other kinds.
    pub len: Option<u64>,
    /// Last modification time when the filesystem reports one.
    pub modified: Option<SystemTime>,
    /// Stable identity when observed from an open regular-file handle.
    pub identity: Option<FileIdentity>,
}

/// A bounded regular-file read together with its final-handle observation.
///
/// The native implementation compares identity, length, and modification time
/// before and after reading, then re-identifies the final path without
/// following links. It rejects changes it can observe. This is not an atomic
/// filesystem-tree snapshot: trusted ancestors remain the caller's
/// responsibility, and filesystems with coarse or mutable timestamps can hide
/// an in-place content change. Native open/read calls are synchronous and
/// cannot be forcibly interrupted by this facade.
#[cfg(feature = "fs")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContextFileObservation {
    /// The bytes, bounded by the caller's limit.
    pub bytes: Vec<u8>,
    /// Metadata derived from the final open handle after the read.
    pub metadata: ContextPathMetadata,
}

#[cfg(feature = "fs")]
pub(crate) fn context_path_kind(metadata: &std::fs::Metadata) -> ContextPathKind {
    #[cfg(windows)]
    {
        use std::os::windows::fs::MetadataExt as _;
        if metadata.file_attributes() & 0x400 != 0 {
            return ContextPathKind::Symlink;
        }
    }
    let file_type = metadata.file_type();
    if file_type.is_symlink() {
        ContextPathKind::Symlink
    } else if file_type.is_file() {
        ContextPathKind::RegularFile
    } else if file_type.is_dir() {
        ContextPathKind::Directory
    } else {
        ContextPathKind::Other
    }
}

#[cfg(feature = "fs")]
pub(crate) fn context_regular_file_metadata(
    metadata: &std::fs::Metadata,
    identity: FileIdentity,
) -> io::Result<ContextPathMetadata> {
    if !metadata.is_file() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "context input is not a regular file",
        ));
    }
    Ok(ContextPathMetadata {
        kind: ContextPathKind::RegularFile,
        len: Some(metadata.len()),
        modified: Some(metadata.modified()?),
        identity: Some(identity),
    })
}

/// Observe the final path component without following a symbolic link.
///
/// This is a point-in-time classification only. It does not open the path,
/// establish a sandbox boundary, or make a later operation race-free.
#[cfg(feature = "fs")]
pub fn context_path_metadata_no_follow(path: &Path) -> io::Result<ContextPathMetadata> {
    let metadata = std::fs::symlink_metadata(path)?;
    let kind = context_path_kind(&metadata);
    Ok(ContextPathMetadata {
        kind,
        len: (kind == ContextPathKind::RegularFile).then_some(metadata.len()),
        modified: metadata.modified().ok(),
        identity: None,
    })
}

/// Return a symbolic link's raw target without resolving it.
///
/// The returned path is inert text. It may be relative, dangling, or outside
/// a caller's selected root; the caller owns any policy before following it.
#[cfg(feature = "fs")]
pub fn read_context_link(path: &Path) -> io::Result<PathBuf> {
    std::fs::read_link(path)
}

/// Resolve a path using the host's canonicalization rules.
///
/// This follows links and therefore is separate from
/// [`context_path_metadata_no_follow`] and bounded regular-file reading.
#[cfg(feature = "fs")]
pub fn canonical_context_path(path: &Path) -> io::Result<PathBuf> {
    std::fs::canonicalize(path)
}

/// Read an ordinary user-authorized regular file with a bounded allocation.
///
/// The final component is opened without following a link. Unix also opens
/// nonblocking so a FIFO can be rejected from handle metadata without waiting.
/// Ancestors are not protected from replacement or link traversal: callers
/// must trust them. At most `max_bytes + 1` bytes are allocated/read, and a
/// successful result includes a coherent final-handle observation.
#[cfg(feature = "fs")]
pub fn read_context_regular_file_bounded(
    path: &Path,
    max_bytes: usize,
) -> io::Result<ContextFileObservation> {
    if max_bytes > MAX_CONTEXT_REGULAR_FILE_BYTES {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "context regular-file limit {max_bytes} exceeds the {} byte facade cap",
                MAX_CONTEXT_REGULAR_FILE_BYTES
            ),
        ));
    }
    crate::fs_read_context_regular_file_bounded(path, max_bytes)
}

// ---------------------------------------------------------------------------
// Demand-driven directory cursor
// ---------------------------------------------------------------------------

/// One owned entry observed by a [`DirectoryCursor`].
///
/// `kind` is a point-in-time, non-following classification of the entry's
/// final component. It is not a handle observation and does not make a later
/// open race-free.
#[cfg(feature = "fs")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DirectoryCursorEntry {
    path: PathBuf,
    file_name: OsString,
    kind: ContextPathKind,
}

#[cfg(feature = "fs")]
impl DirectoryCursorEntry {
    /// The entry path formed from the cursor's supplied directory path and
    /// this entry's name. It is owned but is not canonicalized or guaranteed
    /// to be absolute.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// The entry's final component, owned independently of the native handle.
    pub fn file_name(&self) -> &OsStr {
        &self.file_name
    }

    /// The entry's observed final-component kind without following a link.
    pub fn kind(&self) -> ContextPathKind {
        self.kind
    }
}

/// A synchronous, demand-driven, nonrecursive directory enumeration.
///
/// The cursor owns one native directory-enumeration handle. Each
/// [`next_entry`](Self::next_entry) call asks the host for at most the next
/// entry; it neither descends into child directories nor collects, sorts, or
/// prefetches the rest of the directory. Native APIs can still buffer entries
/// internally, so this is not a claim that the operating system reads exactly
/// one directory record per call.
///
/// Dropping the cursor deterministically releases its native handle, which
/// lets a bounded consumer stop without enumerating the remainder. Calls are
/// synchronous native operations and may block. Opening a directory by path
/// follows the final link where the host does so. This cursor is not a hostile
/// path sandbox or an atomic directory snapshot: callers must trust and police
/// the root and its ancestors, and make separate observations before any
/// security-sensitive operation.
#[cfg(feature = "fs")]
pub struct DirectoryCursor {
    // Kept private so callers cannot retain a native entry/handle. `ReadDir`
    // is the kernel's native directory cursor on every supported host.
    native: std::fs::ReadDir,
}

#[cfg(feature = "fs")]
impl DirectoryCursor {
    /// Open `directory` for demand-driven, nonrecursive enumeration.
    ///
    /// Missing paths, non-directories, and inaccessible directories return the
    /// host error. The supplied spelling is retained in each entry path; it is
    /// not canonicalized.
    pub fn open(directory: impl AsRef<Path>) -> io::Result<Self> {
        Ok(Self {
            native: std::fs::read_dir(directory)?,
        })
    }

    /// Yield the next entry, or `None` after the directory is exhausted.
    ///
    /// An error from native enumeration or entry classification is returned to
    /// the caller; it is not hidden or converted into end-of-directory.
    pub fn next_entry(&mut self) -> io::Result<Option<DirectoryCursorEntry>> {
        let Some(entry) = self.native.next() else {
            return Ok(None);
        };
        let entry = entry?;
        // Copy every facade value before `DirEntry` is dropped. On Unix a
        // retained `DirEntry` can retain the directory descriptor.
        let path = entry.path();
        let file_name = entry.file_name();
        let kind = context_path_kind(&std::fs::symlink_metadata(&path)?);
        Ok(Some(DirectoryCursorEntry {
            path,
            file_name,
            kind,
        }))
    }
}

/// Read a current-user-private regular file, rejecting links and oversized
/// input.
///
/// The final path component is opened without following a link, and all file
/// security checks are made from that same open handle before its contents are
/// read. The immediate parent must also be a current-user-private directory.
/// The path is re-identified after reading where the host can do so, so a
/// replacement of that final component during the operation is rejected rather
/// than silently read. This is not a filesystem sandbox: callers must supply a
/// trusted parent and ancestor path, and must prevent races that could replace
/// or redirect those path components while this operation runs.
///
/// `max_bytes` is both the returned-data limit and the allocation/read bound:
/// at most `max_bytes + 1` bytes are read in order to distinguish an exact
/// limit from an oversized file. Limits above
/// [`MAX_PRIVATE_REGULAR_FILE_BYTES`] are rejected.
///
/// On Unix, private means owned by the effective uid with no group or other
/// permission bits. On Windows, the trusted parent must have the protected
/// owner-and-SYSTEM DACL, and the opened file must be owned by the current user
/// with exactly the private owner-rights-and-SYSTEM full-control DACL, either
/// direct or inherited. The final component's reparse point is rejected; no
/// claim is made about reparse points in ancestors.
/// Callers that create staging files must still create them under an
/// owner-private directory (for example the runtime-directory helper's
/// result); this operation does not repair insecure paths.
#[cfg(feature = "fs")]
pub fn read_private_regular_file_bounded(path: &Path, max_bytes: usize) -> io::Result<Vec<u8>> {
    if max_bytes > MAX_PRIVATE_REGULAR_FILE_BYTES {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "private regular-file limit {max_bytes} exceeds the {} byte facade cap",
                MAX_PRIVATE_REGULAR_FILE_BYTES
            ),
        ));
    }
    crate::fs_read_private_regular_file_bounded(path, max_bytes)
}

#[cfg(feature = "fs")]
use std::ffi::{OsStr, OsString};
#[cfg(feature = "fs")]
use std::fs::File;
#[cfg(feature = "fs")]
use std::io;
#[cfg(feature = "fs")]
use std::path::{Path, PathBuf};
#[cfg(feature = "fs")]
use std::sync::Arc;
#[cfg(feature = "fs")]
use std::time::SystemTime;

// ---------------------------------------------------------------------------
// Advisory locking
// ---------------------------------------------------------------------------

/// An advisory lock held on an open file, released automatically when this
/// guard drops.
///
/// Holding this guard *is* what "the lock is held" means in this module:
/// there is deliberately no bare `lock`/`unlock` pair here that a caller
/// could call out of balance and get wrong. Release is best-effort -- a
/// failure releasing an
/// advisory lock cannot be reported from a destructor, and on every supported
/// host closing the underlying file descriptor also releases the lock, so a
/// failed explicit unlock here is not a stuck lock, just a redundant release
/// that did not need to happen.
///
/// Advisory locks exclude other advisory-lock holders only, never a process
/// that opens and reads or writes the file without locking it -- that is true
/// on every supported host and is what "advisory" means throughout this
/// module. Unix gets it from `flock`, which is advisory by construction;
/// Windows byte-range locks are mandatory, so the Windows implementation
/// takes its lock on a single byte far past any file's data, leaving the body
/// unobstructed. The exclusion between holders is identical either way; only
/// the bytes the kernel guards differ, and no caller reads or writes those.
///
/// # One guard per open file
///
/// A guard borrows the file shared, so nothing stops a caller from holding
/// two guards on the *same* [`File`] -- and every host answers that
/// differently, so it is a programming error rather than a portable
/// operation:
///
/// - Unix `flock` converts the lock in place, so a shared guard followed by
///   an exclusive one is an upgrade, and *either* guard's drop releases the
///   file's lock outright, including the one the other guard still thinks it
///   holds.
/// - Windows refuses an exclusive request that overlaps a range the same
///   handle already locked: [`try_lock_exclusive`] reports a conflict (see
///   [`is_lock_conflict`]) and [`lock_exclusive`] waits forever, because the
///   only holder that could release it is the caller that is waiting.
///
/// Hold one guard per open file. A second lock on the same path needs a
/// second [`open_lock_file`] handle, which is also what makes the exclusion
/// between the two meaningful.
#[cfg(feature = "fs")]
#[derive(Debug)]
pub struct FileLock<'file> {
    file: &'file File,
}

#[cfg(feature = "fs")]
impl<'file> FileLock<'file> {
    fn new(file: &'file File) -> Self {
        Self { file }
    }
}

#[cfg(feature = "fs")]
impl Drop for FileLock<'_> {
    fn drop(&mut self) {
        let _ = crate::fs_unlock(self.file);
    }
}

/// Take an exclusive advisory lock, waiting until it is available.
///
/// The returned guard releases the lock when dropped.
///
/// # Errors
///
/// Returns an error if the host lock call fails for a reason other than
/// waiting for the lock.
#[cfg(feature = "fs")]
pub fn lock_exclusive(file: &File) -> io::Result<FileLock<'_>> {
    crate::fs_lock_exclusive(file)?;
    Ok(FileLock::new(file))
}

/// Take a shared advisory lock, waiting until it is available.
///
/// The returned guard releases the lock when dropped.
///
/// # Errors
///
/// Returns an error if the host lock call fails for a reason other than
/// waiting for the lock.
#[cfg(feature = "fs")]
pub fn lock_shared(file: &File) -> io::Result<FileLock<'_>> {
    crate::fs_lock_shared(file)?;
    Ok(FileLock::new(file))
}

/// Take an exclusive advisory lock without waiting.
///
/// Returns immediately when another holder has it; the caller decides
/// whether that is a conflict worth retrying, via [`is_lock_conflict`].
///
/// # Errors
///
/// Returns an error if another holder has the lock (see
/// [`is_lock_conflict`]), or if the host lock call fails for another reason.
#[cfg(feature = "fs")]
pub fn try_lock_exclusive(file: &File) -> io::Result<FileLock<'_>> {
    crate::fs_try_lock_exclusive(file)?;
    Ok(FileLock::new(file))
}

/// Take a shared advisory lock without waiting.
///
/// Returns immediately when an exclusive holder has it; the caller decides
/// whether that is a conflict worth retrying, via [`is_lock_conflict`].
///
/// # Errors
///
/// Returns an error if an exclusive holder has the lock (see
/// [`is_lock_conflict`]), or if the host lock call fails for another reason.
#[cfg(feature = "fs")]
pub fn try_lock_shared(file: &File) -> io::Result<FileLock<'_>> {
    crate::fs_try_lock_shared(file)?;
    Ok(FileLock::new(file))
}

/// A held advisory lock that owns its file handle.
///
/// [`FileLock`] borrows, which is right when the lock and the handle live in
/// one scope. It cannot express a lock that outlives the function taking it:
/// a struct cannot hold a `File` and a guard borrowing that same `File`, and
/// a function cannot return one without returning the other. Both are
/// ordinary -- a lock file held for the lifetime of a working directory, a
/// fetch lock returned to a caller -- so this owns the handle instead.
///
/// Dropping releases the lock and closes the handle, in that order.
#[cfg(feature = "fs")]
#[derive(Debug)]
pub struct OwnedFileLock {
    file: Option<File>,
}

#[cfg(feature = "fs")]
impl OwnedFileLock {
    /// Borrow the locked handle, to read or write the file the lock guards.
    pub fn file(&self) -> &File {
        self.file
            .as_ref()
            .expect("the handle is taken only by unlock, which consumes self")
    }

    /// Release the lock and hand the handle back, still open.
    ///
    /// Use this to unlock at a point of your choosing rather than at the end
    /// of the scope, or to keep reading the file afterwards.
    ///
    /// # Errors
    ///
    /// Returns the handle alongside the error if the host refused to unlock,
    /// since a caller that cannot unlock generally still needs to close.
    pub fn unlock(mut self) -> Result<File, (File, io::Error)> {
        let file = self
            .file
            .take()
            .expect("the handle is taken only here, and this consumes self");
        match crate::fs_unlock(&file) {
            Ok(()) => Ok(file),
            Err(error) => Err((file, error)),
        }
    }
}

#[cfg(feature = "fs")]
impl Drop for OwnedFileLock {
    fn drop(&mut self) {
        if let Some(file) = self.file.as_ref() {
            let _ = crate::fs_unlock(file);
        }
    }
}

/// Take an exclusive advisory lock that owns `file`, waiting for it.
///
/// # Errors
///
/// Returns an error if the host lock call fails. `file` is closed in that
/// case; a caller that needs the handle back on failure should use
/// [`lock_exclusive`] and keep its own handle.
#[cfg(feature = "fs")]
pub fn lock_exclusive_owned(file: File) -> io::Result<OwnedFileLock> {
    crate::fs_lock_exclusive(&file)?;
    Ok(OwnedFileLock { file: Some(file) })
}

/// Take a shared advisory lock that owns `file`, waiting for it.
///
/// # Errors
///
/// As [`lock_exclusive_owned`].
#[cfg(feature = "fs")]
pub fn lock_shared_owned(file: File) -> io::Result<OwnedFileLock> {
    crate::fs_lock_shared(&file)?;
    Ok(OwnedFileLock { file: Some(file) })
}

/// Take an exclusive advisory lock that owns `file`, without waiting.
///
/// # Errors
///
/// Returns an error if another holder has the lock (see
/// [`is_lock_conflict`]), or if the host lock call fails. `file` is closed in
/// either case.
#[cfg(feature = "fs")]
pub fn try_lock_exclusive_owned(file: File) -> io::Result<OwnedFileLock> {
    crate::fs_try_lock_exclusive(&file)?;
    Ok(OwnedFileLock { file: Some(file) })
}

/// Take a shared advisory lock that owns `file`, without waiting.
///
/// # Errors
///
/// As [`try_lock_exclusive_owned`].
#[cfg(feature = "fs")]
pub fn try_lock_shared_owned(file: File) -> io::Result<OwnedFileLock> {
    crate::fs_try_lock_shared(&file)?;
    Ok(OwnedFileLock { file: Some(file) })
}

// ---------------------------------------------------------------------------
// Modification time
// ---------------------------------------------------------------------------

/// A filesystem modification time, independent of any host's on-disk
/// representation.
///
/// This is a Unix-epoch second and a nanosecond remainder, not
/// [`SystemTime`]: an on-disk mtime is fundamentally that pair (a filesystem
/// can legitimately record a time before 1970 as a negative second count),
/// and going through `SystemTime`'s own epoch arithmetic for every
/// construction and every host's native call would risk losing precision or
/// failing on values a filesystem can actually hold. A value only ever moves
/// between [`Metadata`](std::fs::Metadata) (via
/// [`from_last_modification_time`](FileTime::from_last_modification_time))
/// and a file (via [`set_file_mtime`]). A client that persists mtimes rather
/// than only copying them between a file and its metadata reads the value
/// back through [`unix_seconds`](FileTime::unix_seconds) and
/// [`nanoseconds`](FileTime::nanoseconds), which are the same two fields the
/// constructors take.
#[cfg(feature = "fs")]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FileTime {
    seconds_since_unix_epoch: i64,
    nanoseconds: u32,
}

#[cfg(feature = "fs")]
impl FileTime {
    /// Construct a modification time from a Unix-epoch second count and a
    /// nanosecond remainder.
    ///
    /// `seconds_since_unix_epoch` may be negative, for a time before 1970,
    /// matching what an on-disk mtime can legitimately encode.
    pub fn from_unix_time(seconds_since_unix_epoch: i64, nanoseconds: u32) -> Self {
        Self {
            seconds_since_unix_epoch,
            nanoseconds,
        }
    }

    /// The whole seconds since the Unix epoch, negative before 1970.
    ///
    /// With [`nanoseconds`](FileTime::nanoseconds) this is the exact pair
    /// [`from_unix_time`](FileTime::from_unix_time) accepts, so a persisted
    /// mtime round-trips without going through `SystemTime` -- which is the
    /// point, since `SystemTime` cannot represent every value a filesystem
    /// can hold.
    pub const fn unix_seconds(self) -> i64 {
        self.seconds_since_unix_epoch
    }

    /// The sub-second remainder, in nanoseconds.
    ///
    /// This is a remainder, not a total: it is always in `0..1_000_000_000`
    /// and is *not* signed for times before 1970. A pre-epoch mtime has a
    /// negative [`unix_seconds`](FileTime::unix_seconds) and a positive
    /// nanosecond remainder counting forward from it, which is how both the
    /// host field and `from_unix_time` encode it.
    pub const fn nanoseconds(self) -> u32 {
        self.nanoseconds
    }

    /// Construct a modification time from [`SystemTime`], such as
    /// [`Metadata::modified`](std::fs::Metadata::modified).
    pub fn from_system_time(time: SystemTime) -> Self {
        match time.duration_since(SystemTime::UNIX_EPOCH) {
            Ok(duration) => Self {
                seconds_since_unix_epoch: duration.as_secs() as i64,
                nanoseconds: duration.subsec_nanos(),
            },
            Err(before_epoch) => {
                let duration = before_epoch.duration();
                let subsec = duration.subsec_nanos();
                let (seconds, nanoseconds) = if subsec == 0 {
                    (-(duration.as_secs() as i64), 0)
                } else {
                    (-(duration.as_secs() as i64) - 1, 1_000_000_000 - subsec)
                };
                Self {
                    seconds_since_unix_epoch: seconds,
                    nanoseconds,
                }
            }
        }
    }

    /// The current modification time, as this host's clock reports it now.
    pub fn now() -> Self {
        Self::from_system_time(SystemTime::now())
    }

    /// The modification time already recorded in `metadata`, such as from
    /// [`std::fs::metadata`] or [`std::fs::symlink_metadata`].
    ///
    /// Infallible: unlike [`Metadata::modified`](std::fs::Metadata::modified),
    /// this reads the raw host field directly rather than going through a
    /// conversion that can report the host as not supporting mtimes at all,
    /// which none of Linux, macOS, or Windows fail to.
    pub fn from_last_modification_time(metadata: &std::fs::Metadata) -> Self {
        last_modification_time(metadata)
    }
}

#[cfg(all(feature = "fs", unix))]
fn last_modification_time(metadata: &std::fs::Metadata) -> FileTime {
    use std::os::unix::fs::MetadataExt as _;

    FileTime {
        seconds_since_unix_epoch: metadata.mtime(),
        nanoseconds: metadata.mtime_nsec().clamp(0, 999_999_999) as u32,
    }
}

#[cfg(all(feature = "fs", windows))]
fn last_modification_time(metadata: &std::fs::Metadata) -> FileTime {
    use std::os::windows::fs::MetadataExt as _;

    windows_file_time_to_unix(metadata.last_write_time())
}

/// Windows-epoch (1601-01-01) 100-nanosecond ticks, converted to a Unix-epoch
/// second/nanosecond pair. Shared by [`last_modification_time`]; kept here
/// rather than duplicated per host because the conversion itself does not
/// diverge -- only which raw field a host hands it does.
#[cfg(all(feature = "fs", windows))]
fn windows_file_time_to_unix(ticks: u64) -> FileTime {
    /// 100-nanosecond ticks between the Windows epoch (1601-01-01) and the
    /// Unix epoch (1970-01-01).
    const WINDOWS_TO_UNIX_EPOCH_TICKS: i64 = 116_444_736_000_000_000;

    let ticks = ticks as i64 - WINDOWS_TO_UNIX_EPOCH_TICKS;
    let seconds_since_unix_epoch = ticks.div_euclid(10_000_000);
    let remainder_ticks = ticks.rem_euclid(10_000_000);
    FileTime {
        seconds_since_unix_epoch,
        nanoseconds: (remainder_ticks * 100) as u32,
    }
}

/// Set the modification time of the file at `path`, without disturbing its
/// access time.
///
/// `path` may name a directory as well as a regular file. Directories carry
/// an mtime on every host this crate supports, and a client restoring a
/// stored tree has to put it back.
///
/// # Errors
///
/// Returns an error if the caller lacks permission to change the file's
/// timestamps, if `path` does not exist, or if `time` is out of range for
/// this host's clock.
#[cfg(feature = "fs")]
pub fn set_file_mtime(path: &Path, time: FileTime) -> io::Result<()> {
    crate::fs_set_file_mtime(path, time.seconds_since_unix_epoch, time.nanoseconds)
}

// ---------------------------------------------------------------------------
// Copy
// ---------------------------------------------------------------------------

/// How [`copy_file`] moved the bytes.
#[cfg(feature = "fs")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CopyOutcome {
    /// The destination shares the source's data blocks (copy-on-write); no
    /// file content was duplicated on disk.
    Reflinked,
    /// The filesystem, or this particular pair of paths, does not support a
    /// reflink here, so this many bytes were duplicated instead.
    Copied {
        /// The number of bytes written to `destination`.
        bytes: u64,
    },
}

/// Copy `source` to `destination`, preferring a reflink over a byte-for-byte
/// copy.
///
/// A reflink shares data blocks copy-on-write instead of duplicating them, so
/// it is near-instant and free of disk space until either copy is modified --
/// but only some filesystems support it (btrfs, XFS with `reflink=1`, APFS,
/// ReFS on Windows Server, and a few others), and both paths generally need
/// to be on the same volume. Where a reflink is not possible this transparently
/// falls back to a full byte copy, and [`CopyOutcome`] tells the caller which
/// one actually happened -- a caller that specifically needs the cheap path
/// can detect the expensive one rather than assume.
///
/// # Errors
///
/// Returns an error if neither a reflink nor a byte copy could complete, such
/// as `source` not existing or a permissions failure on `destination`.
#[cfg(feature = "fs")]
pub fn copy_file(source: &Path, destination: &Path) -> io::Result<CopyOutcome> {
    match reflink_copy::reflink_or_copy(source, destination)? {
        None => Ok(CopyOutcome::Reflinked),
        Some(bytes) => Ok(CopyOutcome::Copied { bytes }),
    }
}

/// Reflink `source` to `destination`, failing rather than falling back.
///
/// [`copy_file`] is the right call when the goal is that the bytes arrive.
/// This is for the two cases where a silent byte copy is the wrong answer:
///
/// - **Probing a filesystem.** "Does this volume support reflinks?" is
///   answered by attempting one and seeing whether it works. Asked through
///   [`copy_file`], every volume answers yes, because the fallback always
///   succeeds -- so a caller that stores the result as a capability would
///   record a capability the filesystem does not have.
/// - **Taking the cheap path or none.** A caller that reflinks to avoid
///   duplicating a large artifact, and does something else entirely when it
///   cannot, must not have a full copy performed on its behalf first. With
///   [`copy_file`] it would pay for the copy and then, on discovering
///   [`CopyOutcome::Copied`], have to undo it.
///
/// `destination` must not already exist.
///
/// # Errors
///
/// Returns an error when the filesystem does not support reflinking this
/// pair of paths -- typically because they are on different volumes or the
/// filesystem has no copy-on-write support -- and for the ordinary reasons a
/// copy fails, such as `source` not existing. The two are deliberately not
/// distinguished: a caller that cannot reflink here does the same thing
/// whichever it is.
#[cfg(feature = "fs")]
pub fn reflink_file(source: &Path, destination: &Path) -> io::Result<()> {
    reflink_copy::reflink(source, destination)
}

// ---------------------------------------------------------------------------
// Parallel directory walk
// ---------------------------------------------------------------------------

/// One entry yielded by a [`DirectoryWalk`].
#[cfg(feature = "fs")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DirectoryEntry {
    path: PathBuf,
    depth: usize,
    is_directory: bool,
    is_file: bool,
    is_symbolic_link: bool,
}

#[cfg(feature = "fs")]
impl DirectoryEntry {
    /// The absolute path of this entry.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Depth of this entry relative to the walk's root, which is depth `0`.
    pub fn depth(&self) -> usize {
        self.depth
    }

    /// Whether this entry is a directory.
    pub fn is_directory(&self) -> bool {
        self.is_directory
    }

    /// Whether this entry is a regular file.
    pub fn is_file(&self) -> bool {
        self.is_file
    }

    /// Whether this entry is a symbolic link that was not followed.
    ///
    /// Never true when the walk that produced it followed symbolic links --
    /// in that case this entry describes the link's target instead.
    pub fn is_symbolic_link(&self) -> bool {
        self.is_symbolic_link
    }

    /// Re-read this entry's metadata from disk.
    ///
    /// # Errors
    ///
    /// Returns an error if the entry no longer exists or cannot be read.
    pub fn metadata(&self) -> io::Result<std::fs::Metadata> {
        std::fs::metadata(&self.path)
    }
}

#[cfg(feature = "fs")]
fn directory_entry_from_jwalk(entry: jwalk::DirEntry<((), ())>) -> DirectoryEntry {
    let file_type = entry.file_type();
    DirectoryEntry {
        path: entry.path(),
        depth: entry.depth(),
        is_directory: file_type.is_dir(),
        is_file: file_type.is_file(),
        is_symbolic_link: file_type.is_symlink(),
    }
}

/// The predicate a [`DirectoryWalk`] consults before descending into a
/// directory. Shared, because the walk hands it to every worker thread that
/// reads a directory, and named, because spelling it inline twice is the
/// kind of type that stops being readable.
#[cfg(feature = "fs")]
type PruneDirectories = Arc<dyn Fn(&Path) -> bool + Send + Sync>;

/// A parallel directory-tree walk, configured before it runs.
///
/// Every option here defaults to what [`std::fs::read_dir`] itself would do
/// for a single directory: hidden entries included, symbolic links not
/// followed, no ordering guarantee, and nothing pruned.
#[cfg(feature = "fs")]
pub struct DirectoryWalk {
    root: PathBuf,
    follow_symbolic_links: bool,
    include_hidden_entries: bool,
    sorted: bool,
    prune_directories: Option<PruneDirectories>,
}

#[cfg(feature = "fs")]
impl DirectoryWalk {
    /// Start configuring a walk rooted at `root`.
    pub fn new(root: PathBuf) -> Self {
        Self {
            root,
            follow_symbolic_links: false,
            include_hidden_entries: true,
            sorted: false,
            prune_directories: None,
        }
    }

    /// Whether to follow symbolic links into their targets. Default: `false`.
    pub fn follow_symbolic_links(mut self, follow: bool) -> Self {
        self.follow_symbolic_links = follow;
        self
    }

    /// Whether to include entries this host considers hidden. Default:
    /// `true`.
    pub fn include_hidden_entries(mut self, include: bool) -> Self {
        self.include_hidden_entries = include;
        self
    }

    /// Whether entries are yielded in a deterministic, sorted order.
    /// Default: `false`, which is faster.
    pub fn sorted(mut self, sorted: bool) -> Self {
        self.sorted = sorted;
        self
    }

    /// Skip descending into (and yielding) any directory for which `keep`
    /// returns `false`.
    ///
    /// This is evaluated once per directory, before it is read, so a rejected
    /// directory's contents are never touched -- the reason to use this
    /// instead of filtering [`DirectoryWalk::walk`]'s output is exactly that
    /// short-circuit, on a tree where the pruned subtrees (`.git`, `target`,
    /// `node_modules`) can dwarf the rest.
    pub fn prune_directories<F>(mut self, keep: F) -> Self
    where
        F: Fn(&Path) -> bool + Send + Sync + 'static,
    {
        let keep: PruneDirectories = Arc::new(keep);
        self.prune_directories = Some(keep);
        self
    }

    /// Run the walk, yielding entries as they are discovered.
    ///
    /// Each item is an error only for an individual entry this walk could not
    /// read (a permissions failure, a race with something deleting the
    /// tree); it does not end the walk.
    pub fn walk(self) -> impl Iterator<Item = io::Result<DirectoryEntry>> {
        let prune_directories = self.prune_directories;
        let walker = jwalk::WalkDir::new(&self.root)
            .follow_links(self.follow_symbolic_links)
            .skip_hidden(!self.include_hidden_entries)
            .sort(self.sorted)
            .process_read_dir(move |_depth, _parent, _state, children| {
                let Some(keep) = &prune_directories else {
                    return;
                };
                children.retain(|entry| match entry {
                    Ok(entry) if entry.file_type().is_dir() => keep(&entry.path()),
                    _ => true,
                });
            });
        walker.into_iter().map(|entry| {
            entry
                .map(directory_entry_from_jwalk)
                .map_err(io::Error::from)
        })
    }
}

// ---------------------------------------------------------------------------
// Glob matching
// ---------------------------------------------------------------------------

/// A compiled set of glob patterns, matched together against one candidate
/// path per call.
///
/// Build one with [`PatternSetBuilder`].
#[cfg(feature = "fs")]
#[derive(Clone, Debug)]
pub struct PatternSet(globset::GlobSet);

#[cfg(feature = "fs")]
impl PatternSet {
    /// Whether `path` matches any pattern in this set.
    ///
    /// Accepts anything path-like because callers match against whatever
    /// they already hold -- a `String` of a relative path built for display,
    /// an `OsStr` from a directory entry -- and requiring `&Path` only makes
    /// them write the conversion at every call site.
    pub fn is_match(&self, path: impl AsRef<Path>) -> bool {
        self.0.is_match(path.as_ref())
    }

    /// Whether this set contains no patterns.
    ///
    /// An empty set matches nothing, so a caller filtering with "exclude
    /// unless excluded" logic uses this to skip the walk's matching work
    /// entirely rather than calling [`is_match`](PatternSet::is_match) per
    /// candidate to be told no every time.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// How many patterns this set contains.
    pub fn len(&self) -> usize {
        self.0.len()
    }
}

/// Builds a [`PatternSet`] from glob patterns.
///
/// Patterns are validated together at [`PatternSetBuilder::build`] rather
/// than one at a time as they are added, so a caller assembling a set from a
/// product's own configuration gets one place to report a bad pattern.
#[cfg(feature = "fs")]
#[derive(Debug, Default)]
pub struct PatternSetBuilder {
    patterns: Vec<String>,
}

#[cfg(feature = "fs")]
impl PatternSetBuilder {
    /// Start with no patterns.
    pub fn new() -> Self {
        Self {
            patterns: Vec::new(),
        }
    }

    /// Add one glob pattern to the set.
    pub fn add_pattern(mut self, pattern: &str) -> Self {
        self.patterns.push(pattern.to_owned());
        self
    }

    /// Compile the added patterns into a [`PatternSet`].
    ///
    /// # Errors
    ///
    /// Returns an error if any added pattern is not valid glob syntax.
    pub fn build(self) -> io::Result<PatternSet> {
        let mut builder = globset::GlobSetBuilder::new();
        for pattern in &self.patterns {
            let glob = globset::Glob::new(pattern)
                .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
            builder.add(glob);
        }
        let set = builder
            .build()
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
        Ok(PatternSet(set))
    }
}

#[cfg(all(test, feature = "fs"))]
mod tests {
    use super::*;

    const PRODUCT: &str = "rp-fs-facade-test";

    /// A directory this facade created is not writable by other users.
    ///
    /// Asserted through `ensure_dir_private`'s own report rather than against
    /// mode bits or a DACL: the property is "already private", and each host
    /// decides what that means. A caller that has just created the directory
    /// must never be told it had to be repaired.
    #[test]
    fn a_freshly_created_private_directory_needs_no_tightening() {
        let root = tempfile::tempdir().expect("temp root");
        let nested = root.path().join("outer").join("inner");

        create_dir_all_private(&nested).expect("create private directory");

        assert!(nested.is_dir(), "the directory and its parents exist");
        assert!(
            !ensure_dir_private(&nested).expect("inspect a fresh private directory"),
            "a directory this facade just created is already private"
        );
    }

    /// Creating an existing private directory again is not an error.
    ///
    /// The operation composes like `create_dir_all`, so callers that always
    /// create before use do not have to distinguish the first run from later
    /// ones.
    #[test]
    fn creating_a_private_directory_twice_succeeds() {
        let root = tempfile::tempdir().expect("temp root");
        let path = root.path().join("twice");

        create_dir_all_private(&path).expect("first create");
        create_dir_all_private(&path).expect("second create");

        assert!(path.is_dir());
    }

    /// Tightening reports a missing directory rather than inventing one.
    #[test]
    fn ensuring_a_missing_directory_is_private_reports_not_found() {
        let root = tempfile::tempdir().expect("temp root");

        let error = ensure_dir_private(&root.path().join("absent")).expect_err("missing directory");

        assert_eq!(error.kind(), io::ErrorKind::NotFound);
    }

    /// Appending keeps what an earlier handle wrote, and the bytes land in order.
    ///
    /// The shared-append contract is about not truncating and not excluding a
    /// second opener; both handles here are live at once, which is the part
    /// Windows would refuse under its default share mode.
    #[test]
    fn shared_append_preserves_earlier_bytes_and_admits_a_second_writer() {
        use std::io::Write as _;

        let root = tempfile::tempdir().expect("temp root");
        let path = root.path().join("log");

        let mut first = open_shared_append(&path).expect("first append handle");
        first.write_all(b"one\n").expect("first write");
        let mut second = open_shared_append(&path).expect("second append handle");
        second.write_all(b"two\n").expect("second write");
        drop((first, second));

        assert_eq!(
            std::fs::read_to_string(&path).expect("read back"),
            "one\ntwo\n"
        );
    }

    /// Every role resolves to an absolute directory that names the product.
    ///
    /// Asserted as a property rather than against one host's spelling: the
    /// point of the facade is that callers cannot tell which host answered.
    #[test]
    fn every_role_is_an_absolute_product_scoped_directory() {
        for directory in [
            user_runtime_dir(PRODUCT),
            user_state_dir(PRODUCT),
            user_run_data_root(PRODUCT),
        ] {
            assert!(
                directory.is_absolute(),
                "{} must be absolute",
                directory.display()
            );
            assert!(
                directory.to_string_lossy().contains(PRODUCT),
                "{} must be scoped to the product",
                directory.display()
            );
        }
    }

    /// Two products never share a directory in any role.
    #[test]
    fn distinct_products_do_not_collide() {
        let other = "rp-fs-facade-other";
        assert_ne!(user_runtime_dir(PRODUCT), user_runtime_dir(other));
        assert_ne!(user_state_dir(PRODUCT), user_state_dir(other));
        assert_ne!(user_run_data_root(PRODUCT), user_run_data_root(other));
    }

    /// A file is the same file as itself, by whichever pair this host uses.
    #[test]
    fn a_file_has_one_identity_through_both_a_handle_and_its_path() {
        let dir = std::env::temp_dir().join(format!("rp-fs-identity-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let path = dir.join("subject");
        let file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(&path)
            .expect("create subject");

        let by_handle = file_identity(&file).expect("identity by handle");
        let by_path = path_identity(&path).expect("identity by path");
        assert_eq!(by_handle, by_path);

        drop(file);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Two distinct files never share an identity, which is the property a
    /// caller relies on to notice its file was replaced underneath it.
    #[test]
    fn distinct_files_have_distinct_identities() {
        let dir = std::env::temp_dir().join(format!("rp-fs-identity2-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let (first, second) = (dir.join("first"), dir.join("second"));
        std::fs::write(&first, b"a").expect("write first");
        std::fs::write(&second, b"b").expect("write second");

        let a = path_identity(&first).expect("identity a");
        let b = path_identity(&second).expect("identity b");
        if a.is_some() {
            assert_ne!(a, b);
        }

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// An exclusive lock excludes a second holder, and releasing readmits one.
    ///
    /// Both handles are opened through the facade, so this exercises the open
    /// and the lock together -- on Windows the two interact, because a
    /// restrictive share mode would fail the second open before it could ask
    /// for the lock.
    #[test]
    fn an_exclusive_lock_excludes_a_second_holder_until_released() {
        let dir = std::env::temp_dir().join(format!("rp-fs-lock-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let path = dir.join("guard.lock");

        let first = open_lock_file(&path).expect("open first");
        let second = open_lock_file(&path).expect("open second");

        let first_lock = try_lock_exclusive(&first).expect("first acquires");
        let conflict = try_lock_exclusive(&second).expect_err("second must be refused");
        assert!(
            is_lock_conflict(&conflict),
            "refusal must classify as a conflict, got {conflict:?}"
        );

        // Dropping the guard is the only release mechanism this facade
        // exposes; the second holder succeeding proves the drop actually
        // released the lock, not just that the borrow ended.
        drop(first_lock);
        let second_lock = try_lock_exclusive(&second).expect("second acquires after release");
        drop(second_lock);

        drop((first, second));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A held lock obstructs no one who did not ask for a lock.
    ///
    /// This is the facade's advisory promise stated as a test, and it is the
    /// pidfile pattern [`open_lock_file`] exists for: a holder writes who it
    /// is, and anyone else reads that without participating in the locking.
    /// Deliberately not host-gated -- the claim is that every host answers
    /// the same way, so every host has to run it.
    #[test]
    fn a_lock_does_not_obstruct_a_process_that_never_locked() {
        use std::io::{Read as _, Write as _};

        let dir = std::env::temp_dir().join(format!("rp-fs-advisory-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let path = dir.join("holder.lock");
        std::fs::write(&path, b"00000").expect("seed contents");

        let held = open_lock_file(&path).expect("open holder");

        // An exclusive holder must not stop a plain reader.
        let exclusive = lock_exclusive(&held).expect("holder takes it exclusively");
        let mut contents = Vec::new();
        std::fs::File::open(&path)
            .expect("a non-participant can open it")
            .read_to_end(&mut contents)
            .expect("a non-participant can read it");
        assert_eq!(contents, b"00000");
        drop(exclusive);

        // A shared holder must not stop a plain writer either. The write
        // does not truncate: a lock file's contents belong to whoever wrote
        // them, and replacing five bytes with five keeps this about the lock
        // rather than about file length.
        let shared = lock_shared(&held).expect("holder takes it shared");
        std::fs::OpenOptions::new()
            .write(true)
            .truncate(false)
            .open(&path)
            .expect("a non-participant can open it for writing")
            .write_all(b"11111")
            .expect("a non-participant can write it");
        drop(shared);

        assert_eq!(std::fs::read(&path).expect("read back"), b"11111");

        drop(held);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Asking one handle to upgrade its own lock is refused, not granted.
    ///
    /// Windows-only because it is the host whose answer differs: `flock`
    /// converts in place, while `LockFileEx` will not take an exclusive lock
    /// overlapping a range the same handle already holds. Written against
    /// the *try* form on purpose -- [`lock_exclusive`] would wait for a
    /// release only this caller could perform, which is a hung CI lane
    /// rather than a failing test.
    #[cfg(windows)]
    #[test]
    fn one_handle_cannot_upgrade_its_own_shared_lock() {
        let dir = std::env::temp_dir().join(format!("rp-fs-upgrade-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let path = dir.join("upgrade.lock");

        let file = open_lock_file(&path).expect("open");
        let shared = lock_shared(&file).expect("take it shared");
        let conflict = try_lock_exclusive(&file).expect_err("an upgrade must be refused");
        assert!(
            is_lock_conflict(&conflict),
            "refusal must classify as a conflict, got {conflict:?}"
        );
        drop(shared);

        drop(file);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A genuine failure is not reported as a conflict, so a caller does not
    /// retry forever on something waiting cannot fix.
    #[test]
    fn an_unrelated_error_is_not_a_lock_conflict() {
        let missing = std::env::temp_dir().join("rp-fs-lock-no-such-file");
        let _ = std::fs::remove_file(&missing);
        let error = std::fs::File::open(&missing).expect_err("must not exist");
        assert!(!is_lock_conflict(&error));
    }

    /// The pair round-trips, which is the only contract a wire encoding owes
    /// its decoder: the far end must reconstruct exactly the path that was
    /// named, not an equivalent one.
    #[test]
    fn a_path_survives_encoding_and_decoding_unchanged() {
        for original in [
            std::path::PathBuf::from("relative/leaf.log"),
            std::env::temp_dir()
                .join("rp path with spaces")
                .join("t.log"),
            std::env::current_exe().expect("current image"),
        ] {
            let decoded =
                decode_path_bytes(&encode_path_bytes(&original)).expect("decode what we encoded");
            assert_eq!(decoded, original);
        }
    }

    /// An empty path is a path, and must not become an error or a surprise.
    #[test]
    fn an_empty_path_round_trips_as_empty() {
        let empty = std::path::PathBuf::new();
        assert!(encode_path_bytes(&empty).is_empty());
        assert_eq!(
            decode_path_bytes(&encode_path_bytes(&empty)).expect("decode empty"),
            empty
        );
    }

    /// Replacing works whether or not the target already exists.
    ///
    /// Both cases matter, and they must be the same case: the no-target one
    /// is what a first write takes, and a host that reached it by a different
    /// call would owe that call's durability separately.
    #[test]
    fn a_file_is_replaced_whether_or_not_the_target_exists() {
        let dir = std::env::temp_dir().join(format!("rp-fs-replace-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let target = dir.join("manifest");

        let first = dir.join("first.tmp");
        std::fs::write(&first, b"first").expect("write first");
        replace_file(&first, &target).expect("replace absent target");
        assert_eq!(std::fs::read(&target).expect("read"), b"first");

        let second = dir.join("second.tmp");
        std::fs::write(&second, b"second").expect("write second");
        replace_file(&second, &target).expect("replace existing target");
        assert_eq!(std::fs::read(&target).expect("read"), b"second");

        // The replaced-from paths are consumed by the move, not left behind.
        assert!(!first.exists());
        assert!(!second.exists());

        sync_directory(&dir).expect("sync the directory that records it");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A first write and an overwrite are the same move, not two mechanisms.
    ///
    /// Windows-only because it is the host that had two: a create branch that
    /// took a plain rename and got no write-through, and a replace branch
    /// that did. The durability itself cannot be asserted from a test -- it
    /// only shows up across an unclean shutdown -- so this pins the property
    /// that stands in for it: both paths move the temporary file's own record
    /// into place, which a copy-and-replace would not do, so whatever the one
    /// path guarantees the other guarantees too.
    #[cfg(windows)]
    #[test]
    fn a_first_write_and_an_overwrite_move_the_same_way() {
        let dir = std::env::temp_dir().join(format!("rp-fs-replace-win-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let target = dir.join("manifest");

        for contents in [&b"first"[..], &b"second"[..]] {
            let tmp = dir.join("staged.tmp");
            std::fs::write(&tmp, contents).expect("stage");
            let staged = path_identity(&tmp).expect("identity of the staged file");

            replace_file(&tmp, &target).expect("replace");

            assert_eq!(std::fs::read(&target).expect("read"), contents);
            assert!(!tmp.exists(), "the staged path is consumed by the move");
            if staged.is_some() {
                assert_eq!(
                    path_identity(&target).expect("identity of the target"),
                    staged,
                    "the target must be the staged file itself, moved"
                );
            }
        }

        sync_directory(&dir).expect("sync the directory that records it");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A directory that does not exist is not something to report as synced.
    ///
    /// Ungated: the answer must not depend on the host. Windows has nothing
    /// to flush, but "nothing to flush" is not the same as "yes", and a
    /// caller leaning on this as a cheap assertion gets the same answer
    /// everywhere.
    #[test]
    fn syncing_a_directory_that_does_not_exist_is_an_error() {
        let missing = std::env::temp_dir()
            .join(format!("rp-fs-no-such-dir-{}", std::process::id()))
            .join("nested");
        let _ = std::fs::remove_dir_all(&missing);
        sync_directory(&missing).expect_err("a missing directory cannot be synced");
    }

    /// Shared data and machine-local state are different roles, and a host
    /// that distinguishes them must not collapse the two.
    #[test]
    fn shared_data_is_its_own_role() {
        let data = user_data_dir(PRODUCT);
        assert!(data.is_absolute());
        assert!(data.to_string_lossy().contains(PRODUCT));
    }

    /// A private file is created, and refuses to open over an existing one.
    ///
    /// The refusal is the security-relevant half: opening over a file someone
    /// else made would inherit their permissions, so it must fail rather than
    /// succeed with weaker protection than the caller asked for.
    #[test]
    fn a_private_file_is_created_once_and_refuses_to_reopen() {
        let dir = std::env::temp_dir().join(format!("rp-fs-private-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let path = dir.join("artifact.json");
        let _ = std::fs::remove_file(&path);

        {
            let mut file = create_private_file(&path).expect("create private file");
            use std::io::Write as _;
            file.write_all(b"payload").expect("write");
        }
        assert_eq!(std::fs::read(&path).expect("read back"), b"payload");

        let second = create_private_file(&path).expect_err("must not open over an existing file");
        assert_eq!(second.kind(), std::io::ErrorKind::AlreadyExists);

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The roles are stable: asking twice gives the same answer, so a path
    /// derived at startup still names the same directory later.
    #[test]
    fn roles_are_stable_across_calls() {
        assert_eq!(user_runtime_dir(PRODUCT), user_runtime_dir(PRODUCT));
        assert_eq!(user_state_dir(PRODUCT), user_state_dir(PRODUCT));
        assert_eq!(user_run_data_root(PRODUCT), user_run_data_root(PRODUCT));
    }

    /// Any number of shared holders may coexist, but an exclusive request is
    /// refused while one is outstanding, and admitted once every shared
    /// holder has dropped.
    #[test]
    fn shared_locks_coexist_but_exclude_an_exclusive_request() {
        let dir = std::env::temp_dir().join(format!("rp-fs-lock-shared-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let path = dir.join("guard.lock");

        let first = open_lock_file(&path).expect("open first");
        let second = open_lock_file(&path).expect("open second");
        let third = open_lock_file(&path).expect("open third");

        let first_shared = try_lock_shared(&first).expect("first shared holder admitted");
        let second_shared = try_lock_shared(&second).expect("second shared holder admitted");

        let conflict =
            try_lock_exclusive(&third).expect_err("exclusive must be refused while shared holds");
        assert!(is_lock_conflict(&conflict));

        drop(first_shared);
        let conflict = try_lock_exclusive(&third)
            .expect_err("exclusive must still be refused with one shared holder left");
        assert!(is_lock_conflict(&conflict));

        drop(second_shared);
        let exclusive =
            try_lock_exclusive(&third).expect("exclusive admitted once shared holders release");
        drop(exclusive);

        drop((first, second, third));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The blocking variants eventually acquire the lock a concurrent holder
    /// releases, rather than failing immediately the way the `try_` variants
    /// do -- this is the property that distinguishes the two families.
    #[test]
    fn blocking_lock_acquires_once_the_holder_releases() {
        let dir = std::env::temp_dir().join(format!("rp-fs-lock-blocking-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let path = dir.join("guard.lock");

        let first = open_lock_file(&path).expect("open first");
        let second = open_lock_file(&path).expect("open second");

        let held = try_lock_exclusive(&first).expect("first acquires");
        drop(held);

        // With no concurrent holder left, the blocking call must return
        // immediately rather than actually block this test.
        let acquired = lock_exclusive(&second).expect("blocking lock acquires");
        drop(acquired);

        drop((first, second));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A modification time survives the round trip from Unix seconds through
    /// [`set_file_mtime`] and back out through
    /// [`FileTime::from_last_modification_time`].
    #[test]
    fn a_unix_time_survives_the_round_trip_through_a_file() {
        let dir = std::env::temp_dir().join(format!("rp-fs-mtime-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let path = dir.join("stamped");
        std::fs::write(&path, b"payload").expect("write");

        // A time with a sub-second remainder, comfortably before this test
        // ever runs, so no host's mtime resolution rounds it away.
        let stamped = FileTime::from_unix_time(1_700_000_000, 500_000_000);
        set_file_mtime(&path, stamped).expect("set mtime");

        let metadata = std::fs::metadata(&path).expect("read metadata back");
        let read_back = FileTime::from_last_modification_time(&metadata);
        assert_eq!(read_back, stamped);

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A directory takes a modification time the same way a file does.
    ///
    /// Windows needs `FILE_FLAG_BACKUP_SEMANTICS` to open a directory handle
    /// at all, so without it this is `ERROR_ACCESS_DENIED` there while both
    /// Unix hosts pass. A client restoring a stored tree puts directory
    /// mtimes back, so the gap only shows up off Linux.
    #[test]
    fn a_unix_time_survives_the_round_trip_through_a_directory() {
        let dir = std::env::temp_dir().join(format!("rp-fs-dir-mtime-{}", std::process::id()));
        let stamped_dir = dir.join("nested");
        std::fs::create_dir_all(&stamped_dir).expect("create dir");

        let stamped = FileTime::from_unix_time(1_600_000_000, 250_000_000);
        set_file_mtime(&stamped_dir, stamped).expect("set directory mtime");

        let metadata = std::fs::metadata(&stamped_dir).expect("read metadata back");
        assert_eq!(FileTime::from_last_modification_time(&metadata), stamped);

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// [`FileTime::from_system_time`] and [`FileTime::from_last_modification_time`]
    /// agree, since a file's metadata is read through [`SystemTime`] itself.
    #[test]
    fn from_system_time_and_from_metadata_agree() {
        let dir = std::env::temp_dir().join(format!("rp-fs-mtime-agree-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let path = dir.join("stamped");
        std::fs::write(&path, b"payload").expect("write");

        let metadata = std::fs::metadata(&path).expect("read metadata");
        let modified = metadata.modified().expect("host supports mtime");

        assert_eq!(
            FileTime::from_last_modification_time(&metadata),
            FileTime::from_system_time(modified)
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A time before the Unix epoch round-trips through [`SystemTime`]
    /// without silently landing on the wrong side of it.
    #[test]
    fn a_time_before_the_unix_epoch_round_trips() {
        // `epoch - 3600.25s` is `-3601` whole seconds plus a forward `0.75s`
        // remainder: nanoseconds always advance from the second mark, they
        // never subtract from it, so the second count floors.
        let before_epoch = SystemTime::UNIX_EPOCH - std::time::Duration::new(3600, 250_000_000);
        let converted = FileTime::from_system_time(before_epoch);
        assert_eq!(converted, FileTime::from_unix_time(-3601, 750_000_000));
    }

    /// `now()` reports a time in the current era, not a zeroed or default
    /// value -- a facade that silently returned the epoch would be a much
    /// harder bug to notice than one that fails loudly.
    #[test]
    fn now_reports_a_recent_time() {
        let now = FileTime::now();
        // 2020-01-01T00:00:00Z. Anything before this is not "now" by any
        // clock this crate supports.
        assert!(now > FileTime::from_unix_time(1_577_836_800, 0));
    }

    /// [`copy_file`] produces a byte-identical destination whether the
    /// filesystem gave it a reflink or fell back to a copy, and reports which
    /// one happened.
    #[test]
    fn copy_file_reproduces_the_source_and_reports_its_strategy() {
        let dir = std::env::temp_dir().join(format!("rp-fs-copy-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let source = dir.join("source");
        let destination = dir.join("destination");
        let content = b"reflink or copy, the bytes must match";
        std::fs::write(&source, content).expect("write source");

        let outcome = copy_file(&source, &destination).expect("copy succeeds");
        assert_eq!(
            std::fs::read(&destination).expect("read destination"),
            content
        );
        match outcome {
            CopyOutcome::Reflinked => {}
            CopyOutcome::Copied { bytes } => assert_eq!(bytes, content.len() as u64),
        }

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// [`reflink_file`] must not silently substitute a byte copy.
    ///
    /// This is the property the probe callers depend on: they ask "can this
    /// volume reflink?" by attempting one, so an implementation that fell
    /// back would answer yes everywhere. The test cannot assume the temp
    /// filesystem supports reflinks, so it asserts the honest disjunction --
    /// either the reflink worked and the bytes match, or it reported failure
    /// and left no destination behind. What must never happen is a reported
    /// success that was actually a copy, which is exactly what
    /// [`copy_file`] is allowed to do and this is not.
    #[test]
    fn reflink_file_either_reflinks_or_reports_that_it_could_not() {
        let dir = std::env::temp_dir().join(format!("rp-fs-reflink-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let source = dir.join("source");
        let destination = dir.join("destination");
        let content = b"a reflink is not a copy";
        std::fs::write(&source, content).expect("write source");

        match reflink_file(&source, &destination) {
            Ok(()) => assert_eq!(
                std::fs::read(&destination).expect("read destination"),
                content,
                "a successful reflink must expose the source's bytes"
            ),
            Err(_) => assert!(
                !destination.exists(),
                "a failed reflink must not leave a destination behind"
            ),
        }

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// An owned lock excludes a second holder, and releasing it lets that
    /// holder in -- whether the release is a drop or an explicit `unlock`.
    ///
    /// This is the property the borrowed guard cannot provide to a caller
    /// that must store the lock or return it, so it is checked the same way:
    /// take the lock, prove a second handle is refused, release, prove it is
    /// then accepted.
    #[test]
    fn an_owned_lock_excludes_a_second_holder_until_released() {
        let dir = std::env::temp_dir().join(format!("rp-fs-owned-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let path = dir.join("lockfile");
        std::fs::write(&path, b"").expect("create lock file");

        let open = || std::fs::File::open(&path).expect("open lock file");

        // Dropping the guard releases.
        {
            let held = lock_exclusive_owned(open()).expect("first holder takes the lock");
            let conflict =
                try_lock_exclusive(&open()).expect_err("a second holder must be refused");
            assert!(is_lock_conflict(&conflict));
            drop(held);
        }
        drop(try_lock_exclusive(&open()).expect("the lock is free once the owner drops"));

        // `unlock` releases at a chosen point and hands the handle back still
        // open, which is why it exists rather than only `drop`.
        let held = lock_exclusive_owned(open()).expect("retake the lock");
        assert!(is_lock_conflict(
            &try_lock_exclusive(&open()).expect_err("still exclusive")
        ));
        let returned = held.unlock().expect("unlock returns the handle");
        assert!(
            returned.metadata().is_ok(),
            "the handle must still be usable after unlocking"
        );
        drop(try_lock_exclusive(&open()).expect("the lock is free after unlock"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// An empty set reports itself empty and matches nothing, and a set
    /// accepts any path-like argument.
    ///
    /// Both matter to a caller that filters a walk: it asks `is_empty` once
    /// to skip matching entirely, and matches against whatever string or
    /// path it already holds rather than converting at every candidate.
    #[test]
    fn an_empty_pattern_set_is_empty_and_matches_nothing() {
        let empty = PatternSetBuilder::new().build().expect("empty set builds");
        assert!(empty.is_empty());
        assert_eq!(empty.len(), 0);
        assert!(!empty.is_match("anything"));
        assert!(!empty.is_match(Path::new("anything")));

        let populated = PatternSetBuilder::new()
            .add_pattern("*.rs")
            .add_pattern("src/**")
            .build()
            .expect("set builds");
        assert!(!populated.is_empty());
        assert_eq!(populated.len(), 2);
        // The same candidate as a `&str`, a `String` and a `&Path`.
        assert!(populated.is_match("main.rs"));
        assert!(populated.is_match(String::from("main.rs")));
        assert!(populated.is_match(Path::new("main.rs")));
        assert!(!populated.is_match("main.txt"));
    }

    /// A persisted mtime survives the round trip through its two fields.
    ///
    /// This is the property a client that stores mtimes depends on, and it
    /// is deliberately checked without `SystemTime` in the middle: the whole
    /// reason `FileTime` carries the raw pair is that `SystemTime` cannot
    /// represent every value a filesystem can hold, so a round trip through
    /// it would not prove this.
    #[test]
    fn a_file_time_round_trips_through_its_accessors() {
        for (seconds, nanoseconds) in [
            (0_i64, 0_u32),
            (1_700_000_000, 123_456_789),
            // Before 1970: the seconds go negative while the remainder stays
            // a positive count forward, which is the encoding that is easy
            // to get wrong when reading a value back.
            (-1, 999_999_999),
            (-86_400, 1),
        ] {
            let time = FileTime::from_unix_time(seconds, nanoseconds);
            assert_eq!(time.unix_seconds(), seconds);
            assert_eq!(time.nanoseconds(), nanoseconds);
            assert_eq!(
                FileTime::from_unix_time(time.unix_seconds(), time.nanoseconds()),
                time,
                "reconstructing from the accessors must yield the same value"
            );
        }
    }

    /// The mtime read back off a file is the one that was written, field for
    /// field -- not merely equal as a `SystemTime`.
    #[test]
    fn a_written_mtime_reads_back_through_the_accessors() {
        let dir = std::env::temp_dir().join(format!("rp-fs-mtime-acc-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create dir");
        let path = dir.join("stamped");
        std::fs::write(&path, b"x").expect("write file");

        let written = FileTime::from_unix_time(1_600_000_000, 500_000_000);
        set_file_mtime(&path, written).expect("set mtime");
        let metadata = std::fs::metadata(&path).expect("stat");
        let read_back = FileTime::from_last_modification_time(&metadata);

        assert_eq!(read_back.unix_seconds(), written.unix_seconds());
        assert_eq!(read_back.nanoseconds(), written.nanoseconds());

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A walk finds every file under its root, and a pruned directory's
    /// contents never appear at all.
    #[test]
    fn a_walk_finds_files_and_honours_pruning() {
        let dir = std::env::temp_dir().join(format!("rp-fs-walk-{}", std::process::id()));
        let pruned = dir.join("pruned");
        let kept = dir.join("kept");
        std::fs::create_dir_all(&pruned).expect("create pruned dir");
        std::fs::create_dir_all(&kept).expect("create kept dir");
        std::fs::write(pruned.join("secret"), b"never seen").expect("write pruned file");
        std::fs::write(kept.join("visible"), b"seen").expect("write kept file");
        std::fs::write(dir.join("root_file"), b"seen too").expect("write root file");

        let entries: Vec<DirectoryEntry> = DirectoryWalk::new(dir.clone())
            .prune_directories(|path| {
                path.file_name().and_then(|name| name.to_str()) != Some("pruned")
            })
            .walk()
            .collect::<io::Result<Vec<_>>>()
            .expect("walk succeeds");

        let file_paths: Vec<&Path> = entries
            .iter()
            .filter(|entry| entry.is_file())
            .map(DirectoryEntry::path)
            .collect();
        assert!(file_paths.contains(&kept.join("visible").as_path()));
        assert!(file_paths.contains(&dir.join("root_file").as_path()));
        assert!(
            !file_paths.contains(&pruned.join("secret").as_path()),
            "a pruned directory's contents must never be yielded"
        );
        assert!(
            entries.iter().all(|entry| entry.path() != pruned.as_path()),
            "a pruned directory itself must not be yielded either"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A set of glob patterns matches any path that satisfies at least one of
    /// them, and rejects a path that satisfies none.
    #[test]
    fn a_pattern_set_matches_any_included_pattern() {
        let set = PatternSetBuilder::new()
            .add_pattern("*.rs")
            .add_pattern("Cargo.toml")
            .build()
            .expect("valid patterns compile");

        assert!(set.is_match(Path::new("src/lib.rs")));
        assert!(set.is_match(Path::new("Cargo.toml")));
        assert!(!set.is_match(Path::new("README.md")));
    }

    /// An invalid glob pattern is reported at build time, not accepted and
    /// silently never matched.
    #[test]
    fn an_invalid_pattern_is_rejected_at_build() {
        let error = PatternSetBuilder::new()
            .add_pattern("[unterminated")
            .build()
            .expect_err("malformed glob syntax must be rejected");
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
    }
}