acyclic-fs 0.1.5

Rust SDK for versioned workspaces and embedded native mounts
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
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
//! Native Linux FUSE, macOS NFS, and Windows `ProjFS` projection boundary.
//!
//! Drivers project one canonical SDK checkout. They own kernel handles and
//! callback cursors only; filesystem truth, COW state, and publication remain
//! in `acyclic-fs`.

use crate::kernel::FileMetadata;
#[cfg(any(target_os = "linux", target_os = "macos"))]
use crate::kernel::MetadataField;
use crate::{FileId, MountId, VolumeId};
use bytes::Bytes;
use std::fs::{File, OpenOptions};
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[cfg(any(target_os = "linux", target_os = "macos"))]
use std::time::SystemTime;
#[cfg(target_os = "linux")]
use std::time::{Duration, Instant};
use thiserror::Error;

mod adapter;
pub use adapter::{CheckoutMountSource, SharedCheckout, SharedCheckoutGuard, SharedCheckoutState};

mod view_gate;

mod lazy;
pub use lazy::LazyMountSource;

mod routed;
pub use routed::RoutedMountSource;

mod customer;
pub use customer::{
    LazyMount, LazyWorkingSet, Mount, MountLifecycleError, MountOptions, MountPublication,
};

#[cfg(any(target_os = "linux", target_os = "macos"))]
mod device;

pub use crate::{
    CaptureError, CaptureOptions, CaptureReceipt, WatchCaptureReceipt, capture_baseline,
    capture_paths, capture_root_identity, capture_subtree, capture_watch_batch,
};

mod materialize;
pub use materialize::{
    HostPathReplacement, HostPathRestore, MaterializationReceipt, MaterializeError,
    MaterializeOptions, materialize_checkout, materialize_checkout_host_path,
    materialize_checkout_path, materialize_checkout_paths, restore_checkout_host_path,
};
pub(crate) use materialize::{
    MaterializeMode, materialize_checkout_paths_with_mode, materialize_checkout_with_mode,
};

mod publication;
pub use publication::{seal_checkout, seal_checkout_with_permit};

mod storage_capabilities;
pub use storage_capabilities::{
    NativeStorageCapabilities, NativeStorageCapabilityError, probe_native_storage_capabilities,
};

mod storage_accelerations;
pub use storage_accelerations::{
    NativeBlockCloneAccelerationEvidence, NativeSparseAccelerationEvidence,
    NativeStorageAccelerationError, NativeStorageAccelerationEvidence,
    probe_native_storage_accelerations,
};

#[cfg(target_os = "macos")]
mod darwin_mount;
#[cfg(target_os = "linux")]
mod fuse;

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn metadata_or<T>(field: MetadataField<T>, unavailable: T) -> T {
    match field {
        MetadataField::Unavailable => unavailable,
        MetadataField::Value(value) => value,
    }
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn system_time_ns(value: SystemTime) -> Result<i64, i32> {
    match value.duration_since(SystemTime::UNIX_EPOCH) {
        Ok(duration) => i64::try_from(duration.as_nanos()).map_err(|_| libc::EOVERFLOW),
        Err(error) => i64::try_from(error.duration().as_nanos())
            .map(|nanos| -nanos)
            .map_err(|_| libc::EOVERFLOW),
    }
}

#[cfg(target_os = "windows")]
mod projfs;

/// Concrete namespace mechanism selected for this binary.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NativeMountKind {
    /// Linux kernel FUSE through `/dev/fuse`.
    LinuxFuse,
    /// Self-contained macOS loopback-NFS session.
    MacOsNfs,
    /// Windows Projected File System provider.
    WindowsProjFs,
}

/// Native-driver isolation required for simultaneous mount sessions.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NativeMountSessionIsolation {
    /// The driver safely owns multiple live sessions in one process.
    SharedProcess,
    /// Every live session requires a distinct operating-system process.
    ProcessIsolated,
}

/// Non-destructive compile-time and host capability facts.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NativeMountCapabilities {
    /// Driver compiled for this target, if any.
    pub kind: Option<NativeMountKind>,
    /// Whether a live host probe admitted the required device/framework.
    pub available: bool,
    /// Whether exact authored effects are observable on this mechanism.
    /// A provider may still reject cross-root operations it cannot observe.
    pub writable: bool,
    /// Whether I/O issued by the provider process itself is observable.
    ///
    /// `ProjFS` suppresses provider-process notifications. Embedded callers
    /// must use the SDK mutation surface for their own writes or place the
    /// provider in a dedicated host process.
    pub provider_process_io_observable: bool,
    /// Required process isolation for simultaneous sessions.
    pub session_isolation: NativeMountSessionIsolation,
    /// Stable bounded reason when unavailable.
    pub unavailable_reason: Option<String>,
}

/// One exact mount request; cross-volume routing remains in the SDK mount table.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NativeMountRequest {
    /// Process-unique mount identity.
    pub mount_id: MountId,
    /// Projected volume.
    pub volume_id: VolumeId,
    /// Empty, caller-owned destination.
    pub destination: PathBuf,
    /// Whether authored effects may be captured.
    pub writable: bool,
}

/// Platform-neutral node facts required by kernel callbacks.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MountNode {
    /// Stable path-independent identity.
    pub file_id: FileId,
    /// Canonical node kind.
    pub kind: MountNodeKind,
    /// Logical regular-file length; zero for non-files.
    pub logical_bytes: u64,
    /// Exact namespace binding count for this path-independent file.
    pub link_count: u64,
    /// Native device identity for character/block devices only.
    pub device: Option<(u32, u32)>,
}

/// One exact mounted path result with complete authenticated metadata.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MountLookup {
    /// Stable file identity, kind, length, and link count.
    pub node: MountNode,
    /// Complete metadata; unavailable fields are never fabricated.
    pub metadata: FileMetadata,
}

/// Namespace kinds representable by native projections.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MountNodeKind {
    /// Regular byte stream.
    Regular,
    /// Directory.
    Directory,
    /// Symbolic link.
    SymbolicLink,
    /// POSIX named pipe.
    Fifo,
    /// POSIX socket node.
    Socket,
    /// POSIX character device.
    CharacterDevice,
    /// POSIX block device.
    BlockDevice,
    /// A canonical kind this driver cannot project safely.
    Unsupported,
}

/// Native sparse-file seek target.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MountSeekTarget {
    /// First allocated-zero or content byte.
    Data,
    /// First unallocated hole byte, including logical end-of-file.
    Hole,
}

/// Exact sparse-allocation operation requested by a native mount.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MountRangeAllocation {
    /// Deallocates the range without changing logical size.
    PunchHole,
    /// Replaces the range with allocated canonical zeros.
    ZeroRange {
        /// Permit logical growth to the range end.
        extend: bool,
    },
    /// Allocates only holes while preserving all existing content.
    Preallocate {
        /// Preserve logical file length.
        keep_size: bool,
    },
}

/// One data span within a bounded sparse open-file snapshot.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MountSparseSpan {
    /// Offset relative to the requested snapshot range.
    pub relative_offset: u64,
    /// Exact allocated bytes; holes are omitted.
    pub bytes: Bytes,
}

/// Bounded sparse range transferred between path-independent native handles.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MountSparseRange {
    /// Logical bytes represented, including omitted holes.
    pub logical_bytes: u64,
    /// Ordered, non-overlapping allocated spans.
    pub spans: Vec<MountSparseSpan>,
}

/// Path-independent regular-file handle used for every native open operation.
///
/// Attached implementations mutate the authenticated checkout by stable
/// [`FileId`], so rename and unlink of one hard-link name
/// cannot stale the handle. After final-link removal, drivers replace all
/// handles for the inode with one shared detached implementation.
pub trait MountOpenFile: Send + Sync + 'static {
    /// Returns current identity, size, and metadata for `fstat`-style calls.
    ///
    /// # Errors
    ///
    /// Returns stale, cancellation, or authenticated engine failures.
    fn lookup(&self) -> Result<MountLookup, MountSourceError>;
    /// Reads one exact bounded logical range.
    ///
    /// # Errors
    ///
    /// Returns range, storage, authentication, cancellation, or work failures.
    fn read_range(&self, offset: u64, length: u32) -> Result<Bytes, MountSourceError>;
    /// Reads at most `maximum_bytes`, clipping to EOF in the same coherent view.
    ///
    /// # Errors
    ///
    /// Returns the same typed failures as [`Self::read_range`].
    fn read_up_to(&self, offset: u64, maximum_bytes: u32) -> Result<Bytes, MountSourceError>;
    /// Finds the next sparse data or hole boundary.
    ///
    /// # Errors
    ///
    /// Returns sparse-tree, storage, authentication, cancellation, or work failures.
    fn seek(&self, offset: u64, target: MountSeekTarget) -> Result<Option<u64>, MountSourceError>;
    /// Replaces one exact byte range in the detached file.
    ///
    /// # Errors
    ///
    /// Returns range, storage, cancellation, allocation, or work failures.
    fn write_range(&self, offset: u64, bytes: Bytes) -> Result<(), MountSourceError>;
    /// Changes the detached logical file length.
    ///
    /// # Errors
    ///
    /// Returns sparse-tree, storage, cancellation, allocation, or work failures.
    fn resize(&self, logical_bytes: u64) -> Result<(), MountSourceError>;
    /// Applies one exact sparse allocation operation.
    ///
    /// # Errors
    ///
    /// Returns unsupported, range, storage, cancellation, allocation, or work failures.
    fn allocate_range(
        &self,
        offset: u64,
        length: u64,
        operation: MountRangeAllocation,
    ) -> Result<(), MountSourceError>;
    /// Replaces complete metadata and optionally logical size atomically from
    /// the native handle's perspective.
    ///
    /// # Errors
    ///
    /// Returns metadata, sparse-tree, storage, cancellation, allocation, or work failures.
    fn set_attributes(
        &self,
        metadata: FileMetadata,
        logical_bytes: Option<u64>,
    ) -> Result<(), MountSourceError>;
    /// Reads one exact native named attribute.
    ///
    /// # Errors
    ///
    /// Returns absence, unsupported-profile, storage, authentication, or work failures.
    fn read_attribute(&self, name: &[u8]) -> Result<Option<Bytes>, MountSourceError>;
    /// Lists one bounded page of native named-attribute names.
    ///
    /// # Errors
    ///
    /// Returns unsupported-profile, pagination, storage, authentication, or work failures.
    fn list_attributes(
        &self,
        cursor: Option<&[u8]>,
        maximum_entries: u32,
    ) -> Result<MountAttributePage, MountSourceError>;
    /// Inserts or replaces one exact native named attribute.
    ///
    /// # Errors
    ///
    /// Returns precondition, unsupported-profile, storage, or work failures.
    fn write_attribute(
        &self,
        name: &[u8],
        value: Bytes,
        mode: MountAttributeWriteMode,
    ) -> Result<(), MountSourceError>;
    /// Removes one exact native named attribute.
    ///
    /// # Errors
    ///
    /// Returns absence, unsupported-profile, storage, or work failures.
    fn remove_attribute(&self, name: &[u8]) -> Result<(), MountSourceError>;

    /// Reads one bounded sparse range without materializing holes.
    ///
    /// # Errors
    ///
    /// Returns stale, range, storage, authentication, cancellation, allocation,
    /// or bounded-work failures.
    fn read_sparse_range(
        &self,
        offset: u64,
        length: u32,
    ) -> Result<MountSparseRange, MountSourceError> {
        let logical_bytes = u64::from(length);
        let end = offset.checked_add(logical_bytes).ok_or_else(|| {
            MountSourceError::Invalid("sparse range overflows the file address space".to_owned())
        })?;
        let mut spans = Vec::new();
        let mut cursor = offset;
        while cursor < end {
            let Some(data_offset) = self.seek(cursor, MountSeekTarget::Data)? else {
                break;
            };
            if data_offset >= end {
                break;
            }
            let hole_offset = self
                .seek(data_offset, MountSeekTarget::Hole)?
                .unwrap_or(end)
                .min(end);
            if hole_offset <= data_offset {
                return Err(MountSourceError::Engine(
                    "sparse seek made no forward progress".to_owned(),
                ));
            }
            let span_length = u32::try_from(hole_offset - data_offset).map_err(|_| {
                MountSourceError::Invalid("sparse span exceeds callback bounds".to_owned())
            })?;
            let bytes = self.read_range(data_offset, span_length)?;
            if bytes.len() != usize::try_from(span_length).unwrap_or(usize::MAX) {
                return Err(MountSourceError::Stale);
            }
            spans.push(MountSparseSpan {
                relative_offset: data_offset - offset,
                bytes,
            });
            cursor = hole_offset;
        }
        Ok(MountSparseRange {
            logical_bytes,
            spans,
        })
    }

    /// Replaces one range from a sparse snapshot, preserving every hole.
    ///
    /// # Errors
    ///
    /// Returns stale, range, sparse-tree, storage, cancellation, allocation,
    /// or bounded-work failures. Native callers treat partial failures as a
    /// short copy and never report unverified completion.
    fn write_sparse_range(
        &self,
        offset: u64,
        range: &MountSparseRange,
    ) -> Result<(), MountSourceError> {
        let end = offset.checked_add(range.logical_bytes).ok_or_else(|| {
            MountSourceError::Invalid("sparse range overflows the file address space".to_owned())
        })?;
        let current = self.lookup()?.node.logical_bytes;
        if end > current {
            self.resize(end)?;
        }
        self.allocate_range(offset, range.logical_bytes, MountRangeAllocation::PunchHole)?;
        for span in &range.spans {
            let destination = offset.checked_add(span.relative_offset).ok_or_else(|| {
                MountSourceError::Invalid("sparse span offset overflows".to_owned())
            })?;
            self.write_range(destination, span.bytes.clone())?;
        }
        Ok(())
    }
}

/// One bounded directory item.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MountDirectoryEntry {
    /// Exact path-component bytes in the volume profile.
    pub name: Vec<u8>,
    /// Stable node facts.
    pub node: MountNode,
    /// Complete authenticated metadata for native stat/enumeration projection.
    pub metadata: FileMetadata,
}

/// One independently resumable directory-handle page.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MountDirectoryPage {
    /// Ordered entries after the supplied opaque cursor.
    pub entries: Vec<MountDirectoryEntry>,
    /// Opaque continuation owned by this open directory handle.
    pub next_cursor: Option<Vec<u8>>,
}

/// One bounded page of exact native named-attribute names.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MountAttributePage {
    /// Strictly ordered native names after the supplied cursor.
    pub names: Vec<Vec<u8>>,
    /// Exact last name when another page exists.
    pub next_cursor: Option<Vec<u8>>,
}

/// Native named-attribute write precondition.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MountAttributeWriteMode {
    /// Insert or replace.
    Upsert,
    /// Require absence.
    Create,
    /// Require presence.
    Replace,
}

/// Exact platform-native absolute path used only at the kernel callback edge.
///
/// Components contain raw Unix name bytes on Linux FUSE/macOS NFS and little-endian
/// UTF-16 code units on `ProjFS`. The checkout adapter converts them into the
/// volume's declared logical-name representation without lossy text routing.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct MountPath {
    components: Vec<Vec<u8>>,
}

impl MountPath {
    /// Returns the volume root.
    #[must_use]
    pub const fn root() -> Self {
        Self {
            components: Vec::new(),
        }
    }

    /// Appends one exact platform-native component.
    #[must_use]
    pub fn child(&self, component: Vec<u8>) -> Self {
        let mut components = self.components.clone();
        components.push(component);
        Self { components }
    }

    /// Borrows exact root-to-leaf components.
    #[must_use]
    pub fn components(&self) -> &[Vec<u8>] {
        &self.components
    }
}

/// Errors returned by the canonical checkout callback bridge.
#[derive(Clone, Debug, Error)]
pub enum MountSourceError {
    /// Path is authentically absent.
    #[error("path is absent")]
    NotFound,
    /// Create-only operation found an existing object.
    #[error("filesystem object already exists")]
    AlreadyExists,
    /// Operation is invalid for the resolved kind or profile.
    #[error("invalid filesystem operation: {0}")]
    Invalid(String),
    /// Operation is not exactly observable or representable on this platform.
    #[error("filesystem operation is unsupported: {0}")]
    Unsupported(String),
    /// Canonical engine operation failed.
    #[error("filesystem engine failure: {0}")]
    Engine(String),
    /// This mount or callback was fenced or cancelled.
    #[error("mount callback is stale or cancelled")]
    Stale,
}

/// An owned permit that pins one coherent projected source view.
///
/// Native drivers retain this value through every externally visible callback
/// result. Sources that can rebind must make rebinding wait for outstanding
/// permits, eliminating check-then-emit races at the kernel boundary.
pub trait MountViewLease: Send + 'static {}

impl MountViewLease for () {}

/// Synchronous callback surface implemented by an embedded checkout adapter.
///
/// Native kernels invoke callbacks on foreign threads, so this intentionally
/// exposes a blocking boundary. Implementations may enter an async runtime but
/// must enforce finite work and timeout limits internally.
pub trait MountFilesystem: Send + Sync + 'static {
    /// Whether this source can represent native POSIX named attributes.
    ///
    /// macOS must know this before mounting: advertising `namedattr` for a
    /// profile that rejects POSIX attributes turns ordinary metadata probes
    /// into I/O errors instead of allowing the OS compatibility fallback.
    fn supports_posix_named_attributes(&self) -> bool {
        false
    }

    /// Whether a native handle close is itself a publication boundary.
    ///
    /// Coordinated overlays may batch close-visible mutations until their
    /// explicit lifecycle boundary; direct checkouts publish on close.
    fn flush_on_handle_close(&self) -> bool {
        true
    }

    /// Whether a lookup may observe one coherent source view right now.
    /// Drivers must retry or fail stale while this is false.
    fn view_is_stable(&self) -> bool {
        true
    }

    /// Returns the current coherent projection view, when the source can
    /// precisely invalidate cached lookups.
    ///
    /// Sources without an epoch return `None`; drivers must then resolve every
    /// lookup through the source. An epoch may be reused only until this value
    /// changes.
    fn view_epoch(&self) -> Option<u64> {
        None
    }

    /// Changes only when existing path or handle bindings may be replaced by
    /// an external source transition. Ordinary mutations may advance
    /// `view_epoch` to invalidate caches without making a native callback
    /// stale. Sources without that distinction retain the conservative view
    /// epoch behavior.
    fn binding_epoch(&self) -> Option<u64> {
        self.view_epoch()
    }

    /// Pins the current coherent projection view for one native callback.
    ///
    /// `expected_epoch` binds a continuation to the view in which it began.
    /// Stable sources need no retained state; rebindable sources override this
    /// method with an owned synchronization permit.
    fn acquire_view_lease(
        &self,
        expected_epoch: Option<u64>,
    ) -> Result<Box<dyn MountViewLease>, MountSourceError> {
        if !self.view_is_stable() || self.view_epoch() != expected_epoch {
            return Err(MountSourceError::Stale);
        }
        Ok(Box::new(()))
    }

    /// Pins source binding identity without treating ordinary native writes
    /// as an external rebind. A callback must separately validate its cache
    /// epoch before reusing a lookup result.
    fn acquire_binding_lease(
        &self,
        expected_epoch: Option<u64>,
    ) -> Result<Box<dyn MountViewLease>, MountSourceError> {
        if !self.view_is_stable() || self.binding_epoch() != expected_epoch {
            return Err(MountSourceError::Stale);
        }
        Ok(Box::new(()))
    }

    /// Looks up one absolute portable path without following links.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure without changing checkout state.
    fn lookup(&self, path: &MountPath) -> Result<Option<MountLookup>, MountSourceError>;
    /// Opens one regular file as an attached path-independent handle.
    ///
    /// # Errors
    ///
    /// Returns absence, non-regular-kind, storage, authentication,
    /// cancellation, or bounded-work failures.
    fn open_file(&self, path: &MountPath) -> Result<Arc<dyn MountOpenFile>, MountSourceError>;
    /// Captures one regular file as a detached path-independent open-file view.
    ///
    /// The driver calls this immediately before removing the final namespace
    /// binding while one or more native handles remain open.
    ///
    /// # Errors
    ///
    /// Returns absence, non-regular-kind, storage, authentication,
    /// cancellation, or bounded-work failures.
    fn detach_file(&self, path: &MountPath) -> Result<Arc<dyn MountOpenFile>, MountSourceError>;
    /// Reads one symbolic link's exact opaque target bytes without following it.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure when the path is absent or is not a link.
    fn read_link(&self, path: &MountPath) -> Result<Bytes, MountSourceError>;
    /// Reads at most one exact logical range.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure without partial output.
    fn read_range(
        &self,
        path: &MountPath,
        offset: u64,
        length: u32,
    ) -> Result<Bytes, MountSourceError>;
    /// Finds the first sparse data or hole byte at/after one offset.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure; `None` means no matching byte exists.
    fn seek(
        &self,
        path: &MountPath,
        offset: u64,
        target: MountSeekTarget,
    ) -> Result<Option<u64>, MountSourceError>;
    /// Reads one bounded page using a handle-owned opaque cursor.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure without advancing the cursor.
    fn read_directory(
        &self,
        path: &MountPath,
        cursor: Option<&[u8]>,
        maximum_entries: u32,
    ) -> Result<MountDirectoryPage, MountSourceError>;
    /// Creates one empty regular file.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure without partial mutation.
    fn create_file(
        &self,
        path: &MountPath,
        metadata: FileMetadata,
    ) -> Result<MountLookup, MountSourceError>;
    /// Creates one empty directory.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure without partial mutation.
    fn create_directory(
        &self,
        path: &MountPath,
        metadata: FileMetadata,
    ) -> Result<MountLookup, MountSourceError>;
    /// Creates one symbolic link with an exact opaque target.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure without partial mutation.
    fn create_symbolic_link(
        &self,
        path: &MountPath,
        target: Bytes,
        metadata: FileMetadata,
    ) -> Result<MountLookup, MountSourceError>;
    /// Creates one FIFO, socket, character device, or block device.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure without partial mutation.
    fn create_special(
        &self,
        path: &MountPath,
        kind: MountNodeKind,
        device: Option<(u32, u32)>,
        metadata: FileMetadata,
    ) -> Result<MountLookup, MountSourceError>;
    /// Atomically replaces complete metadata and optionally logical size.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure without partial mutation.
    fn set_attributes(
        &self,
        path: &MountPath,
        metadata: FileMetadata,
        logical_bytes: Option<u64>,
    ) -> Result<(), MountSourceError>;
    /// Reads one exact native named attribute.
    ///
    /// # Errors
    ///
    /// Returns typed absence, unsupported-profile, or engine failures.
    fn read_attribute(
        &self,
        path: &MountPath,
        name: &[u8],
    ) -> Result<Option<Bytes>, MountSourceError>;
    /// Lists one bounded page of native named-attribute names.
    ///
    /// # Errors
    ///
    /// Returns a typed failure without advancing the supplied cursor.
    fn list_attributes(
        &self,
        path: &MountPath,
        cursor: Option<&[u8]>,
        maximum_entries: u32,
    ) -> Result<MountAttributePage, MountSourceError>;
    /// Inserts or replaces one exact native named attribute.
    ///
    /// # Errors
    ///
    /// Returns a typed failure without partial mutation.
    fn write_attribute(
        &self,
        path: &MountPath,
        name: &[u8],
        value: Bytes,
        mode: MountAttributeWriteMode,
    ) -> Result<(), MountSourceError>;
    /// Removes one exact native named attribute.
    ///
    /// # Errors
    ///
    /// Returns typed absence or engine failure without partial mutation.
    fn remove_attribute(&self, path: &MountPath, name: &[u8]) -> Result<(), MountSourceError>;
    /// Replaces one exact file range.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure without partial mutation.
    fn write_range(
        &self,
        path: &MountPath,
        offset: u64,
        bytes: Bytes,
    ) -> Result<(), MountSourceError>;
    /// Changes one file's logical length.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure without partial mutation.
    fn resize(&self, path: &MountPath, logical_bytes: u64) -> Result<(), MountSourceError>;
    /// Applies one exact sparse allocation operation.
    ///
    /// # Errors
    ///
    /// Returns a typed failure without partial mutation.
    fn allocate_range(
        &self,
        path: &MountPath,
        offset: u64,
        length: u64,
        operation: MountRangeAllocation,
    ) -> Result<(), MountSourceError>;
    /// Clones one immutable range between regular files without reading bytes.
    ///
    /// # Errors
    ///
    /// Returns a typed failure without partial mutation.
    fn clone_range(
        &self,
        source: &MountPath,
        source_offset: u64,
        destination: &MountPath,
        destination_offset: u64,
        length: u64,
    ) -> Result<(), MountSourceError>;
    /// Clones one logical range between stable attached file identities.
    ///
    /// # Errors
    ///
    /// Returns stale identity, sparse-tree, storage, cancellation, allocation,
    /// or bounded-work failures. Detached identities are rejected.
    #[allow(clippy::too_many_arguments)]
    fn clone_range_by_id(
        &self,
        source_file_id: FileId,
        source_offset: u64,
        destination_file_id: FileId,
        destination_offset: u64,
        length: u64,
    ) -> Result<(), MountSourceError>;
    /// Removes one namespace binding.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure without partial mutation.
    fn remove(&self, path: &MountPath, expected: Option<FileId>) -> Result<(), MountSourceError>;
    /// Renames one binding atomically within the volume.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure without partial mutation.
    fn rename(
        &self,
        source: &MountPath,
        destination: &MountPath,
        replace: bool,
    ) -> Result<(), MountSourceError>;
    /// Creates one same-volume hard link.
    ///
    /// # Errors
    ///
    /// Returns a typed source failure without partial mutation.
    fn hard_link(
        &self,
        source: &MountPath,
        destination: &MountPath,
    ) -> Result<(), MountSourceError>;
    /// Seals all pending authored mutations through the checkout's configured
    /// fenced publication path before acknowledging native durability.
    ///
    /// # Errors
    ///
    /// Returns stale or engine failure when authority cannot acknowledge the
    /// exact candidate generation.
    fn flush(&self) -> Result<(), MountSourceError>;
    /// Reconciles exact final host state for one projected path and seals it.
    ///
    /// This is used by native mechanisms such as `ProjFS` that report an exact
    /// close-after-modification boundary but do not expose write byte ranges.
    ///
    /// # Errors
    ///
    /// Returns a typed capture or publication failure without acknowledging
    /// the native notification.
    fn capture_host_path(
        &self,
        source_root: &Path,
        path: &MountPath,
    ) -> Result<(), MountSourceError>;
    /// Reconciles exact final host states together, preserving hard-link
    /// topology and admitting one bounded checkout candidate.
    ///
    /// # Errors
    ///
    /// Returns a typed capture or publication failure without a partial
    /// checkout candidate.
    fn capture_host_paths(
        &self,
        source_root: &Path,
        paths: &[MountPath],
    ) -> Result<(), MountSourceError>;
    /// Reconciles one imported directory and every descendant atomically.
    ///
    /// # Errors
    ///
    /// Returns a typed bounded-capture or publication failure.
    fn capture_host_subtree(
        &self,
        source_root: &Path,
        path: &MountPath,
    ) -> Result<(), MountSourceError>;
}

/// Native mount admission and lifecycle failures.
#[derive(Debug, Error)]
pub enum NativeMountError {
    /// This target has no supported native namespace mechanism.
    #[error("native mounts are unsupported on this target")]
    UnsupportedTarget,
    /// Required host driver/device is unavailable.
    #[error("native mount capability is unavailable: {0}")]
    CapabilityUnavailable(String),
    /// Destination must already exist and be empty.
    #[error("mount destination must be an existing empty directory")]
    InvalidDestination,
    /// Another process owns this exact native destination.
    #[error("mount destination is already owned by another process")]
    DestinationBusy,
    /// Requested writable semantics cannot be captured exactly.
    #[error("writable native mount is unavailable: {0}")]
    WritableUnavailable(String),
    /// Volume name representation cannot be projected exactly on this target.
    #[error("native mount cannot represent the {profile} volume profile on {platform}")]
    ProfileUnavailable {
        /// Declared volume profile.
        profile: &'static str,
        /// Current native target.
        platform: &'static str,
    },
    /// Platform driver operation failed.
    #[error("native mount driver failed: {0}")]
    Driver(String),
}

enum DriverSession {
    #[cfg(target_os = "linux")]
    Fuse(fuse::FuseSession),
    #[cfg(target_os = "macos")]
    DarwinMount(darwin_mount::DarwinMountSession),
    #[cfg(target_os = "windows")]
    ProjFs(projfs::ProjFsSession),
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    Unsupported,
}

struct DriverStartFailure {
    error: NativeMountError,
    preserve_destination_fence: bool,
}

impl DriverStartFailure {
    #[cfg(any(target_os = "windows", target_os = "macos"))]
    fn preserving_destination_fence(error: NativeMountError) -> Self {
        Self {
            error,
            preserve_destination_fence: true,
        }
    }
}

impl From<NativeMountError> for DriverStartFailure {
    fn from(error: NativeMountError) -> Self {
        Self {
            error,
            preserve_destination_fence: false,
        }
    }
}

/// Process-owned mounted namespace. Drop performs one idempotent stop.
pub struct NativeMountSession {
    mount_id: MountId,
    destination: PathBuf,
    driver: Option<DriverSession>,
    destination_guard: Option<MountDestinationGuard>,
}

impl NativeMountSession {
    /// Stable mount identity.
    #[must_use]
    pub const fn mount_id(&self) -> MountId {
        self.mount_id
    }

    /// Exact mounted destination.
    #[must_use]
    pub fn destination(&self) -> &Path {
        &self.destination
    }

    pub(crate) fn flush_callbacks(&self) -> Result<(), NativeMountError> {
        match self.driver.as_ref() {
            #[cfg(target_os = "windows")]
            Some(DriverSession::ProjFs(session)) => session.flush_callbacks(),
            #[cfg(any(target_os = "linux", target_os = "macos"))]
            Some(_) => Ok(()),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            Some(DriverSession::Unsupported) => Err(NativeMountError::UnsupportedTarget),
            None => Ok(()),
        }
    }

    /// Drops the kernel's cached entry/attributes for one mount-relative
    /// path (leading `/` optional). Linux FUSE also invalidates resident
    /// file data. This makes a projection change — such as a
    /// removed route — visible immediately instead of after a cache timeout.
    /// Linux FUSE supports nested entries when the parent directory has a
    /// cached inode; otherwise the entry becomes visible at cache expiry.
    ///
    /// # Errors
    ///
    /// Returns a driver error when the transport cannot invalidate (the
    /// change then becomes visible at the cache's own expiry).
    pub fn invalidate(&self, path: &[u8]) -> Result<(), NativeMountError> {
        match &self.driver {
            #[cfg(target_os = "linux")]
            Some(DriverSession::Fuse(session)) => session.invalidate(path),
            #[cfg(target_os = "macos")]
            Some(DriverSession::DarwinMount(session)) => session.invalidate(path),
            #[cfg(not(any(target_os = "linux", target_os = "macos")))]
            Some(_) => {
                let _ = path;
                Err(NativeMountError::Driver(
                    "invalidation is not implemented for this transport".to_owned(),
                ))
            }
            None => Err(NativeMountError::Driver("session is stopped".to_owned())),
        }
    }

    /// Detaches the kernel namespace and ends the driver session; returns
    /// whether a live session was actually stopped.
    ///
    /// # Errors
    ///
    /// Returns a platform error if the kernel namespace cannot be detached.
    pub fn stop(&mut self) -> Result<bool, NativeMountError> {
        stop_owned_session(
            &mut self.driver,
            &mut self.destination_guard,
            stop_driver,
            MountDestinationGuard::release,
        )
    }
}

fn stop_owned_session<D, G, E>(
    driver: &mut Option<D>,
    destination_guard: &mut Option<G>,
    mut stop: impl FnMut(&mut D) -> Result<(), E>,
    mut release: impl FnMut(&mut G) -> Result<(), E>,
) -> Result<bool, E> {
    if driver.is_none() && destination_guard.is_none() {
        return Ok(false);
    }
    if let Some(active) = driver.as_mut() {
        stop(active)?;
        driver.take();
    }
    if let Some(guard) = destination_guard.as_mut() {
        release(guard)?;
        destination_guard.take();
    }
    Ok(true)
}

fn drop_owned_session<D, G, E>(
    driver: &mut Option<D>,
    destination_guard: &mut Option<G>,
    stop: impl FnMut(&mut D) -> Result<(), E>,
    release: impl FnMut(&mut G) -> Result<(), E>,
) {
    if stop_owned_session(driver, destination_guard, stop, release).is_err() {
        // A failed final detach has unknown kernel state. Keep both the driver owner and its
        // destination fence alive until process exit instead of publishing the destination as
        // reusable while callbacks or a kernel namespace may still exist.
        if let Some(active) = driver.take() {
            std::mem::forget(active);
        }
        if let Some(guard) = destination_guard.take() {
            std::mem::forget(guard);
        }
    }
}

impl Drop for NativeMountSession {
    fn drop(&mut self) {
        drop_owned_session(
            &mut self.driver,
            &mut self.destination_guard,
            stop_driver,
            MountDestinationGuard::release,
        );
    }
}

/// Probes the target's one canonical native namespace mechanism.
#[must_use]
pub fn probe_native_mount() -> NativeMountCapabilities {
    platform::probe()
}

/// Starts a real native projection over the supplied canonical checkout.
///
/// # Errors
///
/// Rejects absent capabilities, non-empty destinations, unsupported writable
/// capture, or any platform-driver startup failure.
pub fn mount_native(
    request: NativeMountRequest,
    source: Arc<dyn MountFilesystem>,
) -> Result<NativeMountSession, NativeMountError> {
    let capabilities = probe_native_mount();
    if !capabilities.available {
        return Err(NativeMountError::CapabilityUnavailable(
            capabilities
                .unavailable_reason
                .unwrap_or_else(|| "unavailable".to_owned()),
        ));
    }
    if request.writable && !capabilities.writable {
        return Err(NativeMountError::WritableUnavailable(
            "the selected kernel API cannot prove exact authored effects".to_owned(),
        ));
    }
    let (driver, destination_guard) =
        start_owned_session(&request.destination, || start_driver(&request, source))?;
    Ok(NativeMountSession {
        mount_id: request.mount_id,
        destination: request.destination,
        driver: Some(driver),
        destination_guard: Some(destination_guard),
    })
}

/// Starts a native projection mounted directly over an existing,
/// non-empty directory — its contents are shadowed for the mount's
/// duration and reappear once the returned session stops. Windows `ProjFS`
/// cannot shadow local entries and this operation is unavailable there.
///
/// For callers that must project a checkout at a specific real path that
/// already has content (for example, redirecting an entire tool session
/// into a fork at the project's own root), as opposed to [`mount_native`]'s
/// ordinary empty-destination contract. Process-fencing against concurrent
/// mounts of the same destination is identical to `mount_native`.
///
/// # Errors
///
/// Same as [`mount_native`], except the destination may be non-empty; it
/// must still be an existing, non-symlink directory not already admitted
/// by another live mount. Windows returns `WritableUnavailable` because
/// `ProjFS` cannot shadow local entries.
pub fn mount_native_over_existing(
    request: NativeMountRequest,
    source: Arc<dyn MountFilesystem>,
) -> Result<NativeMountSession, NativeMountError> {
    #[cfg(windows)]
    {
        let _ = (request, source);
        Err(NativeMountError::WritableUnavailable(
            "Windows ProjFS cannot shadow an existing directory".to_owned(),
        ))
    }
    #[cfg(not(windows))]
    {
        let capabilities = probe_native_mount();
        if !capabilities.available {
            return Err(NativeMountError::CapabilityUnavailable(
                capabilities
                    .unavailable_reason
                    .unwrap_or_else(|| "unavailable".to_owned()),
            ));
        }
        if request.writable && !capabilities.writable {
            return Err(NativeMountError::WritableUnavailable(
                "the selected kernel API cannot prove exact authored effects".to_owned(),
            ));
        }
        let (driver, destination_guard) =
            start_owned_session_over_existing(&request.destination, || {
                start_driver(&request, source)
            })?;
        Ok(NativeMountSession {
            mount_id: request.mount_id,
            destination: request.destination,
            driver: Some(driver),
            destination_guard: Some(destination_guard),
        })
    }
}

/// Reclaims the process fence for one externally detached destination.
///
/// This is the supervisor-side crash-recovery boundary. A live owner keeps the
/// fence locked and causes [`NativeMountError::DestinationBusy`]; an unlocked
/// crash-left fence is acquired and removed under the parent registry lock.
/// Reclaiming an already-removed fence succeeds idempotently.
/// The caller remains responsible for proving that the kernel namespace has
/// already detached before invoking this operation.
///
/// # Errors
///
/// Rejects a missing or non-canonical destination, a live owner, unsafe fence
/// metadata, or a failure to remove the reclaimed fence.
pub fn reclaim_native_mount_destination_fence(destination: &Path) -> Result<(), NativeMountError> {
    let canonical = destination
        .canonicalize()
        .map_err(|_| NativeMountError::InvalidDestination)?;
    MountDestinationGuard::reclaim_canonical(&canonical)
}

/// Reclaims every unlocked native-mount destination fence in one parent.
///
/// The parent registry is held for the complete bounded scan, so a destination
/// cannot be admitted while its persistent fence is being classified or
/// removed. Fences held by live providers remain untouched. Malformed reserved
/// names, links, special files, or an excessive directory fail closed.
///
/// # Errors
///
/// Returns a typed destination or driver error when the parent is invalid, the
/// reserved fence namespace is unsafe, or the bounded scan cannot complete.
pub fn reclaim_stale_native_mount_destination_fences(
    parent: &Path,
) -> Result<u32, NativeMountError> {
    const MAXIMUM_PARENT_ENTRIES: usize = 4_096;
    const PREFIX: &str = ".acyclic-fs-mount-";
    const SUFFIX: &str = ".lock";

    let parent = parent
        .canonicalize()
        .map_err(|_| NativeMountError::InvalidDestination)?;
    let metadata =
        std::fs::symlink_metadata(&parent).map_err(|_| NativeMountError::InvalidDestination)?;
    if !metadata.is_dir() || metadata.file_type().is_symlink() {
        return Err(NativeMountError::InvalidDestination);
    }
    let registry_path = parent.join(".acyclic-fs-mount-registry.lock");
    let registry = acquire_mount_lock(&registry_path, true)?;
    let mut reclaimed = 0_u32;
    for (index, entry) in std::fs::read_dir(&parent)
        .map_err(|error| NativeMountError::Driver(error.to_string()))?
        .enumerate()
    {
        if index >= MAXIMUM_PARENT_ENTRIES {
            return Err(NativeMountError::Driver(
                "native mount parent exceeds its bounded entry count".to_owned(),
            ));
        }
        let entry = entry.map_err(|error| NativeMountError::Driver(error.to_string()))?;
        let name = entry.file_name();
        let Some(name) = name.to_str() else {
            continue;
        };
        if name == ".acyclic-fs-mount-registry.lock" || !name.starts_with(PREFIX) {
            continue;
        }
        let digest = name
            .strip_prefix(PREFIX)
            .and_then(|value| value.strip_suffix(SUFFIX))
            .ok_or(NativeMountError::InvalidDestination)?;
        if digest.len() != 64
            || !digest
                .bytes()
                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
        {
            return Err(NativeMountError::InvalidDestination);
        }
        let path = entry.path();
        let lock = match acquire_existing_mount_lock(&path) {
            Ok(lock) => lock,
            Err(NativeMountError::DestinationBusy) => continue,
            Err(error) => return Err(error),
        };
        drop(lock);
        match std::fs::remove_file(&path) {
            Ok(()) => {
                reclaimed = reclaimed.checked_add(1).ok_or_else(|| {
                    NativeMountError::Driver("native mount fence count overflow".to_owned())
                })?;
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(NativeMountError::Driver(error.to_string())),
        }
    }
    drop(registry);
    Ok(reclaimed)
}

/// Recovers one implementation-owned disposable native destination after its
/// provider process dies.
///
/// The exact destination fence is acquired before any detach attempt, so a
/// surviving owner is never unmounted. Recovery then performs the platform's
/// bounded detach, removes only the now-exposed destination directory, and
/// releases the persistent fence under the parent registry lock. A nonempty
/// ordinary directory is retained and rejected rather than recursively erased.
///
/// # Errors
///
/// Returns [`NativeMountError::DestinationBusy`] for a live owner and a typed
/// driver or destination failure if detach, bounded verification, directory
/// removal, or fence release cannot complete exactly.
pub fn recover_native_mount_destination(destination: &Path) -> Result<(), NativeMountError> {
    let mut guard = MountDestinationGuard::acquire_for_recovery(destination)?;
    recover_platform_destination(destination).map_err(|error| {
        NativeMountError::Driver(format!("native platform recovery failed: {error}"))
    })?;
    match std::fs::remove_dir(destination) {
        Ok(()) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => {
            return Err(NativeMountError::Driver(format!(
                "native recovered destination removal failed for {}: {error}",
                destination.display()
            )));
        }
    }
    guard.release()
}

/// Reclaims a Windows provider's dead mount path without deleting authored residue.
///
/// The caller must own this implementation-managed destination. A stale `ProjFS`
/// cache, or an ordinary nonempty directory left by fail-open tools, is moved
/// to a unique sibling before the destination is reused. The returned path is
/// the preserved residue; `None` means the destination was already empty or
/// absent. A live provider remains fenced and cannot be recovered.
///
/// # Errors
///
/// Rejects a live owner, an unexpected reparse point, or a failed quarantine.
#[cfg(windows)]
pub fn recover_native_mount_destination_preserving_residue(
    destination: &Path,
) -> Result<Option<PathBuf>, NativeMountError> {
    let name = destination
        .file_name()
        .ok_or(NativeMountError::InvalidDestination)?;
    let parent = destination
        .parent()
        .ok_or(NativeMountError::InvalidDestination)?
        .canonicalize()
        .map_err(|_| NativeMountError::InvalidDestination)?;
    let destination = parent.join(name);
    let mut guard = MountDestinationGuard::acquire_for_recovery(&destination)?;
    let preserved = projfs::quarantine_crashed_destination(&destination)?;
    guard.release()?;
    Ok(preserved)
}

/// Detaches and unfences one crash-left native destination while retaining its
/// underlying directory and authored host residue for an explicit caller
/// decision.
///
/// This is the host restart boundary: a live owner is rejected before any
/// detach, while a dead owner's kernel projection and persistent path fence are
/// removed. Call [`recover_native_mount_destination`] when the destination
/// itself is an implementation-owned disposable root.
///
/// # Errors
///
/// Returns a typed busy, detach, verification, or fence-release failure.
pub fn detach_native_mount_destination_after_crash(
    destination: &Path,
) -> Result<(), NativeMountError> {
    let mut guard = MountDestinationGuard::acquire_for_recovery(destination)?;
    detach_platform_destination_after_crash(destination)?;
    guard.release()
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn detach_platform_destination_after_crash(destination: &Path) -> Result<(), NativeMountError> {
    recover_platform_destination(destination)
}

#[cfg(target_os = "windows")]
#[allow(clippy::unnecessary_wraps)]
fn detach_platform_destination_after_crash(_destination: &Path) -> Result<(), NativeMountError> {
    // ProjFS binds the virtualization context to its provider process. Process
    // termination detaches that context, while the authenticated local cache
    // and any authored residue remain at the virtualization root.
    Ok(())
}

#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
fn detach_platform_destination_after_crash(_destination: &Path) -> Result<(), NativeMountError> {
    Err(NativeMountError::UnsupportedTarget)
}

fn start_owned_session<D>(
    destination: &Path,
    start: impl FnOnce() -> Result<D, DriverStartFailure>,
) -> Result<(D, MountDestinationGuard), NativeMountError> {
    let destination_guard = admit_destination(destination)?;
    finish_started_session(destination_guard, start())
}

fn finish_started_session<D>(
    destination_guard: MountDestinationGuard,
    result: Result<D, DriverStartFailure>,
) -> Result<(D, MountDestinationGuard), NativeMountError> {
    match result {
        Ok(driver) => Ok((driver, destination_guard)),
        Err(failure) => {
            if failure.preserve_destination_fence {
                // Startup left an unknown kernel namespace behind. Keep the
                // process-owned lock live until process exit rather than
                // publishing the destination as reusable.
                std::mem::forget(destination_guard);
            }
            Err(failure.error)
        }
    }
}

/// Same as [`start_owned_session`], but admits an existing non-empty
/// destination (see [`admit_destination_over_existing`]).
#[cfg(not(windows))]
fn start_owned_session_over_existing<D>(
    destination: &Path,
    start: impl FnOnce() -> Result<D, DriverStartFailure>,
) -> Result<(D, MountDestinationGuard), NativeMountError> {
    let destination_guard = admit_destination_over_existing(destination)?;
    finish_started_session(destination_guard, start())
}

fn admit_destination(destination: &Path) -> Result<MountDestinationGuard, NativeMountError> {
    let guard = MountDestinationGuard::acquire(destination)?;
    validate_destination(destination)?;
    Ok(guard)
}

/// Same process-fence as [`admit_destination`], but admits an existing
/// non-empty directory instead of requiring emptiness.
#[cfg(not(windows))]
fn admit_destination_over_existing(
    destination: &Path,
) -> Result<MountDestinationGuard, NativeMountError> {
    let guard = MountDestinationGuard::acquire(destination)?;
    validate_directory(destination)?;
    Ok(guard)
}

#[derive(Debug)]
struct MountDestinationGuard {
    file: Option<File>,
    lock_path: PathBuf,
    registry_path: PathBuf,
}

impl MountDestinationGuard {
    fn acquire(destination: &Path) -> Result<Self, NativeMountError> {
        let canonical = destination
            .canonicalize()
            .map_err(|_| NativeMountError::InvalidDestination)?;
        Self::acquire_canonical(&canonical)
    }

    fn acquire_for_recovery(destination: &Path) -> Result<Self, NativeMountError> {
        let name = destination
            .file_name()
            .ok_or(NativeMountError::InvalidDestination)?;
        let parent = destination
            .parent()
            .ok_or(NativeMountError::InvalidDestination)?
            .canonicalize()
            .map_err(|_| NativeMountError::InvalidDestination)?;
        Self::acquire_canonical(&parent.join(name))
    }

    fn acquire_canonical(canonical: &Path) -> Result<Self, NativeMountError> {
        let (lock_path, registry_path) = Self::paths_for_canonical(canonical)?;
        let registry = acquire_mount_lock(&registry_path, true)?;
        let file = acquire_mount_lock(&lock_path, false)?;
        drop(registry);
        Ok(Self {
            file: Some(file),
            lock_path,
            registry_path,
        })
    }

    fn paths_for_canonical(canonical: &Path) -> Result<(PathBuf, PathBuf), NativeMountError> {
        let parent = canonical
            .parent()
            .ok_or(NativeMountError::InvalidDestination)?;
        let mut identity = blake3::Hasher::new();
        identity.update(b"acyclic-fs/native-mount-destination/v1\0");
        update_path_identity(&mut identity, canonical);
        let lock_path = parent.join(format!(
            ".acyclic-fs-mount-{}.lock",
            identity.finalize().to_hex()
        ));
        let registry_path = parent.join(".acyclic-fs-mount-registry.lock");
        Ok((lock_path, registry_path))
    }

    fn reclaim_canonical(canonical: &Path) -> Result<(), NativeMountError> {
        let (lock_path, registry_path) = Self::paths_for_canonical(canonical)?;
        let registry = acquire_mount_lock(&registry_path, true)?;
        if !lock_path
            .try_exists()
            .map_err(|error| NativeMountError::Driver(error.to_string()))?
        {
            return Ok(());
        }
        let file = acquire_existing_mount_lock(&lock_path)?;
        drop(file);
        match std::fs::remove_file(&lock_path) {
            Ok(()) => {}
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(NativeMountError::Driver(error.to_string())),
        }
        drop(registry);
        Ok(())
    }

    fn release(&mut self) -> Result<(), NativeMountError> {
        let registry = acquire_mount_lock(&self.registry_path, true)?;
        release_owned_fence(&mut self.file, || {
            match std::fs::remove_file(&self.lock_path) {
                Ok(()) => {}
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                Err(error) => return Err(NativeMountError::Driver(error.to_string())),
            }
            Ok(())
        })?;
        drop(registry);
        Ok(())
    }
}

fn release_owned_fence<T, E>(
    owner: &mut Option<T>,
    release: impl FnOnce() -> Result<(), E>,
) -> Result<(), E> {
    release()?;
    owner.take();
    Ok(())
}

#[cfg(target_os = "linux")]
fn recover_platform_destination(destination: &Path) -> Result<(), NativeMountError> {
    use std::process::{Command, Stdio};

    if !linux_destination_is_mounted(destination)? {
        return Ok(());
    }
    let helper = [
        "/usr/bin/fusermount3",
        "/bin/fusermount3",
        "/usr/bin/fusermount",
        "/bin/fusermount",
    ]
    .into_iter()
    .find(|candidate| Path::new(candidate).is_file())
    .ok_or_else(|| {
        NativeMountError::CapabilityUnavailable(
            "no canonical fusermount helper is available for crash recovery".to_owned(),
        )
    })?;
    let mut child = Command::new(helper)
        .args(["-u", "-q", "-z", "--"])
        .arg(destination)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .map_err(|error| NativeMountError::Driver(error.to_string()))?;
    let deadline = Instant::now() + Duration::from_secs(30);
    loop {
        if child
            .try_wait()
            .map_err(|error| NativeMountError::Driver(error.to_string()))?
            .is_some()
        {
            break;
        }
        if Instant::now() >= deadline {
            let _ = child.kill();
            let _ = child.wait();
            return Err(NativeMountError::Driver(
                "fusermount crash recovery exceeded 30 seconds".to_owned(),
            ));
        }
        std::thread::sleep(Duration::from_millis(10));
    }
    if linux_destination_is_mounted(destination)? {
        return Err(NativeMountError::Driver(
            "FUSE destination remained mounted after crash recovery".to_owned(),
        ));
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn linux_destination_is_mounted(destination: &Path) -> Result<bool, NativeMountError> {
    use std::os::unix::fs::MetadataExt;

    let parent = destination
        .parent()
        .ok_or(NativeMountError::InvalidDestination)?
        .metadata()
        .map_err(|error| NativeMountError::Driver(error.to_string()))?;
    match destination.metadata() {
        Ok(metadata) => Ok(metadata.dev() != parent.dev()),
        Err(error) if error.raw_os_error() == Some(libc::ENOTCONN) => Ok(true),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(NativeMountError::Driver(error.to_string())),
    }
}

#[cfg(target_os = "macos")]
fn recover_platform_destination(destination: &Path) -> Result<(), NativeMountError> {
    darwin_mount::recover_destination(destination)
}

#[cfg(target_os = "windows")]
fn recover_platform_destination(destination: &Path) -> Result<(), NativeMountError> {
    projfs::recover_cache_only_destination(destination)
}

#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
fn recover_platform_destination(_destination: &Path) -> Result<(), NativeMountError> {
    Err(NativeMountError::UnsupportedTarget)
}

impl Drop for MountDestinationGuard {
    fn drop(&mut self) {
        let _ = self.release();
    }
}

fn acquire_mount_lock(path: &Path, blocking: bool) -> Result<File, NativeMountError> {
    let file = OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(path)
        .map_err(|error| NativeMountError::Driver(error.to_string()))?;
    let lock_metadata = std::fs::symlink_metadata(path)
        .map_err(|error| NativeMountError::Driver(error.to_string()))?;
    if lock_metadata.file_type().is_symlink() || !file.metadata().is_ok_and(|value| value.is_file())
    {
        return Err(NativeMountError::InvalidDestination);
    }
    if blocking {
        fs2::FileExt::lock_exclusive(&file)
            .map_err(|error| NativeMountError::Driver(error.to_string()))?;
    } else {
        fs2::FileExt::try_lock_exclusive(&file).map_err(|error| {
            if lock_is_contended(&error) {
                NativeMountError::DestinationBusy
            } else {
                NativeMountError::Driver(error.to_string())
            }
        })?;
    }
    Ok(file)
}

fn acquire_existing_mount_lock(path: &Path) -> Result<File, NativeMountError> {
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .open(path)
        .map_err(|error| NativeMountError::Driver(error.to_string()))?;
    let lock_metadata = std::fs::symlink_metadata(path)
        .map_err(|error| NativeMountError::Driver(error.to_string()))?;
    if lock_metadata.file_type().is_symlink() || !file.metadata().is_ok_and(|value| value.is_file())
    {
        return Err(NativeMountError::InvalidDestination);
    }
    fs2::FileExt::try_lock_exclusive(&file).map_err(|error| {
        if lock_is_contended(&error) {
            NativeMountError::DestinationBusy
        } else {
            NativeMountError::Driver(error.to_string())
        }
    })?;
    Ok(file)
}

fn lock_is_contended(error: &std::io::Error) -> bool {
    if error.kind() == std::io::ErrorKind::WouldBlock {
        return true;
    }
    #[cfg(windows)]
    {
        // LockFileEx reports ERROR_LOCK_VIOLATION rather than WouldBlock.
        error.raw_os_error() == Some(33)
    }
    #[cfg(not(windows))]
    {
        false
    }
}

#[cfg(unix)]
fn update_path_identity(hasher: &mut blake3::Hasher, path: &Path) {
    use std::os::unix::ffi::OsStrExt;
    hasher.update(path.as_os_str().as_bytes());
}

#[cfg(windows)]
fn update_path_identity(hasher: &mut blake3::Hasher, path: &Path) {
    use std::os::windows::ffi::OsStrExt;
    for unit in path.as_os_str().encode_wide() {
        hasher.update(&unit.to_le_bytes());
    }
}

#[cfg(not(any(unix, windows)))]
fn update_path_identity(hasher: &mut blake3::Hasher, path: &Path) {
    hasher.update(path.to_string_lossy().as_bytes());
}

fn validate_destination(destination: &Path) -> Result<(), NativeMountError> {
    validate_directory(destination)?;
    let mut entries =
        std::fs::read_dir(destination).map_err(|_| NativeMountError::InvalidDestination)?;
    if entries.next().is_some() {
        return Err(NativeMountError::InvalidDestination);
    }
    Ok(())
}

/// The directory half of [`validate_destination`], without the
/// empty-directory requirement — shared with
/// [`mount_native_over_existing`]'s admission path.
fn validate_directory(destination: &Path) -> Result<(), NativeMountError> {
    let metadata =
        std::fs::symlink_metadata(destination).map_err(|_| NativeMountError::InvalidDestination)?;
    if !metadata.is_dir() || metadata.file_type().is_symlink() {
        return Err(NativeMountError::InvalidDestination);
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn start_driver(
    request: &NativeMountRequest,
    source: Arc<dyn MountFilesystem>,
) -> Result<DriverSession, DriverStartFailure> {
    fuse::FuseSession::start(request, source)
        .map(DriverSession::Fuse)
        .map_err(Into::into)
}

#[cfg(target_os = "macos")]
fn start_driver(
    request: &NativeMountRequest,
    source: Arc<dyn MountFilesystem>,
) -> Result<DriverSession, DriverStartFailure> {
    darwin_mount::DarwinMountSession::start(request, source).map(DriverSession::DarwinMount)
}

#[cfg(target_os = "windows")]
fn start_driver(
    request: &NativeMountRequest,
    source: Arc<dyn MountFilesystem>,
) -> Result<DriverSession, DriverStartFailure> {
    projfs::ProjFsSession::start(request, source).map(DriverSession::ProjFs)
}

#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
fn start_driver(
    _request: &NativeMountRequest,
    _source: Arc<dyn MountFilesystem>,
) -> Result<DriverSession, DriverStartFailure> {
    Err(NativeMountError::UnsupportedTarget.into())
}

fn stop_driver(driver: &mut DriverSession) -> Result<(), NativeMountError> {
    match driver {
        #[cfg(target_os = "linux")]
        DriverSession::Fuse(session) => session.stop(),
        #[cfg(target_os = "macos")]
        DriverSession::DarwinMount(session) => session.stop(),
        #[cfg(target_os = "windows")]
        DriverSession::ProjFs(session) => session.stop(),
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        DriverSession::Unsupported => Err(NativeMountError::UnsupportedTarget),
    }
}

#[cfg(target_os = "linux")]
mod platform {
    use super::{NativeMountCapabilities, NativeMountKind, NativeMountSessionIsolation};

    pub(super) fn probe() -> NativeMountCapabilities {
        let available = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open("/dev/fuse")
            .is_ok();
        NativeMountCapabilities {
            kind: Some(NativeMountKind::LinuxFuse),
            available,
            writable: available,
            provider_process_io_observable: available,
            session_isolation: NativeMountSessionIsolation::SharedProcess,
            unavailable_reason: (!available).then(|| "/dev/fuse is not usable".to_owned()),
        }
    }
}

#[cfg(target_os = "macos")]
mod platform {
    use super::{NativeMountCapabilities, NativeMountKind, NativeMountSessionIsolation};

    pub(super) fn probe() -> NativeMountCapabilities {
        let available = std::path::Path::new("/sbin/mount_nfs").is_file()
            && std::path::Path::new("/sbin/umount").is_file();
        NativeMountCapabilities {
            kind: Some(NativeMountKind::MacOsNfs),
            available,
            writable: available,
            provider_process_io_observable: available,
            session_isolation: NativeMountSessionIsolation::SharedProcess,
            unavailable_reason: (!available)
                .then(|| "the built-in macOS NFS mount utilities are unavailable".to_owned()),
        }
    }
}

#[cfg(target_os = "windows")]
mod platform {
    use super::{NativeMountCapabilities, NativeMountKind, NativeMountSessionIsolation};

    pub(super) fn probe() -> NativeMountCapabilities {
        let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
        let available = std::path::Path::new(&system_root)
            .join("System32")
            .join("ProjectedFSLib.dll")
            .is_file();
        NativeMountCapabilities {
            kind: Some(NativeMountKind::WindowsProjFs),
            available,
            writable: available,
            provider_process_io_observable: false,
            session_isolation: NativeMountSessionIsolation::SharedProcess,
            unavailable_reason: (!available)
                .then(|| "ProjectedFSLib.dll is unavailable".to_owned()),
        }
    }
}

#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
mod platform {
    use super::{NativeMountCapabilities, NativeMountSessionIsolation};

    pub(super) fn probe() -> NativeMountCapabilities {
        NativeMountCapabilities {
            kind: None,
            available: false,
            writable: false,
            provider_process_io_observable: false,
            session_isolation: NativeMountSessionIsolation::ProcessIsolated,
            unavailable_reason: Some("unsupported target".to_owned()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::kernel::{LogicalName, NameEncoding, NamespacePath};
    use crate::model::{
        AccessMode, CaseSensitivity, CheckoutMode, ConcurrencyMode, ConsistencyMode,
        FilesystemProfile, GenerationSelector, Lifecycle, MutationMode, UnicodePolicy,
        VolumeConfig, VolumeLimits,
    };
    use crate::path::PortablePath;
    use crate::{
        ByteRange, CancellationToken, Fs, VolumeId, WatchBatch, WatchChange, WatchEpoch,
        WatchSequence, WorkBudget,
    };
    use bytes::Bytes;
    use std::time::{Duration, Instant};

    #[cfg(windows)]
    #[test]
    fn projfs_cannot_shadow_an_existing_directory() -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        std::fs::write(root.path().join("existing.txt"), b"real")?;
        let request = NativeMountRequest {
            mount_id: MountId::new(),
            volume_id: VolumeId::new(),
            destination: root.path().to_path_buf(),
            writable: true,
        };
        let source = Arc::new(RoutedMountSource::new());
        assert!(matches!(
            mount_native_over_existing(request, source),
            Err(NativeMountError::WritableUnavailable(_))
        ));
        assert_eq!(std::fs::read(root.path().join("existing.txt"))?, b"real");
        Ok(())
    }

    fn portable_path(
        limits: VolumeLimits,
        components: &[&[u8]],
    ) -> Result<NamespacePath, Box<dyn std::error::Error>> {
        Ok(NamespacePath::new(
            components
                .iter()
                .map(|name| {
                    LogicalName::new(
                        NameEncoding::Utf8,
                        name.to_vec(),
                        limits.maximum_component_bytes,
                    )
                })
                .collect::<Result<Vec<_>, _>>()?,
            limits,
        )?)
    }

    #[test]
    fn probe_names_exactly_one_target_driver() {
        let probe = probe_native_mount();
        assert!(probe.kind.is_some());
        assert_eq!(probe.available, probe.unavailable_reason.is_none());
    }

    #[test]
    fn destination_admission_rejects_nonempty_directories() {
        let root =
            std::env::temp_dir().join(format!("acyclic-fs-mount-admission-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        assert!(std::fs::create_dir_all(&root).is_ok());
        assert!(std::fs::write(root.join("occupied"), b"x").is_ok());
        assert!(matches!(
            validate_destination(&root),
            Err(NativeMountError::InvalidDestination)
        ));
        let _ = std::fs::remove_dir_all(root);
    }

    #[test]
    fn validate_directory_admits_nonempty_directories_but_still_rejects_non_directories()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = std::env::temp_dir().join(format!(
            "acyclic-fs-mount-over-existing-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root)?;
        std::fs::write(root.join("occupied"), b"x")?;
        assert!(validate_directory(&root).is_ok());

        let file = root.join("occupied");
        assert!(matches!(
            validate_directory(&file),
            Err(NativeMountError::InvalidDestination)
        ));

        let missing = root.join("does-not-exist");
        assert!(matches!(
            validate_directory(&missing),
            Err(NativeMountError::InvalidDestination)
        ));

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

    #[test]
    fn crash_recovery_never_removes_live_or_contaminated_destinations()
    -> Result<(), Box<dyn std::error::Error>> {
        let parent = tempfile::tempdir()?;
        let destination = parent.path().join("native-destination");
        std::fs::create_dir(&destination)?;

        let live_guard = MountDestinationGuard::acquire(&destination)?;
        assert!(matches!(
            recover_native_mount_destination(&destination),
            Err(NativeMountError::DestinationBusy)
        ));
        assert!(destination.is_dir());
        drop(live_guard);

        std::fs::write(destination.join("unowned-content"), b"retain")?;
        assert!(matches!(
            recover_native_mount_destination(&destination),
            Err(NativeMountError::Driver(_))
        ));
        assert_eq!(
            std::fs::read(destination.join("unowned-content"))?,
            b"retain"
        );
        std::fs::remove_file(destination.join("unowned-content"))?;

        recover_native_mount_destination(&destination)?;
        assert!(!destination.exists());
        let residue = std::fs::read_dir(parent.path())?
            .filter_map(Result::ok)
            .map(|entry| entry.file_name())
            .filter(|name| name != ".acyclic-fs-mount-registry.lock")
            .collect::<Vec<_>>();
        assert!(residue.is_empty());
        Ok(())
    }

    #[cfg(windows)]
    #[test]
    fn preserving_recovery_fences_live_owner_and_retains_ordinary_residue()
    -> Result<(), Box<dyn std::error::Error>> {
        let parent = tempfile::tempdir()?;
        let destination = parent.path().join("mount");
        std::fs::create_dir(&destination)?;
        let live_guard = MountDestinationGuard::acquire(&destination)?;
        assert!(matches!(
            recover_native_mount_destination_preserving_residue(&destination),
            Err(NativeMountError::DestinationBusy)
        ));
        drop(live_guard);

        std::fs::write(destination.join("authored.txt"), b"retain")?;
        let preserved = recover_native_mount_destination_preserving_residue(&destination)?
            .ok_or("nonempty destination was not preserved")?;
        assert!(!destination.exists());
        assert_eq!(std::fs::read(preserved.join("authored.txt"))?, b"retain");
        assert!(recover_native_mount_destination_preserving_residue(&destination)?.is_none());
        Ok(())
    }

    #[test]
    fn failed_destination_admission_releases_ownership() -> Result<(), Box<dyn std::error::Error>> {
        let temporary = tempfile::tempdir()?;
        let destination = temporary.path().join("mount");
        std::fs::create_dir(&destination)?;
        std::fs::write(destination.join("occupied"), b"x")?;
        assert!(matches!(
            admit_destination(&destination),
            Err(NativeMountError::InvalidDestination)
        ));
        std::fs::remove_file(destination.join("occupied"))?;
        let _recovered = admit_destination(&destination)?;
        Ok(())
    }

    #[test]
    fn failed_driver_start_releases_destination_ownership() -> Result<(), Box<dyn std::error::Error>>
    {
        let temporary = tempfile::tempdir()?;
        let destination = temporary.path().join("mount");
        std::fs::create_dir(&destination)?;

        let failed = start_owned_session::<()>(&destination, || {
            Err(NativeMountError::Driver("injected startup failure".to_owned()).into())
        });
        assert!(matches!(failed, Err(NativeMountError::Driver(_))));
        let recovered_after_error = MountDestinationGuard::acquire(&destination)?;
        drop(recovered_after_error);

        Ok(())
    }

    #[test]
    fn destination_ownership_is_process_external_and_recoverable()
    -> Result<(), Box<dyn std::error::Error>> {
        let temporary = tempfile::tempdir()?;
        let destination = temporary.path().join("mount");
        std::fs::create_dir(&destination)?;
        let first = MountDestinationGuard::acquire(&destination)?;
        let second = MountDestinationGuard::acquire(&destination);
        assert!(
            matches!(second, Err(NativeMountError::DestinationBusy)),
            "unexpected second-owner result: {second:?}"
        );
        let independent = temporary.path().join("independent");
        std::fs::create_dir(&independent)?;
        let _independent = MountDestinationGuard::acquire(&independent)?;
        drop(first);
        let _recovered = MountDestinationGuard::acquire(&destination)?;
        Ok(())
    }

    #[test]
    fn orderly_destination_release_removes_per_mount_fence()
    -> Result<(), Box<dyn std::error::Error>> {
        let temporary = tempfile::tempdir()?;
        let destination = temporary.path().join("mount");
        std::fs::create_dir(&destination)?;
        let guard = MountDestinationGuard::acquire(&destination)?;
        drop(guard);

        let mut residue = std::fs::read_dir(temporary.path())?
            .map(|entry| entry.map(|value| value.file_name()))
            .collect::<Result<Vec<_>, _>>()?;
        residue.sort();
        assert_eq!(
            residue,
            vec![
                std::ffi::OsString::from(".acyclic-fs-mount-registry.lock"),
                std::ffi::OsString::from("mount"),
            ]
        );
        Ok(())
    }

    #[test]
    fn repeated_admission_teardown_has_constant_persistent_resource_set()
    -> Result<(), Box<dyn std::error::Error>> {
        let temporary = tempfile::tempdir()?;
        let destinations = [
            temporary.path().join("mount-a"),
            temporary.path().join("mount-b"),
        ];
        for destination in &destinations {
            std::fs::create_dir(destination)?;
        }
        for ordinal in 0..1_024 {
            let guard = MountDestinationGuard::acquire(&destinations[ordinal % 2])?;
            drop(guard);
        }
        let mut residue = std::fs::read_dir(temporary.path())?
            .map(|entry| entry.map(|value| value.file_name()))
            .collect::<Result<Vec<_>, _>>()?;
        residue.sort();
        assert_eq!(
            residue,
            vec![
                std::ffi::OsString::from(".acyclic-fs-mount-registry.lock"),
                std::ffi::OsString::from("mount-a"),
                std::ffi::OsString::from("mount-b"),
            ]
        );
        for destination in destinations {
            std::fs::remove_dir(destination)?;
        }
        Ok(())
    }

    #[test]
    fn bounded_parent_sweep_reclaims_stale_fences_and_preserves_live_owners()
    -> Result<(), Box<dyn std::error::Error>> {
        let temporary = tempfile::tempdir()?;
        let live_destination = temporary.path().join("live");
        let stale_destination = temporary.path().join("stale");
        std::fs::create_dir(&live_destination)?;
        std::fs::create_dir(&stale_destination)?;
        let live = MountDestinationGuard::acquire(&live_destination)?;
        let mut stale = MountDestinationGuard::acquire(&stale_destination)?;
        let live_path = live.lock_path.clone();
        let stale_path = stale.lock_path.clone();
        stale.file.take();
        std::mem::forget(stale);

        assert_eq!(
            reclaim_stale_native_mount_destination_fences(temporary.path())?,
            1
        );
        assert!(live_path.is_file());
        assert!(!stale_path.exists());
        drop(live);
        assert_eq!(
            reclaim_stale_native_mount_destination_fences(temporary.path())?,
            0
        );
        Ok(())
    }

    #[test]
    fn parent_sweep_rejects_malformed_reserved_fence_names()
    -> Result<(), Box<dyn std::error::Error>> {
        let temporary = tempfile::tempdir()?;
        std::fs::write(temporary.path().join(".acyclic-fs-mount-invalid.lock"), b"")?;
        assert!(matches!(
            reclaim_stale_native_mount_destination_fences(temporary.path()),
            Err(NativeMountError::InvalidDestination)
        ));
        Ok(())
    }

    #[test]
    fn destination_reclaim_child_waits_for_external_release()
    -> Result<(), Box<dyn std::error::Error>> {
        let Some(destination) = std::env::var_os("ACYCLIC_FS_RECLAIM_CHILD_DESTINATION") else {
            return Ok(());
        };
        let ready = std::env::var_os("ACYCLIC_FS_RECLAIM_CHILD_READY")
            .ok_or("reclaim child readiness path is absent")?;
        let release = std::env::var_os("ACYCLIC_FS_RECLAIM_CHILD_RELEASE")
            .ok_or("reclaim child release path is absent")?;
        std::fs::write(ready, b"ready")?;
        let deadline = Instant::now() + Duration::from_secs(10);
        while !Path::new(&release).is_file() {
            if Instant::now() >= deadline {
                return Err("reclaim child release timed out".into());
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        reclaim_native_mount_destination_fence(Path::new(&destination))?;
        Ok(())
    }

    #[test]
    fn independent_supervisors_concurrently_reclaim_one_crash_left_fence()
    -> Result<(), Box<dyn std::error::Error>> {
        struct KillChildren(Vec<std::process::Child>);

        impl Drop for KillChildren {
            fn drop(&mut self) {
                for child in &mut self.0 {
                    let _ = child.kill();
                    let _ = child.wait();
                }
            }
        }

        let temporary = tempfile::tempdir()?;
        let destination = temporary.path().join("mount");
        let release = temporary.path().join("release");
        std::fs::create_dir(&destination)?;
        let mut crashed = MountDestinationGuard::acquire(&destination)?;
        let crash_left_path = crashed.lock_path.clone();
        crashed.file.take();
        std::mem::forget(crashed);

        let executable = std::env::current_exe()?;
        let mut children = KillChildren(Vec::new());
        let mut readiness = Vec::new();
        for ordinal in 0..2 {
            let ready = temporary.path().join(format!("ready-{ordinal}"));
            let child = std::process::Command::new(&executable)
                .args([
                    "--exact",
                    "native_mount::tests::destination_reclaim_child_waits_for_external_release",
                    "--nocapture",
                ])
                .env("ACYCLIC_FS_RECLAIM_CHILD_DESTINATION", &destination)
                .env("ACYCLIC_FS_RECLAIM_CHILD_READY", &ready)
                .env("ACYCLIC_FS_RECLAIM_CHILD_RELEASE", &release)
                .spawn()?;
            readiness.push(ready);
            children.0.push(child);
        }
        let deadline = Instant::now() + Duration::from_secs(10);
        while readiness.iter().any(|path| !path.is_file()) {
            for child in &mut children.0 {
                if let Some(status) = child.try_wait()? {
                    return Err(format!("reclaim child exited before release: {status}").into());
                }
            }
            if Instant::now() >= deadline {
                return Err("reclaim children did not become ready".into());
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        std::fs::write(&release, b"release")?;
        for child in &mut children.0 {
            let status = child.wait()?;
            if !status.success() {
                return Err(format!("reclaim child failed: {status}").into());
            }
        }
        children.0.clear();
        assert!(!crash_left_path.exists());
        assert!(destination.is_dir());
        Ok(())
    }

    #[test]
    fn destination_ownership_child_holds_lock_until_killed()
    -> Result<(), Box<dyn std::error::Error>> {
        let Some(destination) = std::env::var_os("ACYCLIC_FS_LOCK_CHILD_DESTINATION") else {
            return Ok(());
        };
        let ready = std::env::var_os("ACYCLIC_FS_LOCK_CHILD_READY")
            .ok_or("lock child readiness path is absent")?;
        let _guard = MountDestinationGuard::acquire(Path::new(&destination))?;
        std::fs::write(ready, b"ready")?;
        loop {
            std::thread::park();
        }
    }

    #[test]
    fn destination_ownership_is_reclaimed_after_process_death()
    -> Result<(), Box<dyn std::error::Error>> {
        struct KillOnDrop(std::process::Child);

        impl Drop for KillOnDrop {
            fn drop(&mut self) {
                let _ = self.0.kill();
                let _ = self.0.wait();
            }
        }

        let temporary = tempfile::tempdir()?;
        let destination = temporary.path().join("mount");
        let ready = temporary.path().join("ready");
        std::fs::create_dir(&destination)?;
        let child = std::process::Command::new(std::env::current_exe()?)
            .args([
                "--exact",
                "native_mount::tests::destination_ownership_child_holds_lock_until_killed",
                "--nocapture",
            ])
            .env("ACYCLIC_FS_LOCK_CHILD_DESTINATION", &destination)
            .env("ACYCLIC_FS_LOCK_CHILD_READY", &ready)
            .spawn()?;
        let mut child = KillOnDrop(child);
        let deadline = Instant::now() + Duration::from_secs(10);
        while !ready.is_file() {
            if let Some(status) = child.0.try_wait()? {
                return Err(format!("lock child exited before readiness: {status}").into());
            }
            if Instant::now() >= deadline {
                return Err("lock child readiness timed out".into());
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        assert!(matches!(
            MountDestinationGuard::acquire(&destination),
            Err(NativeMountError::DestinationBusy)
        ));
        assert!(matches!(
            reclaim_native_mount_destination_fence(&destination),
            Err(NativeMountError::DestinationBusy)
        ));
        child.0.kill()?;
        let status = child.0.wait()?;
        assert!(
            !status.success(),
            "killed lock child unexpectedly succeeded"
        );
        reclaim_native_mount_destination_fence(&destination)?;
        reclaim_native_mount_destination_fence(&destination)?;
        let _reclaimed = MountDestinationGuard::acquire(&destination)?;
        Ok(())
    }

    #[test]
    fn failed_stop_retains_driver_and_destination_ownership_for_exact_retry() {
        let mut driver = Some(7_u8);
        let mut destination_guard = Some(11_u8);
        let failure = stop_owned_session(
            &mut driver,
            &mut destination_guard,
            |_| Err("busy"),
            |_| Ok(()),
        );
        assert_eq!(failure, Err("busy"));
        assert_eq!(driver, Some(7));
        assert_eq!(destination_guard, Some(11));

        let stopped = stop_owned_session(
            &mut driver,
            &mut destination_guard,
            |_| Ok::<_, &str>(()),
            |_| Ok(()),
        );
        assert_eq!(stopped, Ok(true));
        assert_eq!(driver, None);
        assert_eq!(destination_guard, None);
        assert_eq!(
            stop_owned_session(
                &mut driver,
                &mut destination_guard,
                |_| Ok::<_, &str>(()),
                |_| Ok(()),
            ),
            Ok(false)
        );
    }

    #[test]
    fn failed_final_stop_keeps_driver_and_destination_fence_until_process_exit() {
        struct DropProbe(Arc<std::sync::atomic::AtomicUsize>);

        impl Drop for DropProbe {
            fn drop(&mut self) {
                self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            }
        }

        let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let mut driver = Some(DropProbe(Arc::clone(&drops)));
        let mut destination_guard = Some(DropProbe(Arc::clone(&drops)));
        drop_owned_session(
            &mut driver,
            &mut destination_guard,
            |_| Err("kernel detach failed"),
            |_| Ok(()),
        );
        assert!(driver.is_none());
        assert!(destination_guard.is_none());
        assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 0);
    }

    #[test]
    fn failed_fence_unlink_retains_the_operating_system_lock() {
        let mut fence = Some(7_u8);
        let failure = release_owned_fence(&mut fence, || Err("unlink failed"));
        assert_eq!(failure, Err("unlink failed"));
        assert_eq!(fence, Some(7));
        assert_eq!(
            release_owned_fence(&mut fence, || Ok::<_, &str>(())),
            Ok(())
        );
        assert_eq!(fence, None);
    }

    #[test]
    fn failed_fence_release_is_retried_without_restarting_the_driver() {
        let mut driver = Some(7_u8);
        let mut destination_guard = Some(11_u8);
        let mut first_release = true;
        let failure = stop_owned_session(
            &mut driver,
            &mut destination_guard,
            |_| Ok::<_, &str>(()),
            |_| {
                if first_release {
                    first_release = false;
                    Err("registry busy")
                } else {
                    Ok(())
                }
            },
        );
        assert_eq!(failure, Err("registry busy"));
        assert_eq!(driver, None);
        assert_eq!(destination_guard, Some(11));

        let stopped = stop_owned_session(
            &mut driver,
            &mut destination_guard,
            |_| Err("driver must not restart"),
            |_| Ok(()),
        );
        assert_eq!(stopped, Ok(true));
        assert_eq!(destination_guard, None);
    }

    #[tokio::test]
    #[allow(clippy::too_many_lines)]
    async fn capture_host_hard_links_preserves_shared_file_identity()
    -> Result<(), Box<dyn std::error::Error>> {
        let limits = VolumeLimits::default();
        let config = VolumeConfig {
            profile: FilesystemProfile::Portable,
            concurrency: ConcurrencyMode::Optimistic,
            lifecycle: Lifecycle::Ephemeral,
            case_sensitivity: CaseSensitivity::Sensitive,
            unicode: UnicodePolicy::Preserve,
            symbolic_links: true,
            hard_links: true,
            sparse_files: true,
            limits,
        };
        let cancellation = CancellationToken::new();
        let fs = Fs::memory();
        let volume = fs
            .create_volume_with_id(
                VolumeId::from_bytes([92; 16]),
                config,
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?
            .value;
        let mut checkout = volume
            .checkout(
                GenerationSelector::Head,
                CheckoutMode {
                    access: AccessMode::ReadWrite,
                    consistency: ConsistencyMode::Pinned,
                    mutations: MutationMode::PrivateOverlay,
                },
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?
            .value;
        let host = tempfile::tempdir()?;
        std::fs::write(host.path().join("a"), b"shared")?;
        std::fs::hard_link(host.path().join("a"), host.path().join("b"))?;
        let path = |name: &str| -> Result<NamespacePath, Box<dyn std::error::Error>> {
            Ok(NamespacePath::new(
                vec![LogicalName::new(
                    NameEncoding::Utf8,
                    name.as_bytes().to_vec(),
                    limits.maximum_component_bytes,
                )?],
                limits,
            )?)
        };
        let paths = [path("a")?, path("b")?];
        crate::native_capture::capture_paths_batched_with_baseline(
            &mut checkout,
            &paths,
            &CaptureOptions {
                expected_root_identity: capture_root_identity(host.path())?,
                source_root: host.path().to_path_buf(),
                maximum_paths: 2,
                maximum_extent_spans: 16,
            },
            1,
            WorkBudget::UNBOUNDED,
            &cancellation,
            None,
        )
        .await?;
        let first = checkout
            .lookup_no_follow(&paths[0], WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("first captured link missing")?;
        let second = checkout
            .lookup_no_follow(&paths[1], WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("second captured link missing")?;
        assert_eq!(first.file_id, second.file_id);
        std::fs::hard_link(host.path().join("a"), host.path().join("z"))?;
        let additional = path("z")?;
        capture_paths(
            &mut checkout,
            &[paths[0].clone(), additional.clone()],
            &CaptureOptions {
                expected_root_identity: capture_root_identity(host.path())?,
                source_root: host.path().to_path_buf(),
                maximum_paths: 2,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        let additional_id = checkout
            .lookup_no_follow(&additional, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("additional link missing")?
            .file_id;
        assert_eq!(additional_id, first.file_id);
        std::fs::hard_link(host.path().join("a"), host.path().join("0"))?;
        let earlier_alias = path("0")?;
        capture_paths(
            &mut checkout,
            &[paths[0].clone(), earlier_alias.clone()],
            &CaptureOptions {
                expected_root_identity: capture_root_identity(host.path())?,
                source_root: host.path().to_path_buf(),
                maximum_paths: 2,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        let earlier_id = checkout
            .lookup_no_follow(&earlier_alias, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("earlier alias missing")?
            .file_id;
        assert_eq!(earlier_id, first.file_id);
        std::fs::hard_link(host.path().join("a"), host.path().join("c"))?;
        let third = path("c")?;
        let watch = capture_watch_batch(
            &mut checkout,
            WatchBatch::Changes {
                epoch: WatchEpoch::from_u64(1),
                first_sequence: WatchSequence::from_u64(1),
                next_sequence: WatchSequence::from_u64(2),
                changes: vec![WatchChange::Created(third.clone())],
            },
            &CaptureOptions {
                expected_root_identity: capture_root_identity(host.path())?,
                source_root: host.path().to_path_buf(),
                maximum_paths: 1,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await;
        assert!(matches!(
            watch,
            Err(crate::OperationFailure {
                error: CaptureError::RescanRequired { .. },
                ..
            })
        ));
        assert!(
            checkout
                .lookup_no_follow(&third, WorkBudget::UNBOUNDED, &cancellation)
                .await?
                .value
                .record
                .is_none()
        );
        std::fs::write(host.path().join("existing"), b"old")?;
        let existing = path("existing")?;
        capture_paths(
            &mut checkout,
            std::slice::from_ref(&existing),
            &CaptureOptions {
                expected_root_identity: capture_root_identity(host.path())?,
                source_root: host.path().to_path_buf(),
                maximum_paths: 1,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        let old_id = checkout
            .lookup_no_follow(&existing, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("existing path missing")?
            .file_id;
        std::fs::remove_file(host.path().join("existing"))?;
        std::fs::hard_link(host.path().join("a"), host.path().join("existing"))?;
        let watch = capture_watch_batch(
            &mut checkout,
            WatchBatch::Changes {
                epoch: WatchEpoch::from_u64(1),
                first_sequence: WatchSequence::from_u64(2),
                next_sequence: WatchSequence::from_u64(3),
                changes: vec![WatchChange::Created(existing.clone())],
            },
            &CaptureOptions {
                expected_root_identity: capture_root_identity(host.path())?,
                source_root: host.path().to_path_buf(),
                maximum_paths: 1,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await;
        assert!(matches!(
            watch,
            Err(crate::OperationFailure {
                error: CaptureError::RescanRequired { .. },
                ..
            })
        ));
        assert_eq!(
            checkout
                .lookup_no_follow(&existing, WorkBudget::UNBOUNDED, &cancellation)
                .await?
                .value
                .record
                .ok_or("replacement changed checkout")?
                .file_id,
            old_id
        );
        Ok(())
    }

    #[tokio::test]
    async fn baseline_path_limit_stops_unbounded_traversal()
    -> Result<(), Box<dyn std::error::Error>> {
        let cancellation = CancellationToken::new();
        let fs = Fs::memory();
        let volume = fs
            .create_volume_with_id(
                VolumeId::from_bytes([94; 16]),
                VolumeConfig::portable(Lifecycle::Ephemeral),
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?
            .value;
        let mut checkout = volume
            .checkout(
                GenerationSelector::Head,
                CheckoutMode {
                    access: AccessMode::ReadWrite,
                    consistency: ConsistencyMode::Pinned,
                    mutations: MutationMode::PrivateOverlay,
                },
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?
            .value;
        let host = tempfile::tempdir()?;
        for index in 0..3 {
            std::fs::write(host.path().join(format!("file-{index}")), b"x")?;
        }
        let result = capture_baseline(
            &mut checkout,
            &CaptureOptions {
                expected_root_identity: capture_root_identity(host.path())?,
                source_root: host.path().to_path_buf(),
                maximum_paths: 2,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await;
        let Err(error) = result else {
            return Err("path cap unexpectedly permitted traversal".into());
        };
        assert!(matches!(error.error, CaptureError::InvalidOptions));
        assert!(error.work.items_examined <= 2);
        Ok(())
    }

    #[tokio::test]
    #[allow(clippy::too_many_lines)]
    async fn explicit_materialization_and_capture_round_trip_sparse_checkout()
    -> Result<(), Box<dyn std::error::Error>> {
        Box::pin(explicit_materialization_and_capture_round_trip_sparse_checkout_inner()).await
    }

    #[allow(clippy::too_many_lines)]
    async fn explicit_materialization_and_capture_round_trip_sparse_checkout_inner()
    -> Result<(), Box<dyn std::error::Error>> {
        let limits = VolumeLimits::default();
        let config = VolumeConfig {
            profile: FilesystemProfile::Portable,
            concurrency: ConcurrencyMode::Optimistic,
            lifecycle: Lifecycle::Ephemeral,
            case_sensitivity: CaseSensitivity::Sensitive,
            unicode: UnicodePolicy::Preserve,
            symbolic_links: true,
            hard_links: true,
            sparse_files: true,
            limits,
        };
        let cancellation = CancellationToken::new();
        let fs = Fs::memory();
        let volume = fs
            .create_volume_with_id(
                VolumeId::from_bytes([91; 16]),
                config,
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?
            .value;
        let mut checkout = volume
            .checkout(
                GenerationSelector::Head,
                CheckoutMode {
                    access: AccessMode::ReadWrite,
                    consistency: ConsistencyMode::Pinned,
                    mutations: MutationMode::PrivateOverlay,
                },
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?
            .value;
        let file = NamespacePath::new(
            vec![LogicalName::new(
                NameEncoding::Utf8,
                b"sparse.bin".to_vec(),
                limits.maximum_component_bytes,
            )?],
            limits,
        )?;
        checkout
            .create_file(
                file.clone(),
                Bytes::from_static(b"head"),
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?;
        checkout
            .resize_file(
                file.clone(),
                1024 * 1024,
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?;
        checkout
            .write_file(
                file.clone(),
                1024 * 1024 - 4,
                Bytes::from_static(b"tail"),
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?;

        let temporary = tempfile::tempdir()?;
        let destination = temporary.path().join("view");
        std::fs::create_dir(&destination)?;
        let materialized = Box::pin(materialize_checkout(
            &mut checkout,
            &MaterializeOptions {
                destination: destination.clone(),
                maximum_directory_entries: 16,
                maximum_extent_spans: 16,
                transfer_bytes: 64 * 1024,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        ))
        .await
        .map_err(|error| std::io::Error::other(format!("sparse materialization: {error}")))?;
        assert_eq!(materialized.value.files, 1);
        let host_file = destination.join("sparse.bin");
        assert_eq!(
            std::fs::metadata(&host_file)
                .map_err(|error| std::io::Error::other(format!("materialized metadata: {error}")))?
                .len(),
            1024 * 1024
        );
        let body = std::fs::read(&host_file)
            .map_err(|error| std::io::Error::other(format!("materialized read: {error}")))?;
        assert_eq!(&body[..4], b"head");
        assert_eq!(&body[body.len() - 4..], b"tail");

        let sparse_capture = capture_paths(
            &mut checkout,
            std::slice::from_ref(&file),
            &CaptureOptions {
                expected_root_identity: capture_root_identity(&destination)?,
                source_root: destination.clone(),
                maximum_paths: 1,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await
        .map_err(|error| std::io::Error::other(format!("sparse recapture: {error}")))?;
        assert!(sparse_capture.value.staged_file_bytes < 1024 * 1024);
        let sparse_plan = checkout
            .plan_file_extents(
                &file,
                ByteRange {
                    offset: 0,
                    length: 1024 * 1024,
                },
                16,
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?
            .value
            .ok_or("captured sparse file returned an inline plan")?;
        assert!(
            sparse_plan
                .spans
                .iter()
                .any(|span| matches!(span.kind, crate::kernel::ExtentKind::Hole))
        );

        std::fs::write(&host_file, b"captured")?;
        let captured = capture_paths(
            &mut checkout,
            std::slice::from_ref(&file),
            &CaptureOptions {
                expected_root_identity: capture_root_identity(&destination)?,
                source_root: destination.clone(),
                maximum_paths: 1,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        assert_eq!(captured.value.changed_paths, 1);
        let read = checkout
            .read_file_range(
                &file,
                ByteRange {
                    offset: 0,
                    length: 8,
                },
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?;
        assert_eq!(read.value.bytes.as_ref(), b"captured");

        let before_rename = checkout
            .lookup_no_follow(&file, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("captured file disappeared")?;
        let renamed = NamespacePath::new(
            vec![LogicalName::new(
                NameEncoding::Utf8,
                b"renamed.bin".to_vec(),
                limits.maximum_component_bytes,
            )?],
            limits,
        )?;
        std::fs::rename(&host_file, destination.join("renamed.bin"))?;
        let watch = capture_watch_batch(
            &mut checkout,
            WatchBatch::Changes {
                epoch: WatchEpoch::from_u64(7),
                first_sequence: WatchSequence::from_u64(11),
                next_sequence: WatchSequence::from_u64(12),
                changes: vec![WatchChange::Renamed {
                    from: file.clone(),
                    to: renamed.clone(),
                }],
            },
            &CaptureOptions {
                expected_root_identity: capture_root_identity(&destination)?,
                source_root: destination.clone(),
                maximum_paths: 1,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        assert_eq!(watch.value.next_sequence.get(), 12);
        let old = checkout
            .lookup_no_follow(&file, WorkBudget::UNBOUNDED, &cancellation)
            .await?;
        assert!(old.value.record.is_none());
        let new = checkout
            .lookup_no_follow(&renamed, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("renamed file disappeared")?;
        assert_eq!(new.file_id, before_rename.file_id);

        let moved = NamespacePath::new(
            vec![LogicalName::new(
                NameEncoding::Utf8,
                b"moved.bin".to_vec(),
                limits.maximum_component_bytes,
            )?],
            limits,
        )?;
        std::fs::rename(
            destination.join("renamed.bin"),
            destination.join("moved.bin"),
        )?;
        std::fs::write(destination.join("renamed.bin"), b"replacement")?;
        capture_watch_batch(
            &mut checkout,
            WatchBatch::Changes {
                epoch: WatchEpoch::from_u64(7),
                first_sequence: WatchSequence::from_u64(12),
                next_sequence: WatchSequence::from_u64(14),
                changes: vec![
                    WatchChange::Renamed {
                        from: renamed.clone(),
                        to: moved.clone(),
                    },
                    WatchChange::Created(renamed.clone()),
                ],
            },
            &CaptureOptions {
                expected_root_identity: capture_root_identity(&destination)?,
                source_root: destination.clone(),
                maximum_paths: 2,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        let moved_record = checkout
            .lookup_no_follow(&moved, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("moved file disappeared")?;
        let replacement_record = checkout
            .lookup_no_follow(&renamed, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("replacement file disappeared")?;
        assert_eq!(moved_record.file_id, before_rename.file_id);
        assert_ne!(replacement_record.file_id, before_rename.file_id);
        let replacement = checkout
            .read_file_range(
                &renamed,
                ByteRange {
                    offset: 0,
                    length: 11,
                },
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?;
        assert_eq!(replacement.value.bytes.as_ref(), b"replacement");

        std::fs::write(destination.join("renamed.bin"), b"replaced-again")?;
        capture_watch_batch(
            &mut checkout,
            WatchBatch::Changes {
                epoch: WatchEpoch::from_u64(7),
                first_sequence: WatchSequence::from_u64(14),
                next_sequence: WatchSequence::from_u64(15),
                changes: vec![WatchChange::Created(renamed.clone())],
            },
            &CaptureOptions {
                expected_root_identity: capture_root_identity(&destination)?,
                source_root: destination.clone(),
                maximum_paths: 1,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        let replaced_again = checkout
            .lookup_no_follow(&renamed, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("standalone create replacement disappeared")?;
        assert_ne!(replaced_again.file_id, replacement_record.file_id);

        std::fs::write(destination.join("renamed.bin"), b"compound-replacement")?;
        capture_watch_batch(
            &mut checkout,
            WatchBatch::Changes {
                epoch: WatchEpoch::from_u64(7),
                first_sequence: WatchSequence::from_u64(15),
                next_sequence: WatchSequence::from_u64(17),
                changes: vec![
                    WatchChange::Created(renamed.clone()),
                    WatchChange::Modified(renamed.clone()),
                ],
            },
            &CaptureOptions {
                expected_root_identity: capture_root_identity(&destination)?,
                source_root: destination.clone(),
                maximum_paths: 2,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        let compound_replacement = checkout
            .lookup_no_follow(&renamed, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("compound replacement disappeared")?;
        assert_ne!(compound_replacement.file_id, replaced_again.file_id);

        let dirty_baseline = capture_baseline(
            &mut checkout,
            &CaptureOptions {
                expected_root_identity: capture_root_identity(&destination)?,
                source_root: destination.clone(),
                maximum_paths: 16,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await;
        let Err(dirty_baseline) = dirty_baseline else {
            return Err("dirty baseline replaced private mutations".into());
        };
        assert!(matches!(dirty_baseline.error, CaptureError::DirtyCheckout));

        seal_checkout(
            &mut checkout,
            crate::OperationId::new(),
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;

        std::fs::remove_file(destination.join("renamed.bin"))?;
        std::fs::remove_file(destination.join("moved.bin"))?;
        std::fs::create_dir(destination.join("nested"))?;
        std::fs::write(destination.join("nested").join("new.txt"), b"baseline")?;
        let baseline = capture_baseline(
            &mut checkout,
            &CaptureOptions {
                expected_root_identity: capture_root_identity(&destination)?,
                source_root: destination.clone(),
                maximum_paths: 16,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        assert_eq!(baseline.value.examined_paths, 4);
        let removed = checkout
            .lookup_no_follow(&renamed, WorkBudget::UNBOUNDED, &cancellation)
            .await?;
        assert!(removed.value.record.is_none());
        let removed_moved = checkout
            .lookup_no_follow(&moved, WorkBudget::UNBOUNDED, &cancellation)
            .await?;
        assert!(removed_moved.value.record.is_none());
        let nested = PortablePath::parse("/nested/new.txt", limits)?;
        let nested = NamespacePath::from_portable(&nested, limits)?;
        let nested_read = checkout
            .read_file_range(
                &nested,
                ByteRange {
                    offset: 0,
                    length: 8,
                },
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?;
        assert_eq!(nested_read.value.bytes.as_ref(), b"baseline");

        let missing =
            NamespacePath::from_portable(&PortablePath::parse("/missing.tmp", limits)?, limits)?;
        let arrived =
            NamespacePath::from_portable(&PortablePath::parse("/arrived.txt", limits)?, limits)?;
        std::fs::write(destination.join("arrived.txt"), b"arrival")?;
        capture_watch_batch(
            &mut checkout,
            WatchBatch::Changes {
                epoch: WatchEpoch::from_u64(8),
                first_sequence: WatchSequence::from_u64(0),
                next_sequence: WatchSequence::from_u64(1),
                changes: vec![WatchChange::Renamed {
                    from: missing,
                    to: arrived.clone(),
                }],
            },
            &CaptureOptions {
                expected_root_identity: capture_root_identity(&destination)?,
                source_root: destination.clone(),
                maximum_paths: 1,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        assert_eq!(
            checkout
                .read_file_range(
                    &arrived,
                    ByteRange {
                        offset: 0,
                        length: 7,
                    },
                    WorkBudget::UNBOUNDED,
                    &cancellation,
                )
                .await?
                .value
                .bytes
                .as_ref(),
            b"arrival"
        );

        let prior_arrival = checkout
            .lookup_no_follow(&arrived, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("arrival disappeared")?;
        let temporary_name =
            NamespacePath::from_portable(&PortablePath::parse("/arrival.tmp", limits)?, limits)?;
        std::fs::write(destination.join("arrival.tmp"), b"replacement-arrival")?;
        std::fs::remove_file(destination.join("arrived.txt"))?;
        std::fs::rename(
            destination.join("arrival.tmp"),
            destination.join("arrived.txt"),
        )?;
        capture_watch_batch(
            &mut checkout,
            WatchBatch::Changes {
                epoch: WatchEpoch::from_u64(8),
                first_sequence: WatchSequence::from_u64(1),
                next_sequence: WatchSequence::from_u64(3),
                changes: vec![
                    WatchChange::Created(temporary_name.clone()),
                    WatchChange::Renamed {
                        from: temporary_name,
                        to: arrived.clone(),
                    },
                ],
            },
            &CaptureOptions {
                expected_root_identity: capture_root_identity(&destination)?,
                source_root: destination.clone(),
                maximum_paths: 2,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        let replaced_arrival = checkout
            .lookup_no_follow(&arrived, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("replacement arrival disappeared")?;
        assert_ne!(replaced_arrival.file_id, prior_arrival.file_id);

        let created_and_modified = NamespacePath::from_portable(
            &PortablePath::parse("/created-and-modified.txt", limits)?,
            limits,
        )?;
        std::fs::write(
            destination.join("created-and-modified.txt"),
            b"created-and-modified",
        )?;
        capture_watch_batch(
            &mut checkout,
            WatchBatch::Changes {
                epoch: WatchEpoch::from_u64(8),
                first_sequence: WatchSequence::from_u64(3),
                next_sequence: WatchSequence::from_u64(5),
                changes: vec![
                    WatchChange::Created(created_and_modified.clone()),
                    WatchChange::Modified(created_and_modified.clone()),
                ],
            },
            &CaptureOptions {
                expected_root_identity: capture_root_identity(&destination)?,
                source_root: destination.clone(),
                maximum_paths: 2,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        assert_eq!(
            checkout
                .read_file_range(
                    &created_and_modified,
                    ByteRange {
                        offset: 0,
                        length: 20,
                    },
                    WorkBudget::UNBOUNDED,
                    &cancellation,
                )
                .await?
                .value
                .bytes
                .as_ref(),
            b"created-and-modified"
        );

        let expected_root_identity = capture_root_identity(&destination)?;
        let displaced = temporary.path().join("displaced-view");
        std::fs::rename(&destination, &displaced)?;
        std::fs::create_dir(&destination)?;
        std::fs::write(destination.join("arrived.txt"), b"untrusted-root")?;
        let swapped = capture_paths(
            &mut checkout,
            std::slice::from_ref(&arrived),
            &CaptureOptions {
                source_root: destination,
                expected_root_identity,
                maximum_paths: 1,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await;
        let Err(swapped) = swapped else {
            return Err("capture accepted a replacement root".into());
        };
        assert!(matches!(swapped.error, CaptureError::RootChanged));
        Ok(())
    }

    #[tokio::test]
    async fn coalesced_parent_child_removals_capture_deepest_first()
    -> Result<(), Box<dyn std::error::Error>> {
        let config = VolumeConfig::portable(Lifecycle::Ephemeral);
        let limits = config.limits;
        let cancellation = CancellationToken::new();
        let fs = Fs::memory();
        let volume = fs
            .create_volume(config, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value;
        let mut checkout = volume
            .checkout(
                GenerationSelector::Head,
                CheckoutMode {
                    access: AccessMode::ReadWrite,
                    consistency: ConsistencyMode::Pinned,
                    mutations: MutationMode::PrivateOverlay,
                },
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?
            .value;
        let temporary = tempfile::tempdir()?;
        let root = temporary.path().join("capture");
        std::fs::create_dir(&root)?;
        let options = CaptureOptions {
            expected_root_identity: capture_root_identity(&root)?,
            source_root: root.clone(),
            maximum_paths: 8,
            maximum_extent_spans: 8,
        };
        capture_baseline(
            &mut checkout,
            &options,
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        let parent = portable_path(limits, &[b"parent"])?;
        let child = portable_path(limits, &[b"parent", b"child.txt"])?;
        std::fs::create_dir(root.join("parent"))?;
        std::fs::write(root.join("parent").join("child.txt"), b"child")?;
        capture_watch_batch(
            &mut checkout,
            WatchBatch::Changes {
                epoch: WatchEpoch::from_u64(1),
                first_sequence: WatchSequence::from_u64(0),
                next_sequence: WatchSequence::from_u64(1),
                changes: vec![WatchChange::Created(parent.clone())],
            },
            &options,
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        assert!(
            checkout
                .lookup_no_follow(&child, WorkBudget::UNBOUNDED, &cancellation)
                .await?
                .value
                .record
                .is_some()
        );
        std::fs::remove_file(root.join("parent").join("child.txt"))?;
        std::fs::remove_dir(root.join("parent"))?;
        capture_watch_batch(
            &mut checkout,
            WatchBatch::Changes {
                epoch: WatchEpoch::from_u64(1),
                first_sequence: WatchSequence::from_u64(1),
                next_sequence: WatchSequence::from_u64(3),
                changes: vec![
                    WatchChange::Removed(parent.clone()),
                    WatchChange::Removed(child.clone()),
                ],
            },
            &options,
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        assert!(
            checkout
                .lookup_no_follow(&parent, WorkBudget::UNBOUNDED, &cancellation)
                .await?
                .value
                .record
                .is_none()
        );
        Ok(())
    }

    // FSEvents can replay creation hints for paths that existed before the
    // watcher's baseline. Stale created hints must not replace a directory
    // that is still a directory: that remove is illegal while the directory
    // has children, and hints only select which paths to authenticate.
    #[tokio::test]
    async fn stale_created_hints_for_existing_directory_capture_exactly()
    -> Result<(), Box<dyn std::error::Error>> {
        let config = VolumeConfig::portable(Lifecycle::Ephemeral);
        let limits = config.limits;
        let cancellation = CancellationToken::new();
        let fs = Fs::memory();
        let volume = fs
            .create_volume(config, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value;
        let mut checkout = volume
            .checkout(
                GenerationSelector::Head,
                CheckoutMode {
                    access: AccessMode::ReadWrite,
                    consistency: ConsistencyMode::Pinned,
                    mutations: MutationMode::PrivateOverlay,
                },
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?
            .value;
        let nested = portable_path(limits, &[b"nested"])?;
        let child = portable_path(limits, &[b"nested", b"child.txt"])?;
        let created = portable_path(limits, &[b"watch.txt"])?;

        let temporary = tempfile::tempdir()?;
        std::fs::create_dir(temporary.path().join("nested"))?;
        std::fs::write(temporary.path().join("nested/child.txt"), b"child")?;
        let options = CaptureOptions {
            source_root: temporary.path().to_path_buf(),
            expected_root_identity: capture_root_identity(temporary.path())?,
            maximum_paths: 16,
            maximum_extent_spans: 16,
        };
        capture_baseline(
            &mut checkout,
            &options,
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        let directory_before = checkout
            .lookup_no_follow(&nested, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("captured directory disappeared")?;

        std::fs::write(temporary.path().join("watch.txt"), b"created")?;
        capture_watch_batch(
            &mut checkout,
            WatchBatch::Changes {
                epoch: WatchEpoch::from_u64(1),
                first_sequence: WatchSequence::from_u64(0),
                next_sequence: WatchSequence::from_u64(6),
                changes: vec![
                    WatchChange::Created(child.clone()),
                    WatchChange::MetadataChanged(child.clone()),
                    WatchChange::Created(nested.clone()),
                    WatchChange::MetadataChanged(nested.clone()),
                    WatchChange::Created(created.clone()),
                    WatchChange::Modified(created.clone()),
                ],
            },
            &options,
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        let directory_after = checkout
            .lookup_no_follow(&nested, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value
            .record
            .ok_or("directory disappeared after stale hints")?;
        assert_eq!(directory_after.file_id, directory_before.file_id);
        for (path, expected) in [(&child, b"child".as_slice()), (&created, b"created")] {
            let read = checkout
                .read_file_range(
                    path,
                    ByteRange {
                        offset: 0,
                        length: u64::try_from(expected.len())?,
                    },
                    WorkBudget::UNBOUNDED,
                    &cancellation,
                )
                .await?;
            assert_eq!(read.value.bytes.as_ref(), expected);
        }
        Ok(())
    }

    #[tokio::test]
    async fn windows_created_and_modified_hint_captures_one_new_file()
    -> Result<(), Box<dyn std::error::Error>> {
        let mut config = VolumeConfig::portable(Lifecycle::Ephemeral);
        config.profile = FilesystemProfile::Windows;
        let limits = config.limits;
        let cancellation = CancellationToken::new();
        let fs = Fs::memory();
        let volume = fs
            .create_volume(config, WorkBudget::UNBOUNDED, &cancellation)
            .await?
            .value;
        let mut checkout = volume
            .checkout(
                GenerationSelector::Head,
                CheckoutMode {
                    access: AccessMode::ReadWrite,
                    consistency: ConsistencyMode::Pinned,
                    mutations: MutationMode::PrivateOverlay,
                },
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?
            .value;
        let name = "watch.txt"
            .encode_utf16()
            .flat_map(u16::to_le_bytes)
            .collect();
        let path = NamespacePath::new(
            vec![LogicalName::new(
                NameEncoding::WindowsUtf16Le,
                name,
                limits.maximum_component_bytes,
            )?],
            limits,
        )?;
        let temporary = tempfile::tempdir()?;
        std::fs::write(temporary.path().join("watch.txt"), b"created")?;
        capture_watch_batch(
            &mut checkout,
            WatchBatch::Changes {
                epoch: WatchEpoch::from_u64(1),
                first_sequence: WatchSequence::from_u64(0),
                next_sequence: WatchSequence::from_u64(2),
                changes: vec![
                    WatchChange::Created(path.clone()),
                    WatchChange::Modified(path.clone()),
                ],
            },
            &CaptureOptions {
                source_root: temporary.path().to_path_buf(),
                expected_root_identity: capture_root_identity(temporary.path())?,
                maximum_paths: 16,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        let read = checkout
            .read_file_range(
                &path,
                ByteRange {
                    offset: 0,
                    length: 7,
                },
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?;
        assert_eq!(read.value.bytes.as_ref(), b"created");
        Ok(())
    }

    #[cfg(unix)]
    #[tokio::test]
    #[allow(clippy::too_many_lines)]
    async fn posix_fifo_and_socket_materialize_and_capture_exactly()
    -> Result<(), Box<dyn std::error::Error>> {
        use std::os::unix::fs::FileTypeExt;

        let limits = VolumeLimits::default();
        let config = VolumeConfig {
            profile: FilesystemProfile::Posix,
            concurrency: ConcurrencyMode::Optimistic,
            lifecycle: Lifecycle::Ephemeral,
            case_sensitivity: CaseSensitivity::Sensitive,
            unicode: UnicodePolicy::Preserve,
            symbolic_links: true,
            hard_links: true,
            sparse_files: true,
            limits,
        };
        let cancellation = CancellationToken::new();
        let fs = Fs::memory();
        let source = fs
            .create_volume_with_id(
                VolumeId::from_bytes([92; 16]),
                config,
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?
            .value;
        let mut source_checkout = source
            .checkout(
                GenerationSelector::Head,
                CheckoutMode {
                    access: AccessMode::ReadWrite,
                    consistency: ConsistencyMode::Pinned,
                    mutations: MutationMode::PrivateOverlay,
                },
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?
            .value;
        let fifo = NamespacePath::new(
            vec![LogicalName::new(
                NameEncoding::PosixBytes,
                b"pipe".to_vec(),
                limits.maximum_component_bytes,
            )?],
            limits,
        )?;
        let socket = NamespacePath::new(
            vec![LogicalName::new(
                NameEncoding::PosixBytes,
                b"socket".to_vec(),
                limits.maximum_component_bytes,
            )?],
            limits,
        )?;
        source_checkout
            .create_empty_special(
                fifo.clone(),
                crate::kernel::FileKind::Fifo,
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?;
        source_checkout
            .create_empty_special(
                socket.clone(),
                crate::kernel::FileKind::Socket,
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?;

        let temporary = tempfile::tempdir()?;
        let destination = temporary.path().join("special-view");
        std::fs::create_dir(&destination)?;
        let materialized = Box::pin(materialize_checkout(
            &mut source_checkout,
            &MaterializeOptions {
                destination: destination.clone(),
                maximum_directory_entries: 16,
                maximum_extent_spans: 16,
                transfer_bytes: 64 * 1024,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        ))
        .await?;
        assert_eq!(materialized.value.special_files, 2);
        assert!(
            std::fs::symlink_metadata(destination.join("pipe"))?
                .file_type()
                .is_fifo()
        );
        assert!(
            std::fs::symlink_metadata(destination.join("socket"))?
                .file_type()
                .is_socket()
        );

        let captured = fs
            .create_volume_with_id(
                VolumeId::from_bytes([93; 16]),
                config,
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?
            .value;
        let mut captured_checkout = captured
            .checkout(
                GenerationSelector::Head,
                CheckoutMode {
                    access: AccessMode::ReadWrite,
                    consistency: ConsistencyMode::Pinned,
                    mutations: MutationMode::PrivateOverlay,
                },
                WorkBudget::UNBOUNDED,
                &cancellation,
            )
            .await?
            .value;
        let receipt = capture_baseline(
            &mut captured_checkout,
            &CaptureOptions {
                expected_root_identity: capture_root_identity(&destination)?,
                source_root: destination,
                maximum_paths: 2,
                maximum_extent_spans: 16,
            },
            WorkBudget::UNBOUNDED,
            &cancellation,
        )
        .await?;
        assert_eq!(receipt.value.changed_paths, 2);
        assert_eq!(
            captured_checkout
                .lookup_no_follow(&fifo, WorkBudget::UNBOUNDED, &cancellation)
                .await?
                .value
                .record
                .ok_or("captured FIFO is absent")?
                .kind,
            crate::kernel::FileKind::Fifo
        );
        assert_eq!(
            captured_checkout
                .lookup_no_follow(&socket, WorkBudget::UNBOUNDED, &cancellation)
                .await?
                .value
                .record
                .ok_or("captured socket is absent")?
                .kind,
            crate::kernel::FileKind::Socket
        );
        Ok(())
    }
}