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
//! Native directory sources over the canonical checkout and watcher engines.

use crate::foundation::{Digest, Epoch, Head, OperationId, ProposedCommit, Sequence};
use crate::kernel::{
    DurableSourceMode, DurableSourceState, PublishGenerationRequest, RebaseDecision, SourceFact,
    SourceInvalidation, contextual_publication_fingerprint, decode_published_generation,
    decode_source_fact, encode_source_fact, source_authority_id, volume_authority_id,
};
use crate::model::{CheckoutMode, GenerationSelector};
use crate::path::PortablePath;
use crate::{
    AppendOutcome, AsyncAuthorityStore, AsyncObjectStore, CancellationToken, CaptureOptions,
    CapturePolicy, Checkout, CheckoutCommitOutcome, CreateAuthorityOutcome, Fs, Generation,
    IdempotencyKey, NativeWatch, NativeWatchOptions, ReplayLimit, WatchBatch,
    WatchInvalidationReason, WorkBudget, Workspace,
};
use bytes::Bytes;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use thiserror::Error;
use tokio::sync::Mutex;

/// Whether an attached directory is fixed or continuously reconciled.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SourceMode {
    /// Capture one exact baseline and require explicit rescans thereafter.
    Pinned,
    /// Track bounded native hints and fail closed when continuity is lost.
    Tracking,
}

/// Exact bounded native-source configuration.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SourceOptions {
    /// Source advancement behavior.
    pub mode: SourceMode,
    /// Maximum paths in one authenticated baseline or reconciliation batch.
    pub maximum_paths: u32,
    /// Maximum sparse data spans admitted per regular file.
    pub maximum_extent_spans: u32,
    /// Maximum pending native hints before continuity is invalidated.
    pub maximum_queued_changes: u32,
    /// Canonical portable prefixes omitted from capture and deletion inference.
    pub excluded_paths: Vec<PortablePath>,
}

impl Default for SourceOptions {
    fn default() -> Self {
        Self {
            mode: SourceMode::Tracking,
            maximum_paths: 262_144,
            maximum_extent_spans: 65_536,
            maximum_queued_changes: 65_536,
            excluded_paths: Vec::new(),
        }
    }
}

/// Durable semantic source state exposed to callers.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SourceState {
    /// Workspace and attached directory agree at the acknowledged cursor.
    Clean,
    /// A bounded host interval is being authenticated and captured.
    PendingCapture,
    /// Native continuity was lost; automatic advancement is stopped.
    NeedsRescan(WatchInvalidationReason),
    /// Source changes overlap independent workspace publication; reattachment
    /// is required to establish a new acknowledged base.
    Conflict,
    /// The returned generation is independent of this source.
    Sealed,
}

/// Terminal source reconciliation result.
pub enum ReconcileOutcome<A, O> {
    /// Source changes, if any, are durably represented by this generation.
    Clean(Generation<A, O>),
    /// Continuity is lost and an explicit full rescan is required.
    NeedsRescan(WatchInvalidationReason),
    /// Concurrent workspace changes overlap source capture; the source remains
    /// fail-closed until it is reattached.
    Conflict,
}

/// Fail-closed attached-source failure.
#[derive(Debug, Error)]
pub enum SourceError {
    /// Source configuration is empty or exceeds workspace bounds.
    #[error("source options are invalid")]
    InvalidOptions,
    /// Pinned sources do not admit automatic reconciliation.
    #[error("pinned source requires an explicit rescan")]
    Pinned,
    /// An existing durable source is bound to different semantics or identity.
    #[error("source binding does not match the durable workspace source")]
    BindingMismatch,
    /// Another process changed source ownership or state first.
    #[error("source state changed concurrently")]
    Concurrent,
    /// Source and workspace histories conflict; reattachment is required.
    #[error("source conflicts with the workspace and must be reattached")]
    Conflict,
    /// A retry identity is already bound to another source operation.
    #[error("source operation identity is already bound to another request")]
    IdempotencyConflict,
    /// Native watcher, capture, authority, or immutable storage failed.
    #[error("source operation failed: {0}")]
    Engine(String),
}

#[derive(Clone, Copy)]
enum SourceOperation {
    Reconcile,
    Rescan,
    Seal,
}

#[derive(Clone, Copy)]
enum SourceOperationStage {
    Begin,
    Terminal,
}

struct RecoveredSourceOperation {
    fact: SourceFact,
    head: Head,
}

struct SourceSession<A, O> {
    workspace: Workspace<A, O>,
    checkout: Checkout<A, O>,
    watcher: NativeWatch,
    capture: CaptureOptions,
    capture_policy: CapturePolicy,
    mode: SourceMode,
    maximum_queued_changes: u32,
    state: SourceState,
    authority_head: Head,
}

/// Cloneable handle to one exact attached native directory.
pub struct Source<A, O> {
    inner: Arc<Mutex<SourceSession<A, O>>>,
}

impl<A, O> Clone for Source<A, O> {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<A: AsyncAuthorityStore, O: AsyncObjectStore> Source<A, O> {
    /// Returns the current fail-closed semantic state.
    pub async fn state(&self) -> SourceState {
        self.inner.lock().await.state
    }

    /// Re-establishes a clean source baseline after the core materializer has
    /// installed a published workspace generation into the attached root.
    ///
    /// A fresh checkout is opened at authenticated workspace HEAD and a full
    /// bounded rescan proves the resulting host tree. Any concurrent host
    /// change is captured as a later generation instead of being discarded.
    pub async fn acknowledge_materialization(
        &self,
        key: IdempotencyKey,
    ) -> Result<ReconcileOutcome<A, O>, SourceError> {
        let mut session = self.inner.lock().await;
        refresh_source_authority(&mut session).await?;
        session.checkout = session
            .workspace
            .volume
            .checkout(
                GenerationSelector::Head,
                CheckoutMode::tracking_transaction(),
                WorkBudget::UNBOUNDED,
                &CancellationToken::new(),
            )
            .await
            .map_err(engine)?
            .value;
        session.state = SourceState::NeedsRescan(WatchInvalidationReason::InitialSnapshotRequired);
        begin_source_operation(&mut session, key, SourceOperation::Rescan).await?;
        rescan_session(
            &mut session,
            key,
            SourceOperation::Rescan,
            SourceState::Clean,
        )
        .await
    }

    /// Captures one bounded contiguous watcher interval and publishes it.
    /// A clean interval still advances authority ordering to atomically prove
    /// that its acknowledged workspace generation was current.
    ///
    /// # Errors
    ///
    /// Rejects pinned sources and propagates exact native/canonical failures.
    pub async fn reconcile(&self) -> Result<ReconcileOutcome<A, O>, SourceError> {
        self.reconcile_with_key(IdempotencyKey::new()).await
    }

    /// Captures and publishes one watcher interval under a stable retry key.
    ///
    /// An exact retry returns the original durable outcome, including after a
    /// process restart. Reusing the key for another lifecycle operation is an
    /// idempotency conflict.
    ///
    /// # Errors
    ///
    /// Rejects pinned sources, conflicting retry identities, and exact
    /// native/canonical failures.
    pub async fn reconcile_with_key(
        &self,
        key: IdempotencyKey,
    ) -> Result<ReconcileOutcome<A, O>, SourceError> {
        let mut session = self.inner.lock().await;
        if let Some(outcome) =
            replay_reconcile_operation(&mut session, key, SourceOperation::Reconcile).await?
        {
            return Ok(outcome);
        }
        if session.state == SourceState::Conflict {
            return Ok(ReconcileOutcome::Conflict);
        }
        if session.mode == SourceMode::Pinned {
            return Err(SourceError::Pinned);
        }
        begin_source_operation(&mut session, key, SourceOperation::Reconcile).await?;
        let maximum_paths = session.capture.maximum_paths;
        let batch = session
            .watcher
            .poll(
                maximum_paths,
                WorkBudget::UNBOUNDED,
                &CancellationToken::new(),
            )
            .map_err(engine)?
            .value;
        if let WatchBatch::RescanRequired { reason, .. } = batch {
            let fact = persist_source_operation(
                &mut session,
                SourceState::NeedsRescan(reason),
                key,
                SourceOperation::Reconcile,
            )
            .await?;
            return reconcile_outcome_from_fact(&session, fact);
        }
        let capture = session.capture.clone();
        let policy = session.capture_policy.clone();
        crate::capture_watch_batch_with_policy(
            &mut session.checkout,
            batch,
            &capture,
            &policy,
            WorkBudget::UNBOUNDED,
            &CancellationToken::new(),
        )
        .await
        .map_err(engine)?;
        publish_session(
            &mut session,
            key,
            SourceOperation::Reconcile,
            SourceState::Clean,
        )
        .await
    }

    /// Rebuilds one complete authenticated baseline while preserving events
    /// that arrive concurrently with the scan.
    ///
    /// # Errors
    ///
    /// Returns native, capture, authority, or storage failures without
    /// acknowledging an incomplete interval.
    pub async fn rescan(&self) -> Result<ReconcileOutcome<A, O>, SourceError> {
        self.rescan_with_key(IdempotencyKey::new()).await
    }

    /// Rebuilds a complete baseline under a stable retry key.
    ///
    /// # Errors
    ///
    /// Returns conflicting retry identities and exact native/canonical
    /// failures.
    pub async fn rescan_with_key(
        &self,
        key: IdempotencyKey,
    ) -> Result<ReconcileOutcome<A, O>, SourceError> {
        let mut session = self.inner.lock().await;
        if let Some(outcome) =
            replay_reconcile_operation(&mut session, key, SourceOperation::Rescan).await?
        {
            return Ok(outcome);
        }
        if session.state == SourceState::Conflict {
            return Ok(ReconcileOutcome::Conflict);
        }
        begin_source_operation(&mut session, key, SourceOperation::Rescan).await?;
        rescan_session(
            &mut session,
            key,
            SourceOperation::Rescan,
            SourceState::Clean,
        )
        .await
    }

    /// Produces an immutable generation whose bytes no longer depend on the
    /// attached directory.
    ///
    /// # Errors
    ///
    /// Fails unless a complete authenticated rescan and publication succeeds.
    pub async fn seal(&self) -> Result<Generation<A, O>, SourceError> {
        self.seal_with_key(IdempotencyKey::new()).await
    }

    /// Seals the source under a stable retry key.
    ///
    /// # Errors
    ///
    /// Returns conflicting retry identities and fails unless the original or
    /// recovered operation reached a clean sealed generation.
    pub async fn seal_with_key(
        &self,
        key: IdempotencyKey,
    ) -> Result<Generation<A, O>, SourceError> {
        let mut session = self.inner.lock().await;
        if let Some(generation) = replay_seal_operation(&mut session, key).await? {
            return Ok(generation);
        }
        if session.state == SourceState::Conflict {
            return Err(SourceError::Conflict);
        }
        begin_source_operation(&mut session, key, SourceOperation::Seal).await?;
        let generation = match rescan_session(
            &mut session,
            key,
            SourceOperation::Seal,
            SourceState::Sealed,
        )
        .await?
        {
            ReconcileOutcome::Clean(generation) => generation,
            ReconcileOutcome::Conflict => return Err(SourceError::Conflict),
            ReconcileOutcome::NeedsRescan(_) => {
                return Err(SourceError::Engine(
                    "source could not reach a clean sealed state".to_owned(),
                ));
            }
        };
        Ok(generation)
    }
}

async fn rescan_session<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
    key: IdempotencyKey,
    operation: SourceOperation,
    terminal_state: SourceState,
) -> Result<ReconcileOutcome<A, O>, SourceError> {
    let trailing = {
        let mut attempt = 0;
        loop {
            session.watcher.begin_rescan().map_err(engine)?;
            let policy = session.capture_policy.clone();
            let capture = crate::capture_baseline_with_policy(
                &mut session.checkout,
                &session.capture,
                &policy,
                WorkBudget::UNBOUNDED,
                &CancellationToken::new(),
            )
            .await;
            if let Err(error) = capture {
                let _ = session
                    .watcher
                    .abort_rescan(WatchInvalidationReason::BackendError);
                let _ = persist_session_state(
                    session,
                    SourceState::NeedsRescan(WatchInvalidationReason::BackendError),
                )
                .await;
                discard_unpublished_capture(session).await?;
                return Err(engine(error));
            }
            let batch = session.watcher.finish_rescan().map_err(engine)?;
            if matches!(
                batch,
                WatchBatch::RescanRequired {
                    reason: WatchInvalidationReason::NativeRescanRequired,
                    ..
                }
            ) && attempt < 3
            {
                // Native backends may deliver a coalesced hint from before
                // this scan after it completes. Never publish the partial
                // checkout; retry the baseline under the same operation key.
                discard_unpublished_capture(session).await?;
                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
                attempt += 1;
                continue;
            }
            break batch;
        }
    };
    if let WatchBatch::RescanRequired { reason, .. } = trailing {
        let fact =
            persist_source_operation(session, SourceState::NeedsRescan(reason), key, operation)
                .await?;
        discard_unpublished_capture(session).await?;
        return reconcile_outcome_from_fact(session, fact);
    }
    let capture = session.capture.clone();
    let policy = session.capture_policy.clone();
    crate::capture_watch_batch_with_policy(
        &mut session.checkout,
        trailing,
        &capture,
        &policy,
        WorkBudget::UNBOUNDED,
        &CancellationToken::new(),
    )
    .await
    .map_err(engine)?;
    publish_session(session, key, operation, terminal_state).await
}

async fn discard_unpublished_capture<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
) -> Result<(), SourceError> {
    let base = session.checkout.generation_id();
    session.checkout = session
        .workspace
        .volume
        .checkout(
            GenerationSelector::Exact(base),
            CheckoutMode::tracking_transaction(),
            WorkBudget::UNBOUNDED,
            &CancellationToken::new(),
        )
        .await
        .map_err(engine)?
        .value;
    Ok(())
}

async fn publish_session<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
    key: IdempotencyKey,
    operation: SourceOperation,
    terminal_state: SourceState,
) -> Result<ReconcileOutcome<A, O>, SourceError> {
    let had_pending_mutations = session.checkout.has_pending_mutations();
    let operation_id = source_volume_operation_id(key, operation);
    let operation_context = source_volume_operation_context(key, operation);
    let outcome = session
        .checkout
        .commit_with_context(
            operation_id,
            operation_context,
            WorkBudget::UNBOUNDED,
            &CancellationToken::new(),
        )
        .await
        .map_err(engine)?
        .value;
    match outcome {
        CheckoutCommitOutcome::Committed { generation_id, .. }
        | CheckoutCommitOutcome::AlreadyCommitted { generation_id, .. } => {
            persist_generation_outcome(session, terminal_state, generation_id, key, operation).await
        }
        CheckoutCommitOutcome::Conflict { .. } if !had_pending_mutations => {
            persist_state_outcome(session, SourceState::Conflict, key, operation).await
        }
        CheckoutCommitOutcome::Conflict { actual } => {
            if conflict_head_reuses_checkout_base(
                &session.workspace,
                session.checkout.generation_id(),
                actual,
            )
            .await?
            {
                return persist_state_outcome(session, SourceState::Conflict, key, operation).await;
            }
            let rebased = rebase_source_checkout(session).await?;
            if matches!(rebased, RebaseDecision::Conflicted { .. }) {
                return persist_state_outcome(session, SourceState::Conflict, key, operation).await;
            }
            let retried = session
                .checkout
                .commit_with_context(
                    operation_id,
                    operation_context,
                    WorkBudget::UNBOUNDED,
                    &CancellationToken::new(),
                )
                .await
                .map_err(engine)?
                .value;
            match retried {
                CheckoutCommitOutcome::Committed { generation_id, .. }
                | CheckoutCommitOutcome::AlreadyCommitted { generation_id, .. } => {
                    persist_generation_outcome(
                        session,
                        terminal_state,
                        generation_id,
                        key,
                        operation,
                    )
                    .await
                }
                CheckoutCommitOutcome::Conflict { .. } | CheckoutCommitOutcome::Fenced { .. } => {
                    persist_state_outcome(session, SourceState::Conflict, key, operation).await
                }
                CheckoutCommitOutcome::IdempotencyConflict { .. } => {
                    Err(SourceError::IdempotencyConflict)
                }
            }
        }
        CheckoutCommitOutcome::Fenced { .. } => {
            persist_state_outcome(session, SourceState::Conflict, key, operation).await
        }
        CheckoutCommitOutcome::IdempotencyConflict { .. } => Err(SourceError::IdempotencyConflict),
    }
}

async fn conflict_head_reuses_checkout_base<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    workspace: &Workspace<A, O>,
    checkout_generation: crate::GenerationId,
    actual: Head,
) -> Result<bool, SourceError> {
    let previous_sequence = actual.sequence.get().checked_sub(1).ok_or_else(|| {
        SourceError::Engine("conflicting volume head has no durable record".to_owned())
    })?;
    let records = workspace
        .volume
        .fs
        .authority()
        .replay(
            volume_authority_id(workspace.volume.id()),
            Sequence::new(previous_sequence),
            ReplayLimit {
                records: 1,
                payload_bytes: 4096,
            },
            WorkBudget::UNBOUNDED,
            &CancellationToken::new(),
        )
        .await
        .map_err(engine)?
        .value;
    let record = records.first().ok_or_else(|| {
        SourceError::Engine("conflicting volume head has no durable record".to_owned())
    })?;
    if record.epoch != actual.epoch
        || record.sequence != actual.sequence
        || record.digest != actual.digest
    {
        return Err(SourceError::Engine(
            "conflicting volume head does not match durable history".to_owned(),
        ));
    }
    let published = decode_published_generation(&record.payload, 4096).map_err(engine)?;
    if published.volume_id != workspace.volume.id() {
        return Err(SourceError::Engine(
            "conflicting volume publication belongs to another volume".to_owned(),
        ));
    }
    Ok(published.generation_root.digest == checkout_generation.digest())
}

async fn rebase_source_checkout<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
) -> Result<RebaseDecision, SourceError> {
    session
        .checkout
        .rebase_head(
            session
                .workspace
                .volume
                .config()
                .limits
                .maximum_checkout_dependencies,
            WorkBudget::UNBOUNDED,
            &CancellationToken::new(),
        )
        .await
        .map(|receipt| receipt.value)
        .map_err(engine)
}

async fn persist_generation_outcome<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
    state: SourceState,
    generation_id: crate::GenerationId,
    key: IdempotencyKey,
    operation: SourceOperation,
) -> Result<ReconcileOutcome<A, O>, SourceError> {
    let fact =
        persist_source_operation_with_generation(session, state, generation_id, key, operation)
            .await?;
    reconcile_outcome_from_fact(session, fact)
}

async fn persist_state_outcome<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
    state: SourceState,
    key: IdempotencyKey,
    operation: SourceOperation,
) -> Result<ReconcileOutcome<A, O>, SourceError> {
    let fact = persist_source_operation(session, state, key, operation).await?;
    reconcile_outcome_from_fact(session, fact)
}

fn reconcile_outcome_from_fact<A, O>(
    session: &SourceSession<A, O>,
    fact: SourceFact,
) -> Result<ReconcileOutcome<A, O>, SourceError> {
    match fact.state {
        DurableSourceState::Clean | DurableSourceState::Sealed => {
            Ok(ReconcileOutcome::Clean(Generation {
                workspace: session.workspace.clone(),
                id: fact.generation_id,
            }))
        }
        DurableSourceState::NeedsRescan(reason) => {
            Ok(ReconcileOutcome::NeedsRescan(watch_invalidation(reason)))
        }
        DurableSourceState::Conflict => Ok(ReconcileOutcome::Conflict),
        DurableSourceState::PendingCapture => Err(SourceError::Engine(
            "source operation has no terminal outcome".to_owned(),
        )),
    }
}

impl<A: AsyncAuthorityStore, O: AsyncObjectStore> Fs<A, O> {
    /// Creates or opens one workspace and attaches an exact native directory.
    ///
    /// # Errors
    ///
    /// Rejects invalid bounds, unsafe roots, unsupported host semantics, or a
    /// baseline that cannot be atomically authenticated and published.
    pub async fn attach_directory(
        &self,
        name: impl AsRef<str>,
        path: impl AsRef<Path>,
        options: SourceOptions,
    ) -> Result<Workspace<A, O>, SourceError> {
        if options.maximum_paths == 0
            || options.maximum_extent_spans == 0
            || options.maximum_queued_changes == 0
        {
            return Err(SourceError::InvalidOptions);
        }
        let workspace = self.create_workspace(name).await.map_err(engine)?;
        let watcher = NativeWatch::open_with_profile(
            path.as_ref(),
            workspace.volume.config().profile,
            NativeWatchOptions {
                limits: workspace.volume.config().limits,
                maximum_queued_changes: options.maximum_queued_changes,
                recursive: true,
            },
        )
        .map_err(engine)?;
        let capture = CaptureOptions {
            source_root: PathBuf::from(path.as_ref()),
            expected_root_identity: watcher.root_identity(),
            maximum_paths: options.maximum_paths,
            maximum_extent_spans: options.maximum_extent_spans,
        };
        let capture_policy = CapturePolicy::excluding(
            options
                .excluded_paths
                .iter()
                .map(|path| {
                    crate::kernel::NamespacePath::from_portable_in_profile(
                        path,
                        workspace.volume.config().profile,
                        workspace.volume.config().limits,
                    )
                    .map_err(engine)
                })
                .collect::<Result<Vec<_>, _>>()?,
        )
        .map_err(engine)?;
        let generation = workspace.head().await.map_err(engine)?;
        let authority_head = attach_source_authority(
            &workspace,
            watcher.root_identity(),
            &options,
            capture_policy.fingerprint(),
            generation.id,
        )
        .await?;
        let checkout = workspace
            .volume
            .checkout(
                GenerationSelector::Head,
                CheckoutMode::tracking_transaction(),
                WorkBudget::UNBOUNDED,
                &CancellationToken::new(),
            )
            .await
            .map_err(engine)?
            .value;
        let source = Source {
            inner: Arc::new(Mutex::new(SourceSession {
                workspace: workspace.clone(),
                checkout,
                watcher,
                capture,
                capture_policy,
                mode: options.mode,
                maximum_queued_changes: options.maximum_queued_changes,
                state: SourceState::NeedsRescan(WatchInvalidationReason::InitialSnapshotRequired),
                authority_head,
            })),
        };
        if !matches!(source.rescan().await?, ReconcileOutcome::Clean(_)) {
            return Err(SourceError::Engine(
                "initial source baseline did not become clean".to_owned(),
            ));
        }
        Ok(Workspace {
            source: Some(source),
            ..workspace
        })
    }
}

async fn attach_source_authority<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    workspace: &Workspace<A, O>,
    root_identity: crate::NativeRootIdentity,
    options: &SourceOptions,
    capture_policy: Digest,
    generation_id: crate::GenerationId,
) -> Result<Head, SourceError> {
    let authority_id = source_authority_id(workspace.volume.id());
    let created = workspace
        .volume
        .fs
        .authority()
        .create_authority(
            authority_id,
            Epoch::GENESIS,
            WorkBudget::UNBOUNDED,
            &CancellationToken::new(),
        )
        .await
        .map_err(engine)?
        .value;
    let head = match created {
        CreateAuthorityOutcome::Created(head) | CreateAuthorityOutcome::Existing(head) => head,
    };
    if head.sequence != Sequence::GENESIS {
        let latest = replay_source_fact(workspace, head).await?;
        if latest.volume_id != workspace.volume.id()
            || latest.root_identity != root_identity.to_bytes()
            || latest.mode != durable_mode(options.mode)
            || latest.maximum_paths != options.maximum_paths
            || latest.maximum_extent_spans != options.maximum_extent_spans
            || latest.maximum_queued_changes != options.maximum_queued_changes
            || (latest.schema_version == 1 && !options.excluded_paths.is_empty())
            || (latest.schema_version >= 2 && latest.capture_policy != capture_policy)
        {
            return Err(SourceError::BindingMismatch);
        }
    }
    append_source_fact(
        workspace,
        head,
        SourceFact {
            schema_version: 2,
            volume_id: workspace.volume.id(),
            root_identity: root_identity.to_bytes(),
            mode: durable_mode(options.mode),
            maximum_paths: options.maximum_paths,
            maximum_extent_spans: options.maximum_extent_spans,
            maximum_queued_changes: options.maximum_queued_changes,
            capture_policy,
            state: DurableSourceState::NeedsRescan(SourceInvalidation::InitialSnapshotRequired),
            generation_id,
        },
    )
    .await
}

async fn replay_source_fact<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    workspace: &Workspace<A, O>,
    head: Head,
) -> Result<SourceFact, SourceError> {
    let after = Sequence::new(head.sequence.get().saturating_sub(1));
    let records = workspace
        .volume
        .fs
        .authority()
        .replay(
            source_authority_id(workspace.volume.id()),
            after,
            ReplayLimit {
                records: 1,
                payload_bytes: 4096,
            },
            WorkBudget::UNBOUNDED,
            &CancellationToken::new(),
        )
        .await
        .map_err(engine)?
        .value;
    let record = records.first().ok_or_else(|| {
        SourceError::Engine("source authority head has no terminal fact".to_owned())
    })?;
    decode_source_fact(&record.payload, 4096).map_err(engine)
}

async fn refresh_source_authority<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
) -> Result<(), SourceError> {
    let head = session
        .workspace
        .volume
        .fs
        .authority()
        .head(
            source_authority_id(session.workspace.volume.id()),
            WorkBudget::UNBOUNDED,
            &CancellationToken::new(),
        )
        .await
        .map_err(engine)?
        .value;
    if head == session.authority_head {
        return Ok(());
    }
    let fact = replay_source_fact(&session.workspace, head).await?;
    validate_source_fact_binding(session, &fact)?;
    session.authority_head = head;
    let state = source_state(fact.state);
    session.state = if fact.generation_id == session.checkout.generation_id() {
        state
    } else {
        SourceState::Conflict
    };
    Ok(())
}

async fn recover_published_operation<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
    state: SourceState,
    generation_id: crate::GenerationId,
    begin_head: Head,
    key: IdempotencyKey,
    operation: SourceOperation,
) -> Result<SourceFact, SourceError> {
    refresh_source_authority(session).await?;
    let operation_still_current = (session.state == SourceState::PendingCapture
        && session.authority_head == begin_head)
        || (session.state == SourceState::Clean
            && session.checkout.generation_id() == generation_id);
    let recovered_state = if operation_still_current {
        state
    } else {
        SourceState::Conflict
    };
    persist_source_operation_with_generation(
        session,
        recovered_state,
        generation_id,
        key,
        operation,
    )
    .await
}

async fn replay_reconcile_operation<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
    key: IdempotencyKey,
    operation: SourceOperation,
) -> Result<Option<ReconcileOutcome<A, O>>, SourceError> {
    let fact = if let Some(recovered) =
        find_source_operation(session, key, operation, SourceOperationStage::Terminal).await?
    {
        let fact = recovered.fact;
        refresh_source_authority(session).await?;
        fact
    } else {
        let Some(begin) =
            find_source_operation(session, key, operation, SourceOperationStage::Begin).await?
        else {
            if published_generation_for_key(session, key, operation)
                .await?
                .is_some()
            {
                return Err(SourceError::IdempotencyConflict);
            }
            return Ok(None);
        };
        let Some(generation_id) = published_generation_for_key(session, key, operation).await?
        else {
            return Ok(None);
        };
        recover_published_operation(
            session,
            SourceState::Clean,
            generation_id,
            begin.head,
            key,
            operation,
        )
        .await?
    };
    let outcome = match fact.state {
        DurableSourceState::Clean => ReconcileOutcome::Clean(Generation {
            workspace: session.workspace.clone(),
            id: fact.generation_id,
        }),
        DurableSourceState::NeedsRescan(reason) => {
            ReconcileOutcome::NeedsRescan(watch_invalidation(reason))
        }
        DurableSourceState::Conflict => ReconcileOutcome::Conflict,
        DurableSourceState::PendingCapture | DurableSourceState::Sealed => {
            return Err(SourceError::Engine(
                "durable source operation has an invalid terminal state".to_owned(),
            ));
        }
    };
    Ok(Some(outcome))
}

async fn replay_seal_operation<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
    key: IdempotencyKey,
) -> Result<Option<Generation<A, O>>, SourceError> {
    let fact = if let Some(recovered) = find_source_operation(
        session,
        key,
        SourceOperation::Seal,
        SourceOperationStage::Terminal,
    )
    .await?
    {
        let fact = recovered.fact;
        refresh_source_authority(session).await?;
        fact
    } else {
        let Some(begin) = find_source_operation(
            session,
            key,
            SourceOperation::Seal,
            SourceOperationStage::Begin,
        )
        .await?
        else {
            if published_generation_for_key(session, key, SourceOperation::Seal)
                .await?
                .is_some()
            {
                return Err(SourceError::IdempotencyConflict);
            }
            return Ok(None);
        };
        let Some(generation_id) =
            published_generation_for_key(session, key, SourceOperation::Seal).await?
        else {
            return Ok(None);
        };
        recover_published_operation(
            session,
            SourceState::Sealed,
            generation_id,
            begin.head,
            key,
            SourceOperation::Seal,
        )
        .await?
    };
    match fact.state {
        DurableSourceState::Sealed => Ok(Some(Generation {
            workspace: session.workspace.clone(),
            id: fact.generation_id,
        })),
        DurableSourceState::Conflict => Err(SourceError::Conflict),
        DurableSourceState::NeedsRescan(_) => Err(SourceError::Engine(
            "source could not reach a clean sealed state".to_owned(),
        )),
        DurableSourceState::Clean | DurableSourceState::PendingCapture => Err(SourceError::Engine(
            "durable seal operation has an invalid terminal state".to_owned(),
        )),
    }
}

async fn find_source_operation<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
    key: IdempotencyKey,
    operation: SourceOperation,
    stage: SourceOperationStage,
) -> Result<Option<RecoveredSourceOperation>, SourceError> {
    let authority_id = source_authority_id(session.workspace.volume.id());
    let recovered = session
        .workspace
        .volume
        .fs
        .authority()
        .find_operation(
            authority_id,
            source_stage_operation_id(key, stage),
            WorkBudget::UNBOUNDED,
            &CancellationToken::new(),
        )
        .await
        .map_err(engine)?
        .value;
    let Some(commit) = recovered else {
        return Ok(None);
    };
    let fact = decode_source_fact(&commit.payload, 4096).map_err(engine)?;
    if commit.fingerprint != source_operation_fingerprint(operation, &fact)? {
        return Err(SourceError::IdempotencyConflict);
    }
    validate_source_fact_binding(session, &fact)?;
    let head = Head {
        epoch: commit.epoch,
        sequence: commit.sequence,
        digest: commit.digest,
    };
    if head.epoch == session.authority_head.epoch
        && head.sequence >= session.authority_head.sequence
    {
        session.authority_head = head;
        session.state = source_state(fact.state);
    }
    Ok(Some(RecoveredSourceOperation { fact, head }))
}

fn validate_source_fact_binding<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &SourceSession<A, O>,
    fact: &SourceFact,
) -> Result<(), SourceError> {
    if fact.volume_id != session.workspace.volume.id()
        || fact.root_identity != session.watcher.root_identity().to_bytes()
        || fact.mode != durable_mode(session.mode)
        || fact.maximum_paths != session.capture.maximum_paths
        || fact.maximum_extent_spans != session.capture.maximum_extent_spans
        || fact.maximum_queued_changes != session.maximum_queued_changes
        || (fact.schema_version == 1 && session.capture_policy != CapturePolicy::allow_all())
        || (fact.schema_version >= 2 && fact.capture_policy != session.capture_policy.fingerprint())
    {
        return Err(SourceError::BindingMismatch);
    }
    Ok(())
}

async fn published_generation_for_key<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
    key: IdempotencyKey,
    operation: SourceOperation,
) -> Result<Option<crate::GenerationId>, SourceError> {
    let receipt = session
        .workspace
        .volume
        .fs
        .observe_volume_operation(
            session.workspace.volume.id(),
            source_volume_operation_id(key, operation),
            WorkBudget::UNBOUNDED,
            &CancellationToken::new(),
        )
        .await
        .map_err(engine)?;
    let Some(commit) = receipt.value else {
        return Ok(None);
    };
    let published = decode_published_generation(&commit.payload, 4096).map_err(engine)?;
    if published.volume_id != session.workspace.volume.id() {
        return Err(SourceError::IdempotencyConflict);
    }
    let Some(previous_sequence) = commit.sequence.get().checked_sub(1) else {
        return Err(SourceError::IdempotencyConflict);
    };
    let expected = Head {
        epoch: commit.epoch,
        sequence: Sequence::new(previous_sequence),
        digest: commit.previous_digest,
    };
    let request = PublishGenerationRequest {
        authority_id: volume_authority_id(session.workspace.volume.id()),
        volume_id: session.workspace.volume.id(),
        epoch: commit.epoch,
        expected,
        operation_id: source_volume_operation_id(key, operation),
        generation_root: published.generation_root,
    };
    if commit.fingerprint
        != contextual_publication_fingerprint(
            request,
            source_volume_operation_context(key, operation),
        )
    {
        return Err(SourceError::IdempotencyConflict);
    }
    Ok(Some(crate::GenerationId::new(
        published.generation_root.digest,
    )))
}

async fn begin_source_operation<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
    key: IdempotencyKey,
    operation: SourceOperation,
) -> Result<(), SourceError> {
    if find_source_operation(session, key, operation, SourceOperationStage::Begin)
        .await?
        .is_some()
    {
        return Ok(());
    }
    if published_generation_for_key(session, key, operation)
        .await?
        .is_some()
    {
        return Err(SourceError::IdempotencyConflict);
    }
    let fact = source_fact(
        session,
        SourceState::PendingCapture,
        session.checkout.generation_id(),
    );
    let fingerprint = source_operation_fingerprint(operation, &fact)?;
    session.authority_head = append_source_fact_with_identity(
        &session.workspace,
        session.authority_head,
        fact,
        source_stage_operation_id(key, SourceOperationStage::Begin),
        fingerprint,
    )
    .await?;
    session.state = SourceState::PendingCapture;
    Ok(())
}

async fn persist_session_state<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
    state: SourceState,
) -> Result<(), SourceError> {
    let generation_id = session.checkout.generation_id();
    persist_source_fact(session, state, generation_id).await
}

async fn persist_source_operation<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
    state: SourceState,
    key: IdempotencyKey,
    operation: SourceOperation,
) -> Result<SourceFact, SourceError> {
    let generation_id = session.checkout.generation_id();
    persist_source_operation_with_generation(session, state, generation_id, key, operation).await
}

async fn persist_source_operation_with_generation<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
    state: SourceState,
    generation_id: crate::GenerationId,
    key: IdempotencyKey,
    operation: SourceOperation,
) -> Result<SourceFact, SourceError> {
    let fact = source_fact(session, state, generation_id);
    let fingerprint = source_operation_fingerprint(operation, &fact)?;
    let appended = append_source_fact_with_identity(
        &session.workspace,
        session.authority_head,
        fact,
        source_stage_operation_id(key, SourceOperationStage::Terminal),
        fingerprint,
    )
    .await;
    match appended {
        Ok(head) => {
            session.authority_head = head;
            session.state = state;
            Ok(fact)
        }
        Err(SourceError::IdempotencyConflict) => {
            let recovered =
                find_source_operation(session, key, operation, SourceOperationStage::Terminal)
                    .await?
                    .ok_or(SourceError::IdempotencyConflict)?;
            Ok(recovered.fact)
        }
        Err(error) => Err(error),
    }
}

async fn persist_source_fact<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &mut SourceSession<A, O>,
    state: SourceState,
    generation_id: crate::GenerationId,
) -> Result<(), SourceError> {
    let fact = source_fact(session, state, generation_id);
    session.authority_head =
        append_source_fact(&session.workspace, session.authority_head, fact).await?;
    session.state = state;
    Ok(())
}

fn source_fact<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    session: &SourceSession<A, O>,
    state: SourceState,
    generation_id: crate::GenerationId,
) -> SourceFact {
    SourceFact {
        schema_version: 2,
        volume_id: session.workspace.volume.id(),
        root_identity: session.watcher.root_identity().to_bytes(),
        mode: durable_mode(session.mode),
        maximum_paths: session.capture.maximum_paths,
        maximum_extent_spans: session.capture.maximum_extent_spans,
        maximum_queued_changes: session.maximum_queued_changes,
        capture_policy: session.capture_policy.fingerprint(),
        state: durable_state(state),
        generation_id,
    }
}

async fn append_source_fact<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    workspace: &Workspace<A, O>,
    expected: Head,
    fact: SourceFact,
) -> Result<Head, SourceError> {
    let authority_id = source_authority_id(workspace.volume.id());
    let payload = encode_source_fact(fact).map_err(engine)?;
    let mut fingerprint_hasher = blake3::Hasher::new();
    fingerprint_hasher.update(b"acyclic-fs-source-fingerprint-v1\0");
    fingerprint_hasher.update(&payload);
    let fingerprint = Digest::from_bytes(*fingerprint_hasher.finalize().as_bytes());
    let mut operation_hasher = blake3::Hasher::new();
    operation_hasher.update(b"acyclic-fs-source-operation-v1\0");
    operation_hasher.update(&authority_id.into_bytes());
    operation_hasher.update(&expected.epoch.get().to_le_bytes());
    operation_hasher.update(&expected.sequence.get().to_le_bytes());
    operation_hasher.update(expected.digest.as_bytes());
    operation_hasher.update(fingerprint.as_bytes());
    let mut operation_bytes = [0_u8; 16];
    operation_bytes.copy_from_slice(&operation_hasher.finalize().as_bytes()[..16]);
    append_source_fact_with_identity(
        workspace,
        expected,
        fact,
        OperationId::from_bytes(operation_bytes),
        fingerprint,
    )
    .await
}

async fn append_source_fact_with_identity<A: AsyncAuthorityStore, O: AsyncObjectStore>(
    workspace: &Workspace<A, O>,
    expected: Head,
    fact: SourceFact,
    operation_id: OperationId,
    fingerprint: Digest,
) -> Result<Head, SourceError> {
    let authority_id = source_authority_id(workspace.volume.id());
    let payload = encode_source_fact(fact).map_err(engine)?;
    let outcome = workspace
        .volume
        .fs
        .authority()
        .compare_and_append(
            authority_id,
            expected.epoch,
            expected,
            ProposedCommit {
                operation_id,
                fingerprint,
                payload: Bytes::from(payload),
            },
            WorkBudget::UNBOUNDED,
            &CancellationToken::new(),
        )
        .await
        .map_err(engine)?
        .value;
    match outcome {
        AppendOutcome::Committed(commit) | AppendOutcome::AlreadyCommitted(commit) => Ok(Head {
            epoch: commit.epoch,
            sequence: commit.sequence,
            digest: commit.digest,
        }),
        AppendOutcome::Conflict { .. } | AppendOutcome::Fenced { .. } => {
            Err(SourceError::Concurrent)
        }
        AppendOutcome::IdempotencyConflict { .. } => Err(SourceError::IdempotencyConflict),
    }
}

fn source_operation_fingerprint(
    operation: SourceOperation,
    fact: &SourceFact,
) -> Result<Digest, SourceError> {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"acyclic-fs-source-command-v1\0");
    hasher.update(&[match operation {
        SourceOperation::Reconcile => 1,
        SourceOperation::Rescan => 2,
        SourceOperation::Seal => 3,
    }]);
    hasher.update(&encode_source_fact(*fact).map_err(engine)?);
    Ok(Digest::from_bytes(*hasher.finalize().as_bytes()))
}

fn source_stage_operation_id(key: IdempotencyKey, stage: SourceOperationStage) -> OperationId {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"acyclic-fs-source-stage-v1\0");
    hasher.update(&key.into_bytes());
    hasher.update(&[match stage {
        SourceOperationStage::Begin => 1,
        SourceOperationStage::Terminal => 2,
    }]);
    let mut bytes = [0_u8; 16];
    bytes.copy_from_slice(&hasher.finalize().as_bytes()[..16]);
    OperationId::from_bytes(bytes)
}

fn source_volume_operation_id(key: IdempotencyKey, operation: SourceOperation) -> OperationId {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"acyclic-fs-source-volume-publication-v1\0");
    hasher.update(&key.into_bytes());
    hasher.update(&[match operation {
        SourceOperation::Reconcile => 1,
        SourceOperation::Rescan => 2,
        SourceOperation::Seal => 3,
    }]);
    let mut bytes = [0_u8; 16];
    bytes.copy_from_slice(&hasher.finalize().as_bytes()[..16]);
    OperationId::from_bytes(bytes)
}

fn source_volume_operation_context(key: IdempotencyKey, operation: SourceOperation) -> Digest {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"acyclic-fs-source-volume-context-v1\0");
    hasher.update(&key.into_bytes());
    hasher.update(&[match operation {
        SourceOperation::Reconcile => 1,
        SourceOperation::Rescan => 2,
        SourceOperation::Seal => 3,
    }]);
    Digest::from_bytes(*hasher.finalize().as_bytes())
}

const fn durable_mode(mode: SourceMode) -> DurableSourceMode {
    match mode {
        SourceMode::Pinned => DurableSourceMode::Pinned,
        SourceMode::Tracking => DurableSourceMode::Tracking,
    }
}

const fn durable_state(state: SourceState) -> DurableSourceState {
    match state {
        SourceState::Clean => DurableSourceState::Clean,
        SourceState::PendingCapture => DurableSourceState::PendingCapture,
        SourceState::NeedsRescan(reason) => DurableSourceState::NeedsRescan(match reason {
            WatchInvalidationReason::InitialSnapshotRequired => {
                SourceInvalidation::InitialSnapshotRequired
            }
            WatchInvalidationReason::QueueOverflow => SourceInvalidation::QueueOverflow,
            WatchInvalidationReason::NativeRescanRequired => {
                SourceInvalidation::NativeRescanRequired
            }
            WatchInvalidationReason::BackendError => SourceInvalidation::BackendError,
            WatchInvalidationReason::UnrepresentablePath => SourceInvalidation::UnrepresentablePath,
            WatchInvalidationReason::AmbiguousRename => SourceInvalidation::AmbiguousRename,
            WatchInvalidationReason::RootChanged => SourceInvalidation::RootChanged,
        }),
        SourceState::Conflict => DurableSourceState::Conflict,
        SourceState::Sealed => DurableSourceState::Sealed,
    }
}

const fn source_state(state: DurableSourceState) -> SourceState {
    match state {
        DurableSourceState::Clean => SourceState::Clean,
        DurableSourceState::PendingCapture => SourceState::PendingCapture,
        DurableSourceState::NeedsRescan(reason) => {
            SourceState::NeedsRescan(watch_invalidation(reason))
        }
        DurableSourceState::Conflict => SourceState::Conflict,
        DurableSourceState::Sealed => SourceState::Sealed,
    }
}

const fn watch_invalidation(reason: SourceInvalidation) -> WatchInvalidationReason {
    match reason {
        SourceInvalidation::InitialSnapshotRequired => {
            WatchInvalidationReason::InitialSnapshotRequired
        }
        SourceInvalidation::QueueOverflow => WatchInvalidationReason::QueueOverflow,
        SourceInvalidation::NativeRescanRequired => WatchInvalidationReason::NativeRescanRequired,
        SourceInvalidation::BackendError => WatchInvalidationReason::BackendError,
        SourceInvalidation::UnrepresentablePath => WatchInvalidationReason::UnrepresentablePath,
        SourceInvalidation::AmbiguousRename => WatchInvalidationReason::AmbiguousRename,
        SourceInvalidation::RootChanged => WatchInvalidationReason::RootChanged,
    }
}

fn engine(error: impl std::fmt::Display) -> SourceError {
    SourceError::Engine(error.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use bytes::Bytes;
    use std::sync::atomic::{AtomicU8, Ordering};

    #[derive(Clone, Copy, Eq, PartialEq)]
    enum AppendGatePhase {
        Before = 1,
        After = 2,
    }

    struct AppendGate {
        target: std::sync::Mutex<Option<OperationId>>,
        phase: AtomicU8,
        arrived: tokio::sync::watch::Sender<usize>,
        open: tokio::sync::watch::Sender<bool>,
    }

    impl AppendGate {
        fn new() -> Self {
            let (arrived, _) = tokio::sync::watch::channel(0);
            let (open, _) = tokio::sync::watch::channel(true);
            Self {
                target: std::sync::Mutex::new(None),
                phase: AtomicU8::new(0),
                arrived,
                open,
            }
        }

        fn arm(&self, target: OperationId, phase: AppendGatePhase) {
            let mut configured = match self.target.lock() {
                Ok(configured) => configured,
                Err(poisoned) => poisoned.into_inner(),
            };
            *configured = Some(target);
            self.phase.store(phase as u8, Ordering::Release);
            self.arrived.send_replace(0);
            self.open.send_replace(false);
        }

        fn matches(&self, operation_id: OperationId, phase: AppendGatePhase) -> bool {
            let target = match self.target.lock() {
                Ok(target) => target,
                Err(poisoned) => poisoned.into_inner(),
            };
            !*self.open.borrow()
                && self.phase.load(Ordering::Acquire) == phase as u8
                && *target == Some(operation_id)
        }

        async fn wait(&self) {
            let mut open = self.open.subscribe();
            self.arrived.send_modify(|arrived| *arrived += 1);
            while !*open.borrow_and_update() {
                if open.changed().await.is_err() {
                    return;
                }
            }
        }

        async fn wait_for_arrivals(&self, expected: usize) {
            let mut arrived = self.arrived.subscribe();
            while *arrived.borrow_and_update() < expected {
                if arrived.changed().await.is_err() {
                    return;
                }
            }
        }

        fn release(&self) {
            self.open.send_replace(true);
        }
    }

    #[derive(Clone)]
    struct GatedAuthorityStore {
        inner: Arc<crate::memory::MemoryAuthorityStore>,
        gate: Arc<AppendGate>,
    }

    impl AsyncAuthorityStore for GatedAuthorityStore {
        async fn fork_generation_authority(
            &self,
            source: crate::GenerationForkSource,
            destination_authority: crate::foundation::AuthorityId,
            operation_id: crate::foundation::OperationId,
            budget: WorkBudget,
            cancellation: &CancellationToken,
        ) -> crate::AuthorityResult<CreateAuthorityOutcome> {
            self.inner
                .fork_generation_authority(
                    source,
                    destination_authority,
                    operation_id,
                    budget,
                    cancellation,
                )
                .await
        }

        async fn create_authority(
            &self,
            authority_id: crate::foundation::AuthorityId,
            genesis_epoch: Epoch,
            budget: WorkBudget,
            cancellation: &CancellationToken,
        ) -> crate::AuthorityResult<CreateAuthorityOutcome> {
            self.inner
                .create_authority(authority_id, genesis_epoch, budget, cancellation)
                .await
        }

        async fn head(
            &self,
            authority_id: crate::foundation::AuthorityId,
            budget: WorkBudget,
            cancellation: &CancellationToken,
        ) -> crate::AuthorityResult<Head> {
            self.inner.head(authority_id, budget, cancellation).await
        }

        async fn compare_and_append(
            &self,
            authority_id: crate::foundation::AuthorityId,
            epoch: Epoch,
            expected: Head,
            commit: ProposedCommit,
            budget: WorkBudget,
            cancellation: &CancellationToken,
        ) -> crate::AuthorityResult<AppendOutcome> {
            if self
                .gate
                .matches(commit.operation_id, AppendGatePhase::Before)
            {
                self.gate.wait().await;
            }
            let operation_id = commit.operation_id;
            let result = self
                .inner
                .compare_and_append(authority_id, epoch, expected, commit, budget, cancellation)
                .await;
            if self.gate.matches(operation_id, AppendGatePhase::After) {
                self.gate.wait().await;
            }
            result
        }

        async fn replay(
            &self,
            authority_id: crate::foundation::AuthorityId,
            after: Sequence,
            limit: ReplayLimit,
            budget: WorkBudget,
            cancellation: &CancellationToken,
        ) -> crate::AuthorityResult<Vec<crate::foundation::DurableCommit>> {
            self.inner
                .replay(authority_id, after, limit, budget, cancellation)
                .await
        }

        async fn fence(
            &self,
            authority_id: crate::foundation::AuthorityId,
            expected: Head,
            budget: WorkBudget,
            cancellation: &CancellationToken,
        ) -> crate::AuthorityResult<crate::FenceOutcome> {
            self.inner
                .fence(authority_id, expected, budget, cancellation)
                .await
        }

        async fn find_operation(
            &self,
            authority_id: crate::foundation::AuthorityId,
            operation_id: OperationId,
            budget: WorkBudget,
            cancellation: &CancellationToken,
        ) -> crate::AuthorityResult<Option<crate::foundation::DurableCommit>> {
            self.inner
                .find_operation(authority_id, operation_id, budget, cancellation)
                .await
        }
    }

    fn next_authority_append<A, O>(
        simulation: &crate::Simulation<A, O>,
    ) -> Result<u64, crate::SimulationError> {
        Ok(simulation
            .trace()?
            .iter()
            .filter(|entry| entry.operation == crate::SimulationOperation::AuthorityAppend)
            .map(|entry| entry.occurrence)
            .max()
            .unwrap_or(0)
            .saturating_add(1))
    }

    fn clean_generation<A, O>(
        outcome: ReconcileOutcome<A, O>,
    ) -> Result<Generation<A, O>, &'static str> {
        match outcome {
            ReconcileOutcome::Clean(generation) => Ok(generation),
            ReconcileOutcome::NeedsRescan(_) | ReconcileOutcome::Conflict => {
                Err("source did not become clean")
            }
        }
    }

    async fn publish_without_terminal<A: AsyncAuthorityStore, O: AsyncObjectStore>(
        source: &Source<A, O>,
        key: IdempotencyKey,
        operation: SourceOperation,
    ) -> Result<crate::GenerationId, Box<dyn std::error::Error>> {
        let mut session = source.inner.lock().await;
        begin_source_operation(&mut session, key, operation).await?;
        session.watcher.begin_rescan()?;
        let capture = session.capture.clone();
        let policy = session.capture_policy.clone();
        crate::capture_baseline_with_policy(
            &mut session.checkout,
            &capture,
            &policy,
            WorkBudget::UNBOUNDED,
            &CancellationToken::new(),
        )
        .await?;
        let trailing = session.watcher.finish_rescan()?;
        crate::capture_watch_batch_with_policy(
            &mut session.checkout,
            trailing,
            &capture,
            &policy,
            WorkBudget::UNBOUNDED,
            &CancellationToken::new(),
        )
        .await?;
        match session
            .checkout
            .commit_with_context(
                source_volume_operation_id(key, operation),
                source_volume_operation_context(key, operation),
                WorkBudget::UNBOUNDED,
                &CancellationToken::new(),
            )
            .await?
            .value
        {
            CheckoutCommitOutcome::Committed { generation_id, .. }
            | CheckoutCommitOutcome::AlreadyCommitted { generation_id, .. } => Ok(generation_id),
            _ => Err("source publication did not commit".into()),
        }
    }

    #[tokio::test]
    async fn attached_directory_rescans_and_seals_through_one_workspace()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        std::fs::write(root.path().join("before.txt"), b"before")?;
        let workspace =
            Box::pin(Fs::memory().attach_directory("repo", root.path(), SourceOptions::default()))
                .await?;
        assert_eq!(
            workspace.read("/before.txt", 16).await?,
            Bytes::from_static(b"before")
        );
        let source = workspace.source().ok_or("source handle missing")?;
        assert_eq!(source.state().await, SourceState::Clean);

        std::fs::write(root.path().join("before.txt"), b"after")?;
        std::fs::write(root.path().join("added.txt"), b"added")?;
        assert!(matches!(
            Box::pin(source.rescan()).await?,
            ReconcileOutcome::Clean(_)
        ));
        assert_eq!(
            workspace.read("/before.txt", 16).await?,
            Bytes::from_static(b"after")
        );
        assert_eq!(
            workspace.read("/added.txt", 16).await?,
            Bytes::from_static(b"added")
        );
        let sealed = Box::pin(workspace.seal()).await?;
        assert_eq!(source.state().await, SourceState::Sealed);
        std::fs::remove_dir_all(root.path())?;
        assert_eq!(
            sealed.read("/before.txt", 16).await?,
            Bytes::from_static(b"after")
        );
        Ok(())
    }

    #[tokio::test]
    async fn attached_directory_excludes_private_prefixes_from_all_rescans()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        std::fs::create_dir(root.path().join(".git"))?;
        std::fs::write(root.path().join(".git").join("config"), b"private")?;
        std::fs::write(root.path().join("visible.txt"), b"visible")?;
        let options = SourceOptions {
            excluded_paths: vec![PortablePath::parse(
                "/.git",
                crate::model::VolumeLimits::default(),
            )?],
            ..SourceOptions::default()
        };
        let workspace =
            Box::pin(Fs::memory().attach_directory("filtered", root.path(), options)).await?;
        assert_eq!(
            workspace.read("/visible.txt", 16).await?,
            Bytes::from_static(b"visible")
        );
        assert!(workspace.read("/.git/config", 16).await.is_err());

        std::fs::write(root.path().join(".git").join("config"), b"changed")?;
        let source = workspace.source().ok_or("source handle missing")?;
        assert!(matches!(
            Box::pin(source.rescan()).await?,
            ReconcileOutcome::Clean(_)
        ));
        assert!(workspace.read("/.git/config", 16).await.is_err());
        Ok(())
    }

    #[cfg(feature = "local")]
    #[tokio::test]
    async fn durable_source_restarts_fail_closed_and_remains_gc_classifiable()
    -> Result<(), Box<dyn std::error::Error>> {
        let storage = tempfile::tempdir()?;
        let source_root = tempfile::tempdir()?;
        std::fs::write(source_root.path().join("durable.txt"), b"one")?;
        let local_options = crate::LocalOptions::new(storage.path());

        {
            let fs = Fs::local(local_options.clone()).await?;
            let workspace = Box::pin(fs.attach_directory(
                "durable",
                source_root.path(),
                SourceOptions::default(),
            ))
            .await?;
            let source = workspace.source().ok_or("source missing")?;
            assert_eq!(source.state().await, SourceState::Clean);
        }

        std::fs::write(source_root.path().join("durable.txt"), b"two")?;
        {
            let fs = Fs::local(local_options.clone()).await?;
            let workspace = Box::pin(fs.attach_directory(
                "durable",
                source_root.path(),
                SourceOptions::default(),
            ))
            .await?;
            assert_eq!(
                Box::pin(workspace.read("/durable.txt", 8)).await?,
                Bytes::from_static(b"two")
            );
            let wrong_root = tempfile::tempdir()?;
            assert!(matches!(
                Box::pin(fs.attach_directory(
                    "durable",
                    wrong_root.path(),
                    SourceOptions::default()
                ))
                .await,
                Err(SourceError::BindingMismatch)
            ));
        }

        Ok(())
    }

    #[tokio::test]
    async fn keyed_source_retry_recovers_exact_outcome_and_rejects_another_kind()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        std::fs::write(root.path().join("value.txt"), b"one")?;
        let workspace =
            Box::pin(Fs::memory().attach_directory("keyed", root.path(), SourceOptions::default()))
                .await?;
        let source = workspace.source().ok_or("source missing")?;
        std::fs::write(root.path().join("value.txt"), b"two")?;
        let key = IdempotencyKey::from_bytes([41; 16]);
        let first = clean_generation(Box::pin(source.rescan_with_key(key)).await?)?;
        std::fs::write(root.path().join("value.txt"), b"three")?;
        let retried = clean_generation(Box::pin(source.rescan_with_key(key)).await?)?;
        assert_eq!(retried.id(), first.id());
        assert_eq!(
            retried.read("/value.txt", 8).await?,
            Bytes::from_static(b"two")
        );
        assert!(matches!(
            Box::pin(source.seal_with_key(key)).await,
            Err(SourceError::IdempotencyConflict)
        ));
        Ok(())
    }

    #[tokio::test]
    async fn no_op_reconcile_conflicts_after_an_independent_workspace_advance()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        let workspace = Box::pin(Fs::memory().attach_directory(
            "no-op-stale",
            root.path(),
            SourceOptions::default(),
        ))
        .await?;
        let source = workspace.source().ok_or("source missing")?;
        let acknowledged = source.inner.lock().await.checkout.generation_id();

        let mut unrelated = workspace
            .volume
            .checkout(
                GenerationSelector::Head,
                CheckoutMode::tracking_transaction(),
                WorkBudget::UNBOUNDED,
                &CancellationToken::new(),
            )
            .await?
            .value;
        let advanced = match unrelated
            .commit_with_context(
                IdempotencyKey::from_bytes([62; 16]).operation_id(),
                Digest::from_bytes([62; 32]),
                WorkBudget::UNBOUNDED,
                &CancellationToken::new(),
            )
            .await?
            .value
        {
            CheckoutCommitOutcome::Committed { generation_id, .. }
            | CheckoutCommitOutcome::AlreadyCommitted { generation_id, .. } => generation_id,
            CheckoutCommitOutcome::Conflict { .. }
            | CheckoutCommitOutcome::Fenced { .. }
            | CheckoutCommitOutcome::IdempotencyConflict { .. } => {
                return Err("independent workspace authority advance was rejected".into());
            }
        };
        assert_eq!(advanced, acknowledged);

        let key = IdempotencyKey::from_bytes([63; 16]);
        match Box::pin(source.reconcile_with_key(key)).await? {
            ReconcileOutcome::Conflict => assert!(matches!(
                Box::pin(source.reconcile_with_key(key)).await?,
                ReconcileOutcome::Conflict
            )),
            ReconcileOutcome::NeedsRescan(WatchInvalidationReason::NativeRescanRequired)
                if cfg!(target_os = "macos") =>
            {
                assert!(matches!(
                    Box::pin(source.reconcile_with_key(key)).await?,
                    ReconcileOutcome::NeedsRescan(WatchInvalidationReason::NativeRescanRequired)
                ));
                assert!(matches!(
                    Box::pin(source.rescan_with_key(IdempotencyKey::from_bytes([71; 16]))).await?,
                    ReconcileOutcome::Conflict
                ));
            }
            _ => return Err("source did not preserve conflict or rescan state".into()),
        }
        assert!(matches!(
            Box::pin(source.reconcile_with_key(IdempotencyKey::from_bytes([72; 16]))).await?,
            ReconcileOutcome::Conflict
        ));
        assert!(matches!(
            Box::pin(source.rescan_with_key(IdempotencyKey::from_bytes([73; 16]))).await?,
            ReconcileOutcome::Conflict
        ));
        assert!(matches!(
            Box::pin(source.seal_with_key(IdempotencyKey::from_bytes([74; 16]))).await,
            Err(SourceError::Conflict)
        ));
        assert_eq!(source.state().await, SourceState::Conflict);
        assert_eq!(workspace.head().await?.id(), advanced);
        Ok(())
    }

    #[tokio::test]
    async fn pending_source_capture_conflicts_after_an_authority_only_advance()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        std::fs::write(root.path().join("source.txt"), b"source")?;
        let workspace = Box::pin(Fs::memory().attach_directory(
            "pending-source-authority-fence",
            root.path(),
            SourceOptions::default(),
        ))
        .await?;
        let source = workspace.source().ok_or("source missing")?;
        let key = IdempotencyKey::from_bytes([77; 16]);
        {
            let mut session = source.inner.lock().await;
            begin_source_operation(&mut session, key, SourceOperation::Reconcile).await?;
            let limits = session.checkout.volume_config().limits;
            let portable = crate::path::PortablePath::parse("/source.txt", limits)?;
            let path = crate::kernel::NamespacePath::from_portable(&portable, limits)?;
            session
                .checkout
                .write_file(
                    path,
                    0,
                    Bytes::from_static(b"captured"),
                    WorkBudget::UNBOUNDED,
                    &CancellationToken::new(),
                )
                .await?;
            assert!(session.checkout.has_pending_mutations());
        }

        let mut unrelated = workspace
            .volume
            .checkout(
                GenerationSelector::Head,
                CheckoutMode::tracking_transaction(),
                WorkBudget::UNBOUNDED,
                &CancellationToken::new(),
            )
            .await?
            .value;
        let advanced = match unrelated
            .commit_with_context(
                IdempotencyKey::from_bytes([78; 16]).operation_id(),
                Digest::from_bytes([78; 32]),
                WorkBudget::UNBOUNDED,
                &CancellationToken::new(),
            )
            .await?
            .value
        {
            CheckoutCommitOutcome::Committed { generation_id, .. }
            | CheckoutCommitOutcome::AlreadyCommitted { generation_id, .. } => generation_id,
            CheckoutCommitOutcome::Conflict { .. }
            | CheckoutCommitOutcome::Fenced { .. }
            | CheckoutCommitOutcome::IdempotencyConflict { .. } => {
                return Err("independent workspace authority advance was rejected".into());
            }
        };

        let outcome = {
            let mut session = source.inner.lock().await;
            assert_eq!(advanced, session.checkout.generation_id());
            publish_session(
                &mut session,
                key,
                SourceOperation::Reconcile,
                SourceState::Clean,
            )
            .await?
        };
        assert!(matches!(outcome, ReconcileOutcome::Conflict));
        assert!(matches!(
            Box::pin(source.reconcile_with_key(key)).await?,
            ReconcileOutcome::Conflict
        ));
        assert_eq!(source.state().await, SourceState::Conflict);
        assert_eq!(workspace.head().await?.id(), advanced);
        Ok(())
    }

    #[tokio::test]
    async fn pending_source_capture_rebases_over_a_disjoint_generation()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        std::fs::write(root.path().join("source.txt"), b"source")?;
        let workspace = Box::pin(Fs::memory().attach_directory(
            "pending-source-disjoint-rebase",
            root.path(),
            SourceOptions::default(),
        ))
        .await?;
        let source = workspace.source().ok_or("source missing")?;
        let key = IdempotencyKey::from_bytes([79; 16]);
        let acknowledged = {
            let mut session = source.inner.lock().await;
            begin_source_operation(&mut session, key, SourceOperation::Reconcile).await?;
            let acknowledged = session.checkout.generation_id();
            let limits = session.checkout.volume_config().limits;
            let portable = crate::path::PortablePath::parse("/source.txt", limits)?;
            let path = crate::kernel::NamespacePath::from_portable(&portable, limits)?;
            session
                .checkout
                .write_file(
                    path,
                    0,
                    Bytes::from_static(b"captured"),
                    WorkBudget::UNBOUNDED,
                    &CancellationToken::new(),
                )
                .await?;
            assert!(session.checkout.has_pending_mutations());
            acknowledged
        };

        let mut unrelated = workspace
            .begin_transaction(IdempotencyKey::from_bytes([80; 16]))
            .await?;
        unrelated
            .write("/unrelated.txt", Bytes::from_static(b"unrelated"))
            .await?;
        let advanced = match unrelated.commit().await? {
            crate::TransactionCommit::Committed(generation)
            | crate::TransactionCommit::AlreadyCommitted(generation) => generation,
            crate::TransactionCommit::Conflict { .. }
            | crate::TransactionCommit::Fenced
            | crate::TransactionCommit::IdempotencyConflict => {
                return Err("disjoint workspace advance was rejected".into());
            }
        };
        assert_ne!(advanced.id(), acknowledged);

        let reconciled = {
            let mut session = source.inner.lock().await;
            clean_generation(
                publish_session(
                    &mut session,
                    key,
                    SourceOperation::Reconcile,
                    SourceState::Clean,
                )
                .await?,
            )?
        };
        assert_eq!(
            reconciled.read("/source.txt", 16).await?,
            Bytes::from_static(b"captured")
        );
        assert_eq!(
            reconciled.read("/unrelated.txt", 16).await?,
            Bytes::from_static(b"unrelated")
        );
        assert_eq!(
            clean_generation(Box::pin(source.reconcile_with_key(key)).await?)?.id(),
            reconciled.id()
        );
        assert_eq!(source.state().await, SourceState::Clean);
        Ok(())
    }

    #[tokio::test]
    async fn no_op_reconcile_conflicts_when_an_advance_wins_before_its_fence()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        let gate = Arc::new(AppendGate::new());
        let authority = GatedAuthorityStore {
            inner: Arc::new(crate::memory::MemoryAuthorityStore::default()),
            gate: Arc::clone(&gate),
        };
        let fs = Fs::new(
            authority,
            Arc::new(crate::memory::MemoryObjectStore::default()),
            crate::EmbeddedCapabilities::MEMORY,
        );
        let workspace = Box::pin(fs.attach_directory(
            "no-op-before-fence",
            root.path(),
            SourceOptions::default(),
        ))
        .await?;
        let source_key = IdempotencyKey::from_bytes([66; 16]);
        let acknowledged = workspace
            .source()
            .ok_or("source missing")?
            .inner
            .lock()
            .await
            .checkout
            .generation_id();
        gate.arm(
            source_volume_operation_id(source_key, SourceOperation::Reconcile),
            AppendGatePhase::Before,
        );
        let source = workspace.source().ok_or("source missing")?.clone();
        let operation = tokio::spawn(async move { source.reconcile_with_key(source_key).await });
        gate.wait_for_arrivals(1).await;

        let mut unrelated = workspace
            .begin_transaction(IdempotencyKey::from_bytes([67; 16]))
            .await?;
        unrelated
            .write("/unrelated.txt", Bytes::from_static(b"unrelated"))
            .await?;
        let advanced = match unrelated.commit().await? {
            crate::TransactionCommit::Committed(generation)
            | crate::TransactionCommit::AlreadyCommitted(generation) => generation,
            crate::TransactionCommit::Conflict { .. }
            | crate::TransactionCommit::Fenced
            | crate::TransactionCommit::IdempotencyConflict => {
                return Err("concurrent workspace advance was rejected".into());
            }
        };
        assert_ne!(advanced.id(), acknowledged);
        gate.release();

        assert!(matches!(operation.await??, ReconcileOutcome::Conflict));
        let source = workspace.source().ok_or("source missing")?;
        assert!(matches!(
            Box::pin(source.reconcile_with_key(source_key)).await?,
            ReconcileOutcome::Conflict
        ));
        assert_eq!(source.state().await, SourceState::Conflict);
        assert_eq!(workspace.head().await?.id(), advanced.id());
        Ok(())
    }

    #[tokio::test]
    async fn no_op_reconcile_linearizes_before_an_advance_between_fence_and_terminal()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        let gate = Arc::new(AppendGate::new());
        let authority = GatedAuthorityStore {
            inner: Arc::new(crate::memory::MemoryAuthorityStore::default()),
            gate: Arc::clone(&gate),
        };
        let fs = Fs::new(
            authority,
            Arc::new(crate::memory::MemoryObjectStore::default()),
            crate::EmbeddedCapabilities::MEMORY,
        );
        let workspace = Box::pin(fs.attach_directory(
            "no-op-concurrent",
            root.path(),
            SourceOptions::default(),
        ))
        .await?;
        let source_key = IdempotencyKey::from_bytes([64; 16]);
        let acknowledged = workspace
            .source()
            .ok_or("source missing")?
            .inner
            .lock()
            .await
            .checkout
            .generation_id();
        gate.arm(
            source_stage_operation_id(source_key, SourceOperationStage::Terminal),
            AppendGatePhase::Before,
        );
        let source = workspace.source().ok_or("source missing")?.clone();
        let operation = tokio::spawn(async move { source.reconcile_with_key(source_key).await });
        gate.wait_for_arrivals(1).await;

        let mut unrelated = workspace
            .begin_transaction(IdempotencyKey::from_bytes([65; 16]))
            .await?;
        unrelated
            .write("/unrelated.txt", Bytes::from_static(b"unrelated"))
            .await?;
        let advanced = match unrelated.commit().await? {
            crate::TransactionCommit::Committed(generation)
            | crate::TransactionCommit::AlreadyCommitted(generation) => generation,
            crate::TransactionCommit::Conflict { .. }
            | crate::TransactionCommit::Fenced
            | crate::TransactionCommit::IdempotencyConflict => {
                return Err("concurrent workspace advance was rejected".into());
            }
        };
        assert_ne!(advanced.id(), acknowledged);
        gate.release();

        let reconciled = clean_generation(operation.await??)?;
        assert_eq!(reconciled.id(), acknowledged);
        let source = workspace.source().ok_or("source missing")?;
        assert_eq!(
            clean_generation(Box::pin(source.reconcile_with_key(source_key)).await?)?.id(),
            acknowledged
        );
        assert_eq!(source.state().await, SourceState::Clean);
        assert_eq!(workspace.head().await?.id(), advanced.id());
        Ok(())
    }

    #[tokio::test]
    async fn published_retry_preserves_a_later_fail_closed_state()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        std::fs::write(root.path().join("source.txt"), b"source")?;
        let workspace = Box::pin(Fs::memory().attach_directory(
            "published-retry-terminal-race",
            root.path(),
            SourceOptions::default(),
        ))
        .await?;
        let source = workspace.source().ok_or("source missing")?;
        let published_key = IdempotencyKey::from_bytes([68; 16]);
        let other_key = IdempotencyKey::from_bytes([69; 16]);

        let (published_generation, published_begin_head, other_begin, other_terminal) = {
            let mut session = source.inner.lock().await;
            begin_source_operation(&mut session, published_key, SourceOperation::Reconcile).await?;
            let published_begin_head = session.authority_head;
            let publication = session
                .checkout
                .commit_with_context(
                    source_volume_operation_id(published_key, SourceOperation::Reconcile),
                    source_volume_operation_context(published_key, SourceOperation::Reconcile),
                    WorkBudget::UNBOUNDED,
                    &CancellationToken::new(),
                )
                .await?
                .value;
            let published_generation = match publication {
                CheckoutCommitOutcome::Committed { generation_id, .. }
                | CheckoutCommitOutcome::AlreadyCommitted { generation_id, .. } => generation_id,
                CheckoutCommitOutcome::Conflict { .. }
                | CheckoutCommitOutcome::Fenced { .. }
                | CheckoutCommitOutcome::IdempotencyConflict { .. } => {
                    return Err("source volume publication was rejected".into());
                }
            };
            (
                published_generation,
                published_begin_head,
                source_fact(&session, SourceState::PendingCapture, published_generation),
                source_fact(
                    &session,
                    SourceState::NeedsRescan(WatchInvalidationReason::BackendError),
                    published_generation,
                ),
            )
        };

        let other_begin_head = append_source_fact_with_identity(
            &workspace,
            published_begin_head,
            other_begin,
            source_stage_operation_id(other_key, SourceOperationStage::Begin),
            source_operation_fingerprint(SourceOperation::Reconcile, &other_begin)?,
        )
        .await?;
        let other_terminal_head = append_source_fact_with_identity(
            &workspace,
            other_begin_head,
            other_terminal,
            source_stage_operation_id(other_key, SourceOperationStage::Terminal),
            source_operation_fingerprint(SourceOperation::Reconcile, &other_terminal)?,
        )
        .await?;

        assert!(matches!(
            Box::pin(source.reconcile_with_key(published_key)).await?,
            ReconcileOutcome::Conflict
        ));
        assert!(matches!(
            Box::pin(source.reconcile_with_key(published_key)).await?,
            ReconcileOutcome::Conflict
        ));
        let mut session = source.inner.lock().await;
        let recovered = find_source_operation(
            &mut session,
            published_key,
            SourceOperation::Reconcile,
            SourceOperationStage::Terminal,
        )
        .await?
        .ok_or("recovered terminal missing")?;
        let recovered_head = session.authority_head;
        assert_eq!(recovered.fact.generation_id, published_generation);
        assert_eq!(recovered.fact.state, DurableSourceState::Conflict);
        assert!(recovered_head.sequence > other_terminal_head.sequence);
        assert_eq!(session.state, SourceState::Conflict);
        Ok(())
    }

    #[tokio::test]
    async fn published_retry_conflicts_after_another_source_generation()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        std::fs::write(root.path().join("source.txt"), b"one")?;
        let fs = Fs::memory();
        let first_workspace = Box::pin(fs.attach_directory(
            "published-retry-generation-race",
            root.path(),
            SourceOptions::default(),
        ))
        .await?;
        let first = first_workspace.source().ok_or("first source missing")?;
        let published_key = IdempotencyKey::from_bytes([75; 16]);
        std::fs::write(root.path().join("source.txt"), b"two")?;
        let published_generation =
            publish_without_terminal(first, published_key, SourceOperation::Rescan).await?;

        std::fs::write(root.path().join("source.txt"), b"three")?;
        let second_workspace = Box::pin(fs.attach_directory(
            "published-retry-generation-race",
            root.path(),
            SourceOptions::default(),
        ))
        .await?;
        let second = second_workspace.source().ok_or("second source missing")?;
        let advanced = second_workspace.head().await?;
        assert_ne!(advanced.id(), published_generation);
        assert_eq!(second.state().await, SourceState::Clean);

        assert!(matches!(
            Box::pin(first.rescan_with_key(published_key)).await?,
            ReconcileOutcome::Conflict
        ));
        {
            let mut session = first.inner.lock().await;
            let recovered = find_source_operation(
                &mut session,
                published_key,
                SourceOperation::Rescan,
                SourceOperationStage::Terminal,
            )
            .await?
            .ok_or("conflict terminal missing")?;
            assert_eq!(recovered.fact.generation_id, published_generation);
            assert_eq!(recovered.fact.state, DurableSourceState::Conflict);
            assert_eq!(session.state, SourceState::Conflict);
        }
        assert_eq!(first.state().await, SourceState::Conflict);
        assert!(matches!(
            Box::pin(first.seal_with_key(IdempotencyKey::from_bytes([76; 16]))).await,
            Err(SourceError::Conflict)
        ));
        Ok(())
    }

    #[tokio::test]
    async fn terminal_retry_refreshes_a_later_source_state()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        std::fs::write(root.path().join("source.txt"), b"source")?;
        let workspace = Box::pin(Fs::memory().attach_directory(
            "terminal-retry-refresh",
            root.path(),
            SourceOptions::default(),
        ))
        .await?;
        let source = workspace.source().ok_or("source missing")?;
        let completed_key = IdempotencyKey::from_bytes([70; 16]);
        let later_key = IdempotencyKey::from_bytes([71; 16]);

        let (completed_generation, completed_terminal_head, later_begin, later_terminal) = {
            let mut session = source.inner.lock().await;
            begin_source_operation(&mut session, completed_key, SourceOperation::Reconcile).await?;
            let publication = session
                .checkout
                .commit_with_context(
                    source_volume_operation_id(completed_key, SourceOperation::Reconcile),
                    source_volume_operation_context(completed_key, SourceOperation::Reconcile),
                    WorkBudget::UNBOUNDED,
                    &CancellationToken::new(),
                )
                .await?
                .value;
            let completed_generation = match publication {
                CheckoutCommitOutcome::Committed { generation_id, .. }
                | CheckoutCommitOutcome::AlreadyCommitted { generation_id, .. } => generation_id,
                CheckoutCommitOutcome::Conflict { .. }
                | CheckoutCommitOutcome::Fenced { .. }
                | CheckoutCommitOutcome::IdempotencyConflict { .. } => {
                    return Err("source volume publication was rejected".into());
                }
            };
            persist_source_operation_with_generation(
                &mut session,
                SourceState::Clean,
                completed_generation,
                completed_key,
                SourceOperation::Reconcile,
            )
            .await?;
            (
                completed_generation,
                session.authority_head,
                source_fact(&session, SourceState::PendingCapture, completed_generation),
                source_fact(&session, SourceState::Conflict, completed_generation),
            )
        };

        let later_begin_head = append_source_fact_with_identity(
            &workspace,
            completed_terminal_head,
            later_begin,
            source_stage_operation_id(later_key, SourceOperationStage::Begin),
            source_operation_fingerprint(SourceOperation::Reconcile, &later_begin)?,
        )
        .await?;
        let later_terminal_head = append_source_fact_with_identity(
            &workspace,
            later_begin_head,
            later_terminal,
            source_stage_operation_id(later_key, SourceOperationStage::Terminal),
            source_operation_fingerprint(SourceOperation::Reconcile, &later_terminal)?,
        )
        .await?;

        assert_eq!(
            clean_generation(Box::pin(source.reconcile_with_key(completed_key)).await?)?.id(),
            completed_generation
        );
        let session = source.inner.lock().await;
        assert_eq!(session.authority_head, later_terminal_head);
        assert_eq!(session.state, SourceState::Conflict);
        Ok(())
    }

    #[tokio::test]
    async fn two_source_sessions_replay_one_canonical_terminal_outcome()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        std::fs::write(root.path().join("value.txt"), b"one")?;
        let gate = Arc::new(AppendGate::new());
        let authority = GatedAuthorityStore {
            inner: Arc::new(crate::memory::MemoryAuthorityStore::default()),
            gate: Arc::clone(&gate),
        };
        let fs = Fs::new(
            authority,
            Arc::new(crate::memory::MemoryObjectStore::default()),
            crate::EmbeddedCapabilities::MEMORY,
        );
        let first_workspace =
            Box::pin(fs.attach_directory("two-sessions", root.path(), SourceOptions::default()))
                .await?;
        let second_workspace =
            Box::pin(fs.attach_directory("two-sessions", root.path(), SourceOptions::default()))
                .await?;
        let first = first_workspace.source().ok_or("first source missing")?;
        let second = second_workspace.source().ok_or("second source missing")?;
        let key = IdempotencyKey::from_bytes([52; 16]);
        {
            let mut session = second.inner.lock().await;
            begin_source_operation(&mut session, key, SourceOperation::Rescan).await?;
        }
        {
            let mut session = first.inner.lock().await;
            begin_source_operation(&mut session, key, SourceOperation::Rescan).await?;
        }
        gate.arm(
            source_stage_operation_id(key, SourceOperationStage::Terminal),
            AppendGatePhase::Before,
        );
        let first = first.clone();
        let first_terminal = tokio::spawn(async move {
            let mut session = first.inner.lock().await;
            let generation_id = session.checkout.generation_id();
            persist_source_operation_with_generation(
                &mut session,
                SourceState::Clean,
                generation_id,
                key,
                SourceOperation::Rescan,
            )
            .await
        });
        let second = second.clone();
        let second_terminal = tokio::spawn(async move {
            let mut session = second.inner.lock().await;
            let generation_id = session.checkout.generation_id();
            persist_source_operation_with_generation(
                &mut session,
                SourceState::Conflict,
                generation_id,
                key,
                SourceOperation::Rescan,
            )
            .await
        });
        gate.wait_for_arrivals(2).await;
        gate.release();
        let first_fact = first_terminal.await??;
        let second_fact = second_terminal.await??;
        assert_eq!(first_fact, second_fact);
        let first_session = first_workspace
            .source()
            .ok_or("first source missing")?
            .inner
            .lock()
            .await;
        let second_session = second_workspace
            .source()
            .ok_or("second source missing")?
            .inner
            .lock()
            .await;
        assert_eq!(first_session.authority_head, second_session.authority_head);
        assert_eq!(first_session.state, second_session.state);
        assert_eq!(first_session.state, source_state(first_fact.state));
        Ok(())
    }

    #[tokio::test]
    async fn dropped_source_future_recovers_after_each_durable_append_boundary()
    -> Result<(), Box<dyn std::error::Error>> {
        {
            let root = tempfile::tempdir()?;
            std::fs::write(root.path().join("value.txt"), b"one")?;
            let gate = Arc::new(AppendGate::new());
            let authority = GatedAuthorityStore {
                inner: Arc::new(crate::memory::MemoryAuthorityStore::default()),
                gate: Arc::clone(&gate),
            };
            let fs = Fs::new(
                authority.clone(),
                Arc::new(crate::memory::MemoryObjectStore::default()),
                crate::EmbeddedCapabilities::MEMORY,
            );
            let workspace = Box::pin(fs.attach_directory(
                "drop-after-begin",
                root.path(),
                SourceOptions::default(),
            ))
            .await?;
            let key = IdempotencyKey::from_bytes([59; 16]);
            gate.arm(
                source_stage_operation_id(key, SourceOperationStage::Begin),
                AppendGatePhase::After,
            );
            std::fs::write(root.path().join("value.txt"), b"two")?;
            let source = workspace.source().ok_or("source missing")?.clone();
            let operation = tokio::spawn(async move { source.rescan_with_key(key).await });
            gate.wait_for_arrivals(1).await;
            operation.abort();
            assert!(operation.await.is_err_and(|error| error.is_cancelled()));
            gate.release();

            let source = workspace.source().ok_or("source missing")?;
            let recovered = clean_generation(Box::pin(source.rescan_with_key(key)).await?)?;
            assert_eq!(
                recovered.read("/value.txt", 8).await?,
                Bytes::from_static(b"two")
            );
            std::fs::write(root.path().join("value.txt"), b"three")?;
            let current = clean_generation(Box::pin(source.rescan()).await?)?;
            let current_head = workspace.head().await?;
            assert_eq!(current_head.id(), current.id());
            assert_eq!(
                current.read("/value.txt", 8).await?,
                Bytes::from_static(b"three")
            );
            assert_eq!(
                clean_generation(Box::pin(source.rescan_with_key(key)).await?)?.id(),
                recovered.id()
            );
            assert_eq!(workspace.head().await?.id(), current.id());
            assert_eq!(source.state().await, SourceState::Clean);
            let session = source.inner.lock().await;
            let durable_head = authority
                .inner
                .head(
                    source_authority_id(workspace.volume.id()),
                    WorkBudget::UNBOUNDED,
                    &CancellationToken::new(),
                )
                .await?
                .value;
            assert_eq!(session.authority_head, durable_head);
        }

        for terminal_append in [false, true] {
            let root = tempfile::tempdir()?;
            std::fs::write(root.path().join("value.txt"), b"one")?;
            let gate = Arc::new(AppendGate::new());
            let authority = GatedAuthorityStore {
                inner: Arc::new(crate::memory::MemoryAuthorityStore::default()),
                gate: Arc::clone(&gate),
            };
            let objects = Arc::new(crate::memory::MemoryObjectStore::default());
            let name = if terminal_append {
                "drop-after-terminal"
            } else {
                "drop-after-volume"
            };
            let fs = Fs::new(
                authority.clone(),
                Arc::clone(&objects),
                crate::EmbeddedCapabilities::MEMORY,
            );
            let workspace =
                Box::pin(fs.attach_directory(name, root.path(), SourceOptions::default())).await?;
            let key = IdempotencyKey::from_bytes([60 + u8::from(terminal_append); 16]);
            let target = if terminal_append {
                source_stage_operation_id(key, SourceOperationStage::Terminal)
            } else {
                source_volume_operation_id(key, SourceOperation::Rescan)
            };
            gate.arm(target, AppendGatePhase::After);
            std::fs::write(root.path().join("value.txt"), b"two")?;
            let source = workspace.source().ok_or("source missing")?.clone();
            let operation = tokio::spawn(async move { source.rescan_with_key(key).await });
            gate.wait_for_arrivals(1).await;
            operation.abort();
            assert!(operation.await.is_err_and(|error| error.is_cancelled()));
            gate.release();

            std::fs::write(root.path().join("value.txt"), b"three")?;
            drop(workspace);
            drop(fs);
            let fs = Fs::new(
                authority.clone(),
                objects,
                crate::EmbeddedCapabilities::MEMORY,
            );
            let workspace =
                Box::pin(fs.attach_directory(name, root.path(), SourceOptions::default())).await?;
            let source = workspace.source().ok_or("source missing")?;
            let current = workspace.head().await?;
            assert_eq!(
                current.read("/value.txt", 8).await?,
                Bytes::from_static(b"three")
            );
            let outcome = Box::pin(source.rescan_with_key(key)).await?;
            if terminal_append {
                assert_eq!(
                    clean_generation(outcome)?.read("/value.txt", 8).await?,
                    Bytes::from_static(b"two")
                );
                assert_eq!(source.state().await, SourceState::Clean);
            } else {
                assert!(matches!(outcome, ReconcileOutcome::Conflict));
                assert_eq!(source.state().await, SourceState::Conflict);
            }
            assert_eq!(workspace.head().await?.id(), current.id());
            let session = source.inner.lock().await;
            let durable_head = authority
                .inner
                .head(
                    source_authority_id(workspace.volume.id()),
                    WorkBudget::UNBOUNDED,
                    &CancellationToken::new(),
                )
                .await?
                .value;
            assert_eq!(session.authority_head, durable_head);
        }
        Ok(())
    }

    #[tokio::test]
    async fn source_volume_identity_rejects_a_deliberately_aliased_generic_operation()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        std::fs::write(root.path().join("source.txt"), b"one")?;
        let fs = Fs::memory();
        let workspace = Box::pin(fs.attach_directory(
            "domain-separated",
            root.path(),
            SourceOptions::default(),
        ))
        .await?;
        let source = workspace.source().ok_or("source missing")?;
        let key = IdempotencyKey::from_bytes([42; 16]);
        {
            let mut session = source.inner.lock().await;
            begin_source_operation(&mut session, key, SourceOperation::Rescan).await?;
        }
        let forged_key = IdempotencyKey::from_bytes(
            source_volume_operation_id(key, SourceOperation::Rescan).into_bytes(),
        );
        let mut unrelated = workspace.begin_transaction(forged_key).await?;
        unrelated
            .write("/unrelated.txt", Bytes::from_static(b"generic"))
            .await?;
        let unrelated = match unrelated.commit().await? {
            crate::TransactionCommit::Committed(generation)
            | crate::TransactionCommit::AlreadyCommitted(generation) => generation,
            crate::TransactionCommit::Conflict { .. }
            | crate::TransactionCommit::Fenced
            | crate::TransactionCommit::IdempotencyConflict => {
                return Err("unexpected generic transaction rejection".into());
            }
        };
        std::fs::write(root.path().join("source.txt"), b"two")?;
        assert!(matches!(
            Box::pin(source.rescan_with_key(key)).await,
            Err(SourceError::IdempotencyConflict)
        ));
        assert_eq!(workspace.head().await?.id(), unrelated.id());
        assert_eq!(source.state().await, SourceState::PendingCapture);
        Ok(())
    }

    #[tokio::test]
    async fn ambiguous_volume_and_terminal_appends_recover_the_exact_source_generation()
    -> Result<(), Box<dyn std::error::Error>> {
        for terminal_fault in [false, true] {
            let simulation = crate::Simulation::default();
            let (authority, objects) = simulation.stores();
            let fs = Fs::new(
                authority.clone(),
                objects.clone(),
                crate::EmbeddedCapabilities::MEMORY,
            );
            let root = tempfile::tempdir()?;
            std::fs::write(root.path().join("value.txt"), b"one")?;
            let workspace = Box::pin(fs.attach_directory(
                if terminal_fault {
                    "ambiguous-terminal"
                } else {
                    "ambiguous-volume"
                },
                root.path(),
                SourceOptions::default(),
            ))
            .await?;
            let key = IdempotencyKey::from_bytes([50 + u8::from(terminal_fault); 16]);
            {
                let source = workspace.source().ok_or("source missing")?;
                let mut session = source.inner.lock().await;
                begin_source_operation(&mut session, key, SourceOperation::Rescan).await?;
            }
            std::fs::write(root.path().join("value.txt"), b"two")?;
            simulation.schedule(crate::ScheduledSimulationFault {
                operation: crate::SimulationOperation::AuthorityAppend,
                occurrence: next_authority_append(&simulation)? + u64::from(terminal_fault),
                fault: crate::SimulationFault::AmbiguousAuthorityAppend,
            })?;
            {
                let source = workspace.source().ok_or("source missing")?;
                assert!(matches!(
                    Box::pin(source.rescan_with_key(key)).await,
                    Err(SourceError::Engine(_))
                ));
            }
            std::fs::write(root.path().join("value.txt"), b"three")?;
            drop(workspace);
            drop(fs);
            let fs = Fs::new(authority, objects, crate::EmbeddedCapabilities::MEMORY);
            let workspace = Box::pin(fs.attach_directory(
                if terminal_fault {
                    "ambiguous-terminal"
                } else {
                    "ambiguous-volume"
                },
                root.path(),
                SourceOptions::default(),
            ))
            .await?;
            let source = workspace.source().ok_or("source missing")?;
            let current = workspace.head().await?;
            assert_eq!(
                current.read("/value.txt", 8).await?,
                Bytes::from_static(b"three")
            );
            let outcome = Box::pin(source.rescan_with_key(key)).await?;
            if terminal_fault {
                assert_eq!(
                    clean_generation(outcome)?.read("/value.txt", 8).await?,
                    Bytes::from_static(b"two")
                );
                assert_eq!(source.state().await, SourceState::Clean);
            } else {
                assert!(matches!(outcome, ReconcileOutcome::Conflict));
                assert_eq!(source.state().await, SourceState::Conflict);
            }
            assert_eq!(workspace.head().await?.id(), current.id());
        }
        Ok(())
    }

    #[cfg(feature = "local")]
    #[tokio::test]
    async fn restart_recovers_publication_missing_its_terminal_source_record()
    -> Result<(), Box<dyn std::error::Error>> {
        let storage = tempfile::tempdir()?;
        let root = tempfile::tempdir()?;
        std::fs::write(root.path().join("value.txt"), b"one")?;
        let options = crate::LocalOptions::new(storage.path());
        let key = IdempotencyKey::from_bytes([43; 16]);
        {
            let fs = Fs::local(options.clone()).await?;
            let workspace =
                Box::pin(fs.attach_directory("recover", root.path(), SourceOptions::default()))
                    .await?;
            let source = workspace.source().ok_or("source missing")?;
            std::fs::write(root.path().join("value.txt"), b"two")?;
            publish_without_terminal(source, key, SourceOperation::Rescan).await?;
        }

        std::fs::write(root.path().join("value.txt"), b"three")?;
        {
            let fs = Fs::local(options.clone()).await?;
            let workspace =
                Box::pin(fs.attach_directory("recover", root.path(), SourceOptions::default()))
                    .await?;
            let source = workspace.source().ok_or("source missing")?;
            let current = workspace.head().await?;
            assert_eq!(
                current.read("/value.txt", 8).await?,
                Bytes::from_static(b"three")
            );
            assert!(matches!(
                Box::pin(source.rescan_with_key(key)).await?,
                ReconcileOutcome::Conflict
            ));
            assert_eq!(workspace.head().await?.id(), current.id());
            assert_eq!(source.state().await, SourceState::Conflict);
        }

        let seal_key = IdempotencyKey::from_bytes([44; 16]);
        {
            let fs = Fs::local(options.clone()).await?;
            let workspace =
                Box::pin(fs.attach_directory("recover", root.path(), SourceOptions::default()))
                    .await?;
            let source = workspace.source().ok_or("source missing")?;
            std::fs::write(root.path().join("value.txt"), b"four")?;
            publish_without_terminal(source, seal_key, SourceOperation::Seal).await?;
        }

        std::fs::write(root.path().join("value.txt"), b"five")?;
        {
            let fs = Fs::local(options.clone()).await?;
            let workspace =
                Box::pin(fs.attach_directory("recover", root.path(), SourceOptions::default()))
                    .await?;
            let source = workspace.source().ok_or("source missing")?;
            let current = workspace.head().await?;
            assert!(matches!(
                Box::pin(source.seal_with_key(seal_key)).await,
                Err(SourceError::Conflict)
            ));
            assert_eq!(workspace.head().await?.id(), current.id());
            assert_eq!(source.state().await, SourceState::Conflict);
        }

        let fs = Fs::local(options).await?;
        let workspace =
            Box::pin(fs.attach_directory("recover", root.path(), SourceOptions::default())).await?;
        let source = workspace.source().ok_or("source missing")?;
        assert_eq!(
            workspace.read("/value.txt", 8).await?,
            Bytes::from_static(b"five")
        );
        assert!(matches!(
            Box::pin(source.rescan_with_key(key)).await?,
            ReconcileOutcome::Conflict
        ));
        assert!(matches!(
            Box::pin(source.seal_with_key(seal_key)).await,
            Err(SourceError::Conflict)
        ));
        assert_eq!(
            workspace.read("/value.txt", 8).await?,
            Bytes::from_static(b"five")
        );
        assert_eq!(source.state().await, SourceState::Clean);
        Ok(())
    }
}