mobench-artifacts 0.2.0

Transactional artifact publication primitives for mobench
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
//! Contained artifact roots and atomic run workspaces.
//!
//! [`ApprovedRoot`] validates paths immediately before use. It prevents
//! traversal through pre-existing symlinks, but it does not yet provide the
//! descriptor-relative operations needed to close hostile concurrent-swap
//! races on every supported platform.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::fs::{self, File, OpenOptions};
use std::io::{BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use fs2::FileExt;
use semver::Version;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use thiserror::Error;

/// A validated artifact identifier that is safe to use as one path component.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ArtifactId(String);

impl ArtifactId {
    /// Validate and retain a single artifact path component.
    pub fn new(value: impl Into<String>) -> Result<Self, ArtifactPathError> {
        let value = value.into();
        let path = Path::new(&value);
        let is_one_normal_component = {
            let mut components = path.components();
            matches!(components.next(), Some(std::path::Component::Normal(_)))
                && components.next().is_none()
        };
        if value.is_empty()
            || value.contains('/')
            || value.contains('\\')
            || path.is_absolute()
            || !is_one_normal_component
        {
            return Err(ArtifactPathError::InvalidArtifactId { value });
        }
        Ok(Self(value))
    }

    /// Return the validated component.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ArtifactId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

const STAGING_DIRECTORY: &str = ".mobench-staging";
const STAGING_QUARANTINE_DIRECTORY: &str = ".mobench-staging-quarantine";
const STAGING_LOCK_FILE: &str = ".mobench-staging.lock";
const WORKSPACE_LOCK_FILE: &str = ".mobench-workspace.lock";
const RUN_READER_LOCK_FILE: &str = ".mobench-run-reader.lock";
const RUN_RETENTION_QUARANTINE_DIRECTORY: &str = ".mobench-run-quarantine";
const LATEST_DIRECTORY: &str = ".mobench-latest";
const LATEST_STAGING_DIRECTORY: &str = "staging";
const LATEST_GENERATIONS_DIRECTORY: &str = "generations";
const LATEST_QUARANTINE_DIRECTORY: &str = "quarantine";
const LATEST_CURRENT_FILE: &str = "current";
const LATEST_LOCK_FILE: &str = ".mobench-latest.lock";
const LATEST_READER_LOCK_FILE: &str = ".mobench-reader.lock";
const LATEST_RETENTION_BOUNDARY_FILE: &str = ".mobench-retention-boundary.json";
const RETAIN_LATEST_GENERATIONS: usize = 8;
const RETAIN_PUBLISHED_RUNS: usize = 32;
const RETAIN_QUARANTINE_ENTRIES: usize = 16;
/// File name of the versioned manifest stored in every published run.
pub const RUN_MANIFEST_FILE: &str = "mobench-run-manifest.json";
/// File name of the versioned manifest stored in every latest generation.
pub const LATEST_MANIFEST_FILE: &str = "manifest.json";
const RUN_MANIFEST_VERSION: u32 = 1;
const LATEST_MANIFEST_VERSION: u32 = 1;
const LATEST_LOCK_TIMEOUT: Duration = Duration::from_secs(5);
const LATEST_LOCK_POLL_INTERVAL: Duration = Duration::from_millis(5);
const MAX_ALLOCATION_ATTEMPTS: usize = 1_024;
static WORKSPACE_SEQUENCE: AtomicU64 = AtomicU64::new(0);
static ACTIVE_WORKSPACES: OnceLock<Mutex<BTreeSet<PathBuf>>> = OnceLock::new();

/// A unique private directory for building one complete run before publication.
#[derive(Debug)]
pub struct RunWorkspace {
    root: ApprovedRoot,
    logical_id: ArtifactId,
    expected_latest_generation: Option<String>,
    workspace_lock: Option<File>,
    staging_path: Option<PathBuf>,
    published_path: PathBuf,
}

/// A completed run directory that has been atomically renamed into visibility.
#[derive(Debug, Clone)]
pub struct PublishedRun {
    root: ApprovedRoot,
    path: PathBuf,
    _reader_lease: Arc<File>,
}

/// One regular file recorded in a durable artifact manifest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ManifestArtifact {
    /// Slash-separated path relative to the manifest's directory.
    pub relative_path: String,
    /// Exact file length in bytes.
    pub size: u64,
    /// Lower-case hexadecimal SHA-256 digest.
    pub sha256: String,
}

/// Durable identity and integrity record for one published run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RunManifest {
    /// Manifest format version. Unknown versions are rejected.
    pub format_version: u32,
    /// Version of the mobench-artifacts producer.
    pub producer_version: String,
    /// Caller-provided logical run identity.
    pub logical_id: String,
    /// Collision-resistant published directory identity.
    pub publication_id: String,
    /// Latest generation observed when this run workspace was allocated.
    /// Refresh uses this as a compare-and-swap token.
    pub expected_latest_generation: Option<String>,
    /// Every regular run artifact except this manifest, sorted by path.
    pub artifacts: Vec<ManifestArtifact>,
}

/// Mapping from a published run artifact into one latest-generation alias.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LatestManifestArtifact {
    /// Source path relative to the published run.
    pub source_relative_path: String,
    /// Stable public alias and path relative to the generation directory.
    pub destination_relative_path: String,
    /// Exact file length in bytes.
    pub size: u64,
    /// Lower-case hexadecimal SHA-256 digest.
    pub sha256: String,
}

/// Durable identity and integrity record for one immutable latest generation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LatestManifest {
    /// Manifest format version. Unknown versions are rejected.
    pub format_version: u32,
    /// Version of the mobench-artifacts producer.
    pub producer_version: String,
    /// Identity named by the atomic `current` pointer.
    pub generation: String,
    /// Previously committed generation, when one existed.
    pub predecessor_generation: Option<String>,
    /// Logical identity of the source run.
    pub source_logical_id: String,
    /// Publication identity of the source run.
    pub source_publication_id: String,
    /// Aliases in this generation, sorted by destination path.
    pub artifacts: Vec<LatestManifestArtifact>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct RetentionBoundary {
    format_version: u32,
    predecessor_generation: String,
}

/// A reader pinned to one immutable latest generation.
///
/// Opening resolves the atomic pointer once and verifies the generation
/// manifest and every listed artifact. Subsequent reads never re-resolve
/// `current`, so a concurrent writer cannot mix generations for this reader.
#[derive(Debug, Clone)]
pub struct LatestSnapshot {
    root: ApprovedRoot,
    generation_path: PathBuf,
    manifest: LatestManifest,
    _reader_lease: Arc<File>,
    _source_run_lease: Arc<File>,
    #[cfg(unix)]
    generation_directory: Arc<File>,
}

#[derive(Debug)]
struct LatestUpdateLock {
    file: File,
}

#[derive(Debug)]
struct StableAliasTransaction {
    path: PathBuf,
    root_path: PathBuf,
    installed: Vec<PathBuf>,
    backups: Vec<(PathBuf, PathBuf)>,
}

#[derive(Debug)]
enum PointerCommitFailure {
    BeforeCommit(ArtifactPathError),
    AfterCommit(ArtifactPathError),
}

impl StableAliasTransaction {
    fn rollback(self, original: ArtifactPathError) -> ArtifactPathError {
        let error =
            latest_update_failure(original, &self.installed, &self.backups, self.path.clone());
        let rollback_complete = !matches!(&error, ArtifactPathError::LatestRollback { .. });
        if rollback_complete {
            let _ = fs::remove_dir_all(&self.path);
        }
        let _ = sync_directory(&self.root_path);
        error
    }

    fn finish(self) {
        let _ = fs::remove_dir_all(self.path);
    }
}

impl Drop for LatestUpdateLock {
    fn drop(&mut self) {
        let _ = FileExt::unlock(&self.file);
    }
}

/// One published artifact to copy to a stable convenience path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LatestArtifact {
    source: ArtifactId,
    destination: ArtifactId,
}

impl LatestArtifact {
    /// Refresh a stable path with a published artifact of the same name.
    pub fn same(id: ArtifactId) -> Self {
        Self {
            source: id.clone(),
            destination: id,
        }
    }

    /// Refresh a stable destination from a differently named published file.
    pub fn new(source: ArtifactId, destination: ArtifactId) -> Self {
        Self {
            source,
            destination,
        }
    }
}

impl RunWorkspace {
    /// Allocate a unique staging directory and reserve a collision-resistant
    /// publication path derived from the validated logical run ID.
    pub fn allocate(
        root: impl AsRef<Path>,
        logical_id: &ArtifactId,
    ) -> Result<Self, ArtifactPathError> {
        let root_path = root.as_ref();
        fs::create_dir_all(root_path).map_err(|source| ArtifactPathError::Io {
            operation: "create artifact root",
            path: root_path.to_path_buf(),
            source,
        })?;
        let root = ApprovedRoot::existing(root_path)?;
        let expected_latest_generation =
            recover_latest_for_writer(&root)?.map(|snapshot| snapshot.manifest.generation);
        let _staging_manager_lock = acquire_staging_manager_lock(&root)?;
        let staging_root = root.prepare_dir(STAGING_DIRECTORY)?;
        quarantine_abandoned_run_staging(&root, &staging_root)?;

        for _ in 0..MAX_ALLOCATION_ATTEMPTS {
            let nonce = workspace_nonce();
            let staging_path = staging_root.join(&nonce);
            let published_path = root.path().join(format!("{logical_id}--{nonce}"));
            if fs::symlink_metadata(&published_path).is_ok() {
                continue;
            }

            match fs::create_dir(&staging_path) {
                Ok(()) => {
                    if fs::symlink_metadata(&published_path).is_ok() {
                        let _ = fs::remove_dir(&staging_path);
                        continue;
                    }
                    let workspace_lock_path = staging_path.join(WORKSPACE_LOCK_FILE);
                    let workspace_lock = match OpenOptions::new()
                        .read(true)
                        .write(true)
                        .create_new(true)
                        .open(&workspace_lock_path)
                    {
                        Ok(file) => file,
                        Err(source) => {
                            let _ = fs::remove_dir_all(&staging_path);
                            return Err(ArtifactPathError::Io {
                                operation: "create run-workspace lock",
                                path: workspace_lock_path,
                                source,
                            });
                        }
                    };
                    if let Err(source) = FileExt::lock_exclusive(&workspace_lock) {
                        let _ = fs::remove_dir_all(&staging_path);
                        return Err(ArtifactPathError::Io {
                            operation: "lock run workspace",
                            path: workspace_lock_path,
                            source,
                        });
                    }
                    register_active_workspace(&staging_path);
                    return Ok(Self {
                        root,
                        logical_id: logical_id.clone(),
                        expected_latest_generation,
                        workspace_lock: Some(workspace_lock),
                        staging_path: Some(staging_path),
                        published_path,
                    });
                }
                Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => continue,
                Err(source) => {
                    return Err(ArtifactPathError::Io {
                        operation: "create run staging directory",
                        path: staging_path,
                        source,
                    });
                }
            }
        }

        Err(ArtifactPathError::WorkspaceAllocationExhausted {
            logical_id: logical_id.clone(),
        })
    }

    /// Return the private directory where run outputs must be written.
    pub fn staging_path(&self) -> &Path {
        self.staging_path
            .as_deref()
            .expect("unpublished workspace retains its staging path")
    }

    /// Return the unique path where the completed run will be published.
    pub fn published_path(&self) -> &Path {
        &self.published_path
    }

    /// Return the approved output root shared by published and latest artifacts.
    pub fn root(&self) -> &ApprovedRoot {
        &self.root
    }

    /// Publish the complete staging directory without replacing any existing
    /// file, directory, or symbolic link at the destination.
    pub fn publish(
        mut self,
        required_files: &[ArtifactId],
    ) -> Result<PublishedRun, ArtifactPathError> {
        let staging_path = self
            .staging_path
            .as_ref()
            .expect("unpublished workspace retains its staging path")
            .clone();
        let published_path = self.published_path.clone();
        match fs::symlink_metadata(&staging_path) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                return Err(ArtifactPathError::SymlinkComponent { path: staging_path });
            }
            Ok(metadata) if !metadata.is_dir() => {
                return Err(ArtifactPathError::DirectoryComponentNotDirectory {
                    path: staging_path,
                });
            }
            Ok(_) => {}
            Err(source) => {
                return Err(ArtifactPathError::Io {
                    operation: "inspect run staging directory",
                    path: staging_path,
                    source,
                });
            }
        }
        let staging_relative = staging_path.strip_prefix(self.root.path()).map_err(|_| {
            ArtifactPathError::InvalidRelativePath {
                path: staging_path.clone(),
            }
        })?;
        self.root.prepare_dir(staging_relative)?;

        let staging_root = ApprovedRoot::existing(&staging_path)?;
        for required_file in required_files {
            let required_path = staging_root.prepare_file(required_file.as_str())?;
            match fs::symlink_metadata(&required_path) {
                Ok(metadata) if metadata.file_type().is_symlink() => {
                    return Err(ArtifactPathError::SymlinkComponent {
                        path: required_path,
                    });
                }
                Ok(metadata) if !metadata.is_file() => {
                    return Err(ArtifactPathError::FileDestinationNotFile {
                        path: required_path,
                    });
                }
                Ok(_) => {}
                Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
                    return Err(ArtifactPathError::RequiredArtifactMissing {
                        path: required_path,
                    });
                }
                Err(source) => {
                    return Err(ArtifactPathError::Io {
                        operation: "inspect required staged artifact",
                        path: required_path,
                        source,
                    });
                }
            }
        }

        let manifest_path = staging_path.join(RUN_MANIFEST_FILE);
        match fs::symlink_metadata(&manifest_path) {
            Ok(_) => {
                return Err(ArtifactPathError::ReservedManifestPath {
                    path: manifest_path,
                });
            }
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
            Err(source) => {
                return Err(ArtifactPathError::Io {
                    operation: "inspect reserved run manifest path",
                    path: manifest_path,
                    source,
                });
            }
        }

        create_run_reader_lease_file(&staging_path)?;
        let artifacts =
            inspect_artifact_tree(&staging_path, &[WORKSPACE_LOCK_FILE, RUN_READER_LOCK_FILE])?;
        let publication_id = published_path
            .file_name()
            .and_then(|name| name.to_str())
            .ok_or_else(|| ArtifactPathError::NonUtf8ArtifactPath {
                path: published_path.clone(),
            })?
            .to_owned();
        let manifest = RunManifest {
            format_version: RUN_MANIFEST_VERSION,
            producer_version: env!("CARGO_PKG_VERSION").to_owned(),
            logical_id: self.logical_id.as_str().to_owned(),
            publication_id,
            expected_latest_generation: self.expected_latest_generation.clone(),
            artifacts,
        };
        write_json_file(&manifest_path, &manifest, "write run manifest")?;
        sync_artifact_tree(&staging_path)?;

        match fs::symlink_metadata(&published_path) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                return Err(ArtifactPathError::SymlinkComponent {
                    path: published_path,
                });
            }
            Ok(_) => {
                return Err(ArtifactPathError::PublicationDestinationExists {
                    path: published_path,
                });
            }
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
            Err(source) => {
                return Err(ArtifactPathError::Io {
                    operation: "inspect run publication destination",
                    path: published_path,
                    source,
                });
            }
        }

        let _staging_manager_lock = acquire_staging_manager_lock(&self.root)?;
        let workspace_lock_path = staging_path.join(WORKSPACE_LOCK_FILE);
        let workspace_lock = self.workspace_lock.take();
        if let Some(workspace_lock) = workspace_lock.as_ref() {
            let _ = FileExt::unlock(workspace_lock);
        }
        // Close before unlinking so publication also works on platforms that
        // do not allow deleting an open file. The staging-manager lock keeps
        // recovery from racing this short handoff window.
        drop(workspace_lock);
        fs::remove_file(&workspace_lock_path).map_err(|source| ArtifactPathError::Io {
            operation: "remove run-workspace lock before publication",
            path: workspace_lock_path,
            source,
        })?;
        sync_directory(&staging_path)?;

        rename_directory_noreplace(&staging_path, &published_path).map_err(|source| {
            ArtifactPathError::Io {
                operation: "publish completed run",
                path: published_path.clone(),
                source,
            }
        })?;
        record_durability_event("publish_run");
        let published_sync = sync_directory(
            published_path
                .parent()
                .expect("published run always has an artifact-root parent"),
        );
        let staging_sync = sync_directory(
            staging_path
                .parent()
                .expect("staging run always has a staging-root parent"),
        );
        unregister_active_workspace(&staging_path);
        self.staging_path = None;

        if let Err(source) = published_sync.and(staging_sync) {
            return Err(ArtifactPathError::PublicationDurabilityUncertain {
                path: published_path,
                source: Box::new(source),
            });
        }

        let reader_lease = open_shared_lease(
            &published_path.join(RUN_READER_LOCK_FILE),
            "open published-run reader lease",
            "lock published-run reader lease",
        )
        .map_err(
            |source| ArtifactPathError::PublicationPostCommitMaintenance {
                path: published_path.clone(),
                source: Box::new(source),
            },
        )?;
        let published = PublishedRun {
            root: self.root.clone(),
            path: published_path,
            _reader_lease: reader_lease,
        };
        prune_published_runs(&self.root).map_err(|source| {
            ArtifactPathError::PublicationPostCommitMaintenance {
                path: published.path.clone(),
                source: Box::new(source),
            }
        })?;
        Ok(published)
    }
}

impl Drop for RunWorkspace {
    fn drop(&mut self) {
        if let Some(staging_path) = self.staging_path.as_ref() {
            if let Ok(_manager_lock) = acquire_staging_manager_lock(&self.root) {
                let _ = fs::remove_dir_all(staging_path);
            }
            unregister_active_workspace(staging_path);
        }
    }
}

impl PublishedRun {
    /// Return the unique published run directory.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Return the approved output root containing this run.
    pub fn root(&self) -> &ApprovedRoot {
        &self.root
    }

    /// Read and verify this run's versioned manifest and artifact digests.
    pub fn manifest(&self) -> Result<RunManifest, ArtifactPathError> {
        validate_run_manifest(&self.path)
    }

    /// Commit an immutable latest generation and refresh legacy stable copies.
    ///
    /// The generation becomes authoritative through one atomic `current`
    /// pointer rename. Root-level stable copies are retained for compatibility;
    /// because that legacy file set cannot be swapped atomically, the next
    /// refresh first repairs it from the already committed generation.
    pub fn refresh_latest(&self, artifacts: &[LatestArtifact]) -> Result<(), ArtifactPathError> {
        let published_root = ApprovedRoot::existing(&self.path)?;
        let mut prepared: Vec<(PathBuf, PathBuf, ArtifactId, ArtifactId)> =
            Vec::with_capacity(artifacts.len());
        for artifact in artifacts {
            if prepared
                .iter()
                .any(|(_, _, _, destination)| destination == &artifact.destination)
            {
                return Err(ArtifactPathError::DuplicateLatestDestination {
                    id: artifact.destination.clone(),
                });
            }
            let source = published_root.prepare_file(artifact.source.as_str())?;
            match fs::symlink_metadata(&source) {
                Ok(metadata) if metadata.file_type().is_symlink() => {
                    return Err(ArtifactPathError::SymlinkComponent { path: source });
                }
                Ok(metadata) if !metadata.is_file() => {
                    return Err(ArtifactPathError::FileDestinationNotFile { path: source });
                }
                Ok(_) => {}
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                    return Err(ArtifactPathError::RequiredArtifactMissing { path: source });
                }
                Err(source_error) => {
                    return Err(ArtifactPathError::Io {
                        operation: "inspect published latest source",
                        path: source,
                        source: source_error,
                    });
                }
            }
            let destination = self.root.prepare_file(artifact.destination.as_str())?;
            prepared.push((
                source,
                destination,
                artifact.source.clone(),
                artifact.destination.clone(),
            ));
        }
        let run_manifest = self.manifest()?;
        maybe_mutate_latest_source_after_validation();

        let latest_root_path = self.root.prepare_dir(LATEST_DIRECTORY)?;
        let latest_root = ApprovedRoot::existing(&latest_root_path)?;
        latest_root.prepare_dir(LATEST_STAGING_DIRECTORY)?;
        latest_root.prepare_dir(LATEST_GENERATIONS_DIRECTORY)?;
        latest_root.prepare_dir(LATEST_QUARANTINE_DIRECTORY)?;
        // Allocation and lease acquisition are one short serialized operation.
        // Without this fence, another writer could observe the directory in the
        // interval before its lease exists and quarantine an active staging tree.
        let (generation, staging_path, staging_lease) = {
            let _latest_update_lock = acquire_latest_update_lock(&self.root)?;
            let (generation, staging_path) = allocate_latest_generation(&latest_root)?;
            let lease_result = (|| {
                create_reader_lease_file(&staging_path)?;
                let staging_lease_path = staging_path.join(LATEST_READER_LOCK_FILE);
                let staging_lease = OpenOptions::new()
                    .read(true)
                    .write(true)
                    .open(&staging_lease_path)
                    .map_err(|source| ArtifactPathError::Io {
                        operation: "open active latest-generation staging lease",
                        path: staging_lease_path.clone(),
                        source,
                    })?;
                FileExt::lock_exclusive(&staging_lease).map_err(|source| {
                    ArtifactPathError::Io {
                        operation: "lock active latest-generation staging lease",
                        path: staging_lease_path,
                        source,
                    }
                })?;
                Ok(staging_lease)
            })();
            match lease_result {
                Ok(staging_lease) => (generation, staging_path, staging_lease),
                Err(error) => {
                    let _ = quarantine_latest_path(&latest_root, &staging_path);
                    return Err(error);
                }
            }
        };
        let mut staging_lease = Some(staging_lease);

        // Copy, hash, and sync potentially large artifacts before entering the
        // serialized commit section. The staging lease prevents another
        // writer's recovery pass from quarantining this active generation.
        let preparation_result = (|| {
            let mut manifest_artifacts = Vec::with_capacity(prepared.len());
            for (source, _, source_id, destination_id) in &prepared {
                let staged = staging_path.join(destination_id.as_str());
                copy_new_synced(source, &staged, "stage latest generation artifact")?;
                let (size, sha256) = digest_file(&staged)?;
                let expected = run_manifest
                    .artifacts
                    .iter()
                    .find(|artifact| artifact.relative_path == source_id.as_str())
                    .ok_or_else(|| ArtifactPathError::ManifestIntegrity {
                        path: self.path.join(RUN_MANIFEST_FILE),
                        detail: format!(
                            "latest source `{source_id}` is not recorded in the run manifest"
                        ),
                    })?;
                if expected.size != size || expected.sha256 != sha256 {
                    return Err(ArtifactPathError::ManifestIntegrity {
                        path: source.clone(),
                        detail: format!(
                            "latest source `{source_id}` changed after run-manifest validation"
                        ),
                    });
                }
                manifest_artifacts.push(LatestManifestArtifact {
                    source_relative_path: source_id.as_str().to_owned(),
                    destination_relative_path: destination_id.as_str().to_owned(),
                    size,
                    sha256,
                });
            }
            manifest_artifacts.sort_by(|left, right| {
                left.destination_relative_path
                    .cmp(&right.destination_relative_path)
            });
            sync_artifact_tree(&staging_path)?;
            Ok(manifest_artifacts)
        })();
        let manifest_artifacts = match preparation_result {
            Ok(manifest_artifacts) => manifest_artifacts,
            Err(error) => {
                if let Some(lease) = staging_lease.take() {
                    let _ = FileExt::unlock(&lease);
                    drop(lease);
                }
                if let Err(cleanup) = quarantine_latest_path(&latest_root, &staging_path) {
                    return Err(ArtifactPathError::LatestStagingCleanup {
                        original: Box::new(error),
                        cleanup: Box::new(cleanup),
                        staging_path,
                    });
                }
                return Err(error);
            }
        };

        let generation_path = latest_root
            .path()
            .join(LATEST_GENERATIONS_DIRECTORY)
            .join(&generation);
        let mut generation_committed = false;
        let generation_result = (|| {
            let _latest_update_lock = acquire_latest_update_lock(&self.root)?;
            let predecessor = recover_latest_state_locked(&self.root, &latest_root)?;
            let observed_generation = predecessor
                .as_ref()
                .map(|snapshot| snapshot.manifest.generation.clone());
            if run_manifest.expected_latest_generation != observed_generation {
                return Err(ArtifactPathError::StaleLatestGeneration {
                    expected: run_manifest.expected_latest_generation.clone(),
                    observed: observed_generation,
                });
            }

            let manifest = LatestManifest {
                format_version: LATEST_MANIFEST_VERSION,
                producer_version: env!("CARGO_PKG_VERSION").to_owned(),
                generation: generation.clone(),
                predecessor_generation: predecessor
                    .as_ref()
                    .map(|snapshot| snapshot.manifest.generation.clone()),
                source_logical_id: run_manifest.logical_id.clone(),
                source_publication_id: run_manifest.publication_id.clone(),
                artifacts: manifest_artifacts.clone(),
            };
            write_json_file(
                &staging_path.join(LATEST_MANIFEST_FILE),
                &manifest,
                "write latest-generation manifest",
            )?;
            sync_directory(&staging_path)?;

            fs::rename(&staging_path, &generation_path).map_err(|source| {
                ArtifactPathError::Io {
                    operation: "publish latest generation",
                    path: generation_path.clone(),
                    source,
                }
            })?;
            record_durability_event("publish_generation");
            sync_directory(&latest_root.path().join(LATEST_STAGING_DIRECTORY))?;
            sync_directory(&latest_root.path().join(LATEST_GENERATIONS_DIRECTORY))?;
            if let Some(lease) = staging_lease.take() {
                let _ = FileExt::unlock(&lease);
                drop(lease);
            }

            let generation_manifest = validate_latest_manifest(&generation_path, &generation)?;
            let candidate = make_latest_snapshot(
                self.root.clone(),
                generation_path.clone(),
                generation_manifest,
            )?;
            let alias_transaction =
                install_stable_aliases_transactional(&self.root, &latest_root, &candidate)?;
            match commit_current_pointer(&latest_root, &generation) {
                Ok(()) => {
                    generation_committed = true;
                    alias_transaction.finish();
                }
                Err(PointerCommitFailure::BeforeCommit(pointer_error)) => {
                    return Err(alias_transaction.rollback(pointer_error));
                }
                Err(PointerCommitFailure::AfterCommit(durability_error)) => {
                    generation_committed = true;
                    alias_transaction.finish();
                    return Err(ArtifactPathError::LatestCommitDurabilityUncertain {
                        generation: generation.clone(),
                        source: Box::new(durability_error),
                    });
                }
            }
            prune_latest_generations(&latest_root, candidate.manifest()).map_err(|source| {
                ArtifactPathError::LatestRetentionAfterCommit {
                    generation: generation.clone(),
                    source: Box::new(source),
                }
            })?;
            Ok(())
        })();

        if generation_result.is_err() {
            if let Some(lease) = staging_lease.take() {
                let _ = FileExt::unlock(&lease);
                drop(lease);
            }
            if staging_path.exists() {
                quarantine_latest_path(&latest_root, &staging_path)?;
            } else if generation_path.exists() && !generation_committed {
                quarantine_latest_path(&latest_root, &generation_path)?;
            }
        }
        generation_result
    }
}

impl LatestSnapshot {
    /// Resolve and verify the committed generation without writing or locking.
    pub fn open(root: impl AsRef<Path>) -> Result<Self, ArtifactPathError> {
        let root = ApprovedRoot::existing(root)?;
        load_current_snapshot(&root, false)?.ok_or_else(|| {
            ArtifactPathError::LatestSnapshotUnavailable {
                path: root.path().join(LATEST_DIRECTORY).join(LATEST_CURRENT_FILE),
            }
        })
    }

    /// Repair legacy root-level aliases from the committed generation.
    ///
    /// This is idempotent and is also run automatically before every writer
    /// creates a new generation. The returned reader remains pinned to the
    /// generation used for recovery.
    pub fn recover_stable_aliases(root: impl AsRef<Path>) -> Result<Self, ArtifactPathError> {
        let root = ApprovedRoot::existing(root)?;
        let snapshot = recover_latest_for_writer(&root)?.ok_or_else(|| {
            ArtifactPathError::LatestSnapshotUnavailable {
                path: root.path().join(LATEST_DIRECTORY).join(LATEST_CURRENT_FILE),
            }
        })?;
        Ok(snapshot)
    }

    /// Return the pinned generation identity.
    pub fn generation(&self) -> &str {
        &self.manifest.generation
    }

    /// Return the immutable generation directory.
    pub fn path(&self) -> &Path {
        &self.generation_path
    }

    /// Return the approved artifact root containing this snapshot.
    pub fn root(&self) -> &ApprovedRoot {
        &self.root
    }

    /// Return the verified versioned manifest.
    pub fn manifest(&self) -> &LatestManifest {
        &self.manifest
    }

    /// Open one alias listed by this pinned generation.
    ///
    /// Callers that need integrity verification should prefer
    /// [`LatestSnapshot::read_artifact`], which verifies the exact bytes read
    /// against the pinned manifest.
    pub fn open_artifact(&self, id: &ArtifactId) -> Result<File, ArtifactPathError> {
        if !self
            .manifest
            .artifacts
            .iter()
            .any(|artifact| artifact.destination_relative_path == id.as_str())
        {
            return Err(ArtifactPathError::LatestArtifactNotInSnapshot { id: id.clone() });
        }
        let path = self.generation_path.join(id.as_str());
        open_snapshot_artifact(self, id).map_err(|source| ArtifactPathError::Io {
            operation: "open latest snapshot artifact",
            path,
            source,
        })
    }

    /// Read one alias from this pinned generation.
    pub fn read_artifact(&self, id: &ArtifactId) -> Result<Vec<u8>, ArtifactPathError> {
        let expected = self
            .manifest
            .artifacts
            .iter()
            .find(|artifact| artifact.destination_relative_path == id.as_str())
            .ok_or_else(|| ArtifactPathError::LatestArtifactNotInSnapshot { id: id.clone() })?;
        let mut file = self.open_artifact(id)?;
        let mut contents = Vec::new();
        file.read_to_end(&mut contents)
            .map_err(|source| ArtifactPathError::Io {
                operation: "read latest snapshot artifact",
                path: self.generation_path.join(id.as_str()),
                source,
            })?;
        let actual_digest = sha256_bytes(&contents);
        if contents.len() as u64 != expected.size || actual_digest != expected.sha256 {
            return Err(ArtifactPathError::CorruptGeneration {
                path: self.generation_path.join(id.as_str()),
                detail: "artifact bytes changed after snapshot validation".to_owned(),
            });
        }
        Ok(contents)
    }
}

fn acquire_latest_update_lock(root: &ApprovedRoot) -> Result<LatestUpdateLock, ArtifactPathError> {
    acquire_named_lock(
        root,
        LATEST_LOCK_FILE,
        "open latest-artifact lock",
        "lock latest artifacts",
    )
}

fn acquire_staging_manager_lock(
    root: &ApprovedRoot,
) -> Result<LatestUpdateLock, ArtifactPathError> {
    acquire_named_lock(
        root,
        STAGING_LOCK_FILE,
        "open run-staging lock",
        "lock run staging",
    )
}

fn acquire_named_lock(
    root: &ApprovedRoot,
    name: &str,
    open_operation: &'static str,
    lock_operation: &'static str,
) -> Result<LatestUpdateLock, ArtifactPathError> {
    let path = root.prepare_file(name)?;
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&path)
        .map_err(|source| ArtifactPathError::Io {
            operation: open_operation,
            path: path.clone(),
            source,
        })?;
    let started = Instant::now();

    loop {
        match FileExt::try_lock_exclusive(&file) {
            Ok(()) => return Ok(LatestUpdateLock { file }),
            Err(source)
                if source.kind() == std::io::ErrorKind::WouldBlock
                    && started.elapsed() < LATEST_LOCK_TIMEOUT =>
            {
                std::thread::sleep(LATEST_LOCK_POLL_INTERVAL);
            }
            Err(source) if source.kind() == std::io::ErrorKind::WouldBlock => {
                return Err(ArtifactPathError::LatestLockTimeout { path });
            }
            Err(source) => {
                return Err(ArtifactPathError::Io {
                    operation: lock_operation,
                    path,
                    source,
                });
            }
        }
    }
}

fn quarantine_abandoned_run_staging(
    root: &ApprovedRoot,
    staging_root: &Path,
) -> Result<(), ArtifactPathError> {
    let quarantine_root = root.prepare_dir(STAGING_QUARANTINE_DIRECTORY)?;
    let entries = fs::read_dir(staging_root).map_err(|source| ArtifactPathError::Io {
        operation: "list run staging for recovery",
        path: staging_root.to_path_buf(),
        source,
    })?;
    for entry in entries {
        let entry = entry.map_err(|source| ArtifactPathError::Io {
            operation: "inspect run staging entry",
            path: staging_root.to_path_buf(),
            source,
        })?;
        let staging_path = entry.path();
        if is_active_workspace(&staging_path) {
            continue;
        }
        let metadata =
            fs::symlink_metadata(&staging_path).map_err(|source| ArtifactPathError::Io {
                operation: "inspect run staging workspace",
                path: staging_path.clone(),
                source,
            })?;
        if metadata.file_type().is_symlink() || !metadata.is_dir() {
            quarantine_run_staging_path(staging_root, &quarantine_root, &staging_path)?;
            continue;
        }

        let workspace_lock_path = staging_path.join(WORKSPACE_LOCK_FILE);
        match fs::symlink_metadata(&workspace_lock_path) {
            Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => {
                quarantine_run_staging_path(staging_root, &quarantine_root, &staging_path)?;
                continue;
            }
            Ok(_) => {}
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
            Err(source) => {
                return Err(ArtifactPathError::Io {
                    operation: "inspect run-workspace lock",
                    path: workspace_lock_path,
                    source,
                });
            }
        }
        let workspace_lock = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(&workspace_lock_path)
            .map_err(|source| ArtifactPathError::Io {
                operation: "open staged run-workspace lock",
                path: workspace_lock_path.clone(),
                source,
            })?;
        match FileExt::try_lock_exclusive(&workspace_lock) {
            Ok(()) => {
                quarantine_run_staging_path(staging_root, &quarantine_root, &staging_path)?;
            }
            Err(source) if source.kind() == std::io::ErrorKind::WouldBlock => {}
            Err(source) => {
                return Err(ArtifactPathError::Io {
                    operation: "lock staged run workspace for recovery",
                    path: workspace_lock_path,
                    source,
                });
            }
        }
    }
    prune_quarantine_entries(&quarantine_root, RETAIN_QUARANTINE_ENTRIES)
}

fn quarantine_run_staging_path(
    staging_root: &Path,
    quarantine_root: &Path,
    staging_path: &Path,
) -> Result<(), ArtifactPathError> {
    let name = staging_path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("unreadable");
    let quarantine_path = quarantine_root.join(format!("{name}--{}", workspace_nonce()));
    fs::rename(staging_path, &quarantine_path).map_err(|source| ArtifactPathError::Io {
        operation: "quarantine abandoned run workspace",
        path: staging_path.to_path_buf(),
        source,
    })?;
    sync_directory(staging_root)?;
    sync_directory(quarantine_root)
}

fn allocate_latest_generation(
    latest_root: &ApprovedRoot,
) -> Result<(String, PathBuf), ArtifactPathError> {
    let staging_root = latest_root.prepare_dir(LATEST_STAGING_DIRECTORY)?;
    for _ in 0..MAX_ALLOCATION_ATTEMPTS {
        let generation = format!("generation-{}", workspace_nonce());
        let path = staging_root.join(&generation);
        match fs::create_dir(&path) {
            Ok(()) => return Ok((generation, path)),
            Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(source) => {
                return Err(ArtifactPathError::Io {
                    operation: "create latest staging generation",
                    path,
                    source,
                });
            }
        }
    }
    Err(ArtifactPathError::LatestTransactionAllocationExhausted)
}

fn quarantine_abandoned_latest_staging(
    latest_root: &ApprovedRoot,
) -> Result<(), ArtifactPathError> {
    let staging = latest_root.prepare_dir(LATEST_STAGING_DIRECTORY)?;
    let entries = fs::read_dir(&staging).map_err(|source| ArtifactPathError::Io {
        operation: "list abandoned latest staging",
        path: staging.clone(),
        source,
    })?;
    for entry in entries {
        let entry = entry.map_err(|source| ArtifactPathError::Io {
            operation: "inspect abandoned latest staging entry",
            path: staging.clone(),
            source,
        })?;
        let staging_path = entry.path();
        let metadata =
            fs::symlink_metadata(&staging_path).map_err(|source| ArtifactPathError::Io {
                operation: "inspect abandoned latest staging entry",
                path: staging_path.clone(),
                source,
            })?;
        if metadata.file_type().is_symlink() || !metadata.is_dir() {
            quarantine_latest_path(latest_root, &staging_path)?;
            continue;
        }

        let lease_path = staging_path.join(LATEST_READER_LOCK_FILE);
        let lease_metadata = match fs::symlink_metadata(&lease_path) {
            Ok(metadata) => metadata,
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
                quarantine_latest_path(latest_root, &staging_path)?;
                continue;
            }
            Err(source) => {
                return Err(ArtifactPathError::Io {
                    operation: "inspect latest-generation staging lease",
                    path: lease_path,
                    source,
                });
            }
        };
        if lease_metadata.file_type().is_symlink() || !lease_metadata.is_file() {
            quarantine_latest_path(latest_root, &staging_path)?;
            continue;
        }
        let lease = OpenOptions::new()
            .read(true)
            .write(true)
            .open(&lease_path)
            .map_err(|source| ArtifactPathError::Io {
                operation: "open latest-generation staging lease for recovery",
                path: lease_path.clone(),
                source,
            })?;
        match FileExt::try_lock_exclusive(&lease) {
            Ok(()) => quarantine_latest_path(latest_root, &staging_path)?,
            Err(source) if source.kind() == std::io::ErrorKind::WouldBlock => {}
            Err(source) => {
                return Err(ArtifactPathError::Io {
                    operation: "lock latest-generation staging lease for recovery",
                    path: lease_path,
                    source,
                });
            }
        }
    }
    Ok(())
}

fn quarantine_latest_path(
    latest_root: &ApprovedRoot,
    source_path: &Path,
) -> Result<(), ArtifactPathError> {
    let quarantine = latest_root.prepare_dir(LATEST_QUARANTINE_DIRECTORY)?;
    let source_name = source_path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("unreadable");
    let destination = quarantine.join(format!("{source_name}--{}", workspace_nonce()));
    fs::rename(source_path, &destination).map_err(|source| ArtifactPathError::Io {
        operation: "quarantine abandoned latest staging",
        path: source_path.to_path_buf(),
        source,
    })?;
    sync_directory(
        source_path
            .parent()
            .expect("latest staging entry always has a parent"),
    )?;
    sync_directory(&quarantine)?;
    prune_quarantine_entries(&quarantine, RETAIN_QUARANTINE_ENTRIES)
}

fn commit_current_pointer(
    latest_root: &ApprovedRoot,
    generation: &str,
) -> Result<(), PointerCommitFailure> {
    ArtifactId::new(generation.to_owned()).map_err(PointerCommitFailure::BeforeCommit)?;
    let temporary = latest_root
        .path()
        .join(format!(".current-{}", workspace_nonce()));
    let mut file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&temporary)
        .map_err(|source| {
            PointerCommitFailure::BeforeCommit(ArtifactPathError::Io {
                operation: "create latest pointer candidate",
                path: temporary.clone(),
                source,
            })
        })?;
    file.write_all(generation.as_bytes())
        .and_then(|()| file.write_all(b"\n"))
        .map_err(|source| {
            PointerCommitFailure::BeforeCommit(ArtifactPathError::Io {
                operation: "write latest pointer candidate",
                path: temporary.clone(),
                source,
            })
        })?;
    file.sync_all().map_err(|source| {
        PointerCommitFailure::BeforeCommit(ArtifactPathError::Io {
            operation: "sync latest pointer candidate",
            path: temporary.clone(),
            source,
        })
    })?;
    record_durability_event("sync_pointer_file");

    let current = latest_root.path().join(LATEST_CURRENT_FILE);
    match fs::symlink_metadata(&current) {
        Ok(metadata) if metadata.is_dir() => {
            let _ = fs::remove_file(&temporary);
            return Err(PointerCommitFailure::BeforeCommit(
                ArtifactPathError::FileDestinationNotFile { path: current },
            ));
        }
        Ok(_) => {}
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
        Err(source) => {
            let _ = fs::remove_file(&temporary);
            return Err(PointerCommitFailure::BeforeCommit(ArtifactPathError::Io {
                operation: "inspect current latest pointer",
                path: current,
                source,
            }));
        }
    }
    replace_file_atomically(&temporary, &current).map_err(|source| {
        PointerCommitFailure::BeforeCommit(ArtifactPathError::Io {
            operation: "commit latest pointer",
            path: current,
            source,
        })
    })?;
    record_durability_event("commit_pointer");
    sync_directory(latest_root.path()).map_err(PointerCommitFailure::AfterCommit)
}

fn recover_latest_for_writer(
    root: &ApprovedRoot,
) -> Result<Option<LatestSnapshot>, ArtifactPathError> {
    let _lock = acquire_latest_update_lock(root)?;
    let latest_path = root.prepare_dir(LATEST_DIRECTORY)?;
    let latest_root = ApprovedRoot::existing(latest_path)?;
    latest_root.prepare_dir(LATEST_STAGING_DIRECTORY)?;
    latest_root.prepare_dir(LATEST_GENERATIONS_DIRECTORY)?;
    latest_root.prepare_dir(LATEST_QUARANTINE_DIRECTORY)?;
    recover_latest_state_locked(root, &latest_root)
}

fn recover_latest_state_locked(
    root: &ApprovedRoot,
    latest_root: &ApprovedRoot,
) -> Result<Option<LatestSnapshot>, ArtifactPathError> {
    let (snapshot, needs_alias_refresh) = match load_current_snapshot(root, true) {
        Ok(Some(snapshot)) => {
            quarantine_generations_outside_committed_chain(latest_root, &snapshot.manifest)?;
            (Some(snapshot), true)
        }
        Ok(None) => (
            recover_current_from_generation_chain(root, latest_root)?,
            false,
        ),
        Err(error) if is_recoverable_pointer_error(&error) => (
            recover_current_from_generation_chain(root, latest_root)?,
            false,
        ),
        Err(error) => return Err(error),
    };
    if let Some(snapshot) = snapshot.as_ref() {
        reject_producer_downgrade(&snapshot.manifest.producer_version)?;
        if needs_alias_refresh {
            install_stable_aliases_transactional(root, latest_root, snapshot)?.finish();
        }
    }
    quarantine_abandoned_latest_staging(latest_root)?;
    Ok(snapshot)
}

fn quarantine_generations_outside_committed_chain(
    latest_root: &ApprovedRoot,
    committed: &LatestManifest,
) -> Result<(), ArtifactPathError> {
    let mut committed_chain = BTreeSet::new();
    let mut cursor = committed.clone();
    loop {
        committed_chain.insert(cursor.generation.clone());
        let Some(predecessor) = cursor.predecessor_generation.as_ref() else {
            break;
        };
        let cursor_path = latest_root
            .path()
            .join(LATEST_GENERATIONS_DIRECTORY)
            .join(&cursor.generation);
        if load_retention_boundary(&cursor_path, &cursor)?.is_some() {
            break;
        }
        let path = latest_root
            .path()
            .join(LATEST_GENERATIONS_DIRECTORY)
            .join(predecessor);
        cursor = validate_latest_manifest(&path, predecessor)?;
    }

    let generations = latest_root.path().join(LATEST_GENERATIONS_DIRECTORY);
    let entries = fs::read_dir(&generations).map_err(|source| ArtifactPathError::Io {
        operation: "list uncommitted latest generations",
        path: generations,
        source,
    })?;
    for entry in entries {
        let entry = entry.map_err(|source| ArtifactPathError::Io {
            operation: "inspect uncommitted latest generation",
            path: latest_root.path().join(LATEST_GENERATIONS_DIRECTORY),
            source,
        })?;
        let path = entry.path();
        let generation = entry
            .file_name()
            .to_str()
            .ok_or_else(|| ArtifactPathError::NonUtf8ArtifactPath { path: path.clone() })?
            .to_owned();
        if committed_chain.contains(&generation) {
            continue;
        }
        // The current pointer already anchors and validates the committed
        // chain. Everything else is uncommitted recovery material, so move it
        // without parsing attacker-controlled or crash-torn contents.
        quarantine_latest_path(latest_root, &path)?;
    }
    Ok(())
}

fn is_recoverable_pointer_error(error: &ArtifactPathError) -> bool {
    fn is_current(path: &Path) -> bool {
        path.file_name().and_then(|name| name.to_str()) == Some(LATEST_CURRENT_FILE)
    }

    match error {
        ArtifactPathError::InvalidLatestPointer { .. } => true,
        ArtifactPathError::LatestSnapshotUnavailable { path } => is_current(path),
        ArtifactPathError::SymlinkComponent { path }
        | ArtifactPathError::FileDestinationNotFile { path } => is_current(path),
        ArtifactPathError::Io {
            operation, path, ..
        } => operation.contains("latest snapshot pointer") && is_current(path),
        _ => false,
    }
}

fn recover_current_from_generation_chain(
    root: &ApprovedRoot,
    latest_root: &ApprovedRoot,
) -> Result<Option<LatestSnapshot>, ArtifactPathError> {
    let candidate = select_unique_generation_tip(root, latest_root)?;
    // A directory at `current` blocks replacement even when there is no
    // generation to recover. Isolate it before returning or committing.
    quarantine_directory_pointer_for_recovery(latest_root)?;
    let Some(candidate) = candidate else {
        return Ok(None);
    };
    reject_producer_downgrade(&candidate.manifest.producer_version)?;
    let alias_transaction = install_stable_aliases_transactional(root, latest_root, &candidate)?;
    match commit_current_pointer(latest_root, candidate.generation()) {
        Ok(()) => alias_transaction.finish(),
        Err(PointerCommitFailure::BeforeCommit(error)) => {
            return Err(alias_transaction.rollback(error));
        }
        Err(PointerCommitFailure::AfterCommit(error)) => {
            alias_transaction.finish();
            return Err(ArtifactPathError::LatestCommitDurabilityUncertain {
                generation: candidate.generation().to_owned(),
                source: Box::new(error),
            });
        }
    }
    Ok(Some(candidate))
}

fn quarantine_directory_pointer_for_recovery(
    latest_root: &ApprovedRoot,
) -> Result<(), ArtifactPathError> {
    let current = latest_root.path().join(LATEST_CURRENT_FILE);
    let metadata = match fs::symlink_metadata(&current) {
        Ok(metadata) => metadata,
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(source) => {
            return Err(ArtifactPathError::Io {
                operation: "inspect corrupt latest pointer for recovery",
                path: current,
                source,
            });
        }
    };
    if !metadata.is_dir() || metadata.file_type().is_symlink() {
        return Ok(());
    }
    let quarantine = latest_root.prepare_dir(LATEST_QUARANTINE_DIRECTORY)?;
    let destination = quarantine.join(format!("current-corrupt--{}", workspace_nonce()));
    fs::rename(&current, &destination).map_err(|source| ArtifactPathError::Io {
        operation: "quarantine corrupt latest pointer directory",
        path: current,
        source,
    })?;
    sync_directory(latest_root.path())?;
    sync_directory(&quarantine)
}

fn select_unique_generation_tip(
    root: &ApprovedRoot,
    latest_root: &ApprovedRoot,
) -> Result<Option<LatestSnapshot>, ArtifactPathError> {
    let generations_path = latest_root.path().join(LATEST_GENERATIONS_DIRECTORY);
    let mut entries = fs::read_dir(&generations_path)
        .map_err(|source| ArtifactPathError::Io {
            operation: "list latest generations for recovery",
            path: generations_path.clone(),
            source,
        })?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|source| ArtifactPathError::Io {
            operation: "inspect latest generation for recovery",
            path: generations_path.clone(),
            source,
        })?;
    entries.sort_by_key(|entry| entry.file_name());

    let mut manifests = BTreeMap::new();
    let mut retention_boundaries = BTreeSet::new();
    for entry in entries {
        let path = entry.path();
        let metadata = fs::symlink_metadata(&path).map_err(|source| ArtifactPathError::Io {
            operation: "inspect latest generation for recovery",
            path: path.clone(),
            source,
        })?;
        if metadata.file_type().is_symlink() {
            return Err(ArtifactPathError::SymlinkComponent { path });
        }
        if !metadata.is_dir() {
            return Err(ArtifactPathError::DirectoryComponentNotDirectory { path });
        }
        let generation = entry
            .file_name()
            .to_str()
            .ok_or_else(|| ArtifactPathError::NonUtf8ArtifactPath { path: path.clone() })?
            .to_owned();
        ArtifactId::new(generation.clone())?;
        let manifest = validate_latest_manifest(&path, &generation)?;
        if load_retention_boundary(&path, &manifest)?.is_some() {
            retention_boundaries.insert(generation.clone());
        }
        manifests.insert(generation, (path, manifest));
    }
    if manifests.is_empty() {
        return Ok(None);
    }

    let mut children: BTreeMap<String, Vec<String>> = BTreeMap::new();
    let mut predecessors = BTreeSet::new();
    for (generation, (_, manifest)) in &manifests {
        if retention_boundaries.contains(generation) {
            continue;
        }
        if let Some(predecessor) = manifest.predecessor_generation.as_ref() {
            let Some((_, predecessor_manifest)) = manifests.get(predecessor) else {
                return Err(ArtifactPathError::BrokenGenerationChain {
                    generation: generation.clone(),
                    predecessor: predecessor.clone(),
                });
            };
            reject_chain_downgrade(predecessor_manifest, manifest)?;
            children
                .entry(predecessor.clone())
                .or_default()
                .push(generation.clone());
            predecessors.insert(predecessor.clone());
        }
    }
    for (predecessor, children) in &children {
        if children.len() > 1 {
            return Err(ArtifactPathError::AmbiguousGenerationFork {
                predecessor: predecessor.clone(),
                children: children.clone(),
            });
        }
    }
    validate_generation_map_acyclic(&manifests, &retention_boundaries)?;

    let tips: Vec<_> = manifests
        .keys()
        .filter(|generation| !predecessors.contains(*generation))
        .cloned()
        .collect();
    if tips.len() != 1 {
        return Err(ArtifactPathError::AmbiguousGenerationTips { tips });
    }
    let tip = &tips[0];
    let (generation_path, manifest) = manifests
        .remove(tip)
        .expect("selected generation tip came from the manifest map");
    Ok(Some(make_latest_snapshot(
        root.clone(),
        generation_path,
        manifest,
    )?))
}

fn validate_generation_map_acyclic(
    manifests: &BTreeMap<String, (PathBuf, LatestManifest)>,
    retention_boundaries: &BTreeSet<String>,
) -> Result<(), ArtifactPathError> {
    let mut complete = BTreeSet::new();
    for generation in manifests.keys() {
        let mut chain = BTreeSet::new();
        let mut cursor = generation.as_str();
        while !complete.contains(cursor) {
            if !chain.insert(cursor.to_owned()) {
                return Err(ArtifactPathError::GenerationChainCycle {
                    generation: cursor.to_owned(),
                });
            }
            if retention_boundaries.contains(cursor) {
                break;
            }
            let Some(predecessor) = manifests
                .get(cursor)
                .and_then(|(_, manifest)| manifest.predecessor_generation.as_deref())
            else {
                break;
            };
            cursor = predecessor;
        }
        complete.extend(chain);
    }
    Ok(())
}

fn load_current_snapshot(
    root: &ApprovedRoot,
    allow_missing: bool,
) -> Result<Option<LatestSnapshot>, ArtifactPathError> {
    let latest_path = root.path().join(LATEST_DIRECTORY);
    match fs::symlink_metadata(&latest_path) {
        Ok(metadata) if metadata.file_type().is_symlink() => {
            return Err(ArtifactPathError::SymlinkComponent { path: latest_path });
        }
        Ok(metadata) if !metadata.is_dir() => {
            return Err(ArtifactPathError::DirectoryComponentNotDirectory { path: latest_path });
        }
        Ok(_) => {}
        Err(source) if source.kind() == std::io::ErrorKind::NotFound && allow_missing => {
            return Ok(None);
        }
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
            return Err(ArtifactPathError::LatestSnapshotUnavailable { path: latest_path });
        }
        Err(source) => {
            return Err(ArtifactPathError::Io {
                operation: "inspect latest snapshot root",
                path: latest_path,
                source,
            });
        }
    }
    let latest_root = ApprovedRoot::existing(&latest_path)?;
    let current = latest_root.path().join(LATEST_CURRENT_FILE);
    let metadata = match fs::symlink_metadata(&current) {
        Ok(metadata) if metadata.file_type().is_symlink() => {
            return Err(ArtifactPathError::SymlinkComponent { path: current });
        }
        Ok(metadata) if !metadata.is_file() => {
            return Err(ArtifactPathError::FileDestinationNotFile { path: current });
        }
        Ok(metadata) => metadata,
        Err(source) if source.kind() == std::io::ErrorKind::NotFound && allow_missing => {
            return Ok(None);
        }
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
            return Err(ArtifactPathError::LatestSnapshotUnavailable { path: current });
        }
        Err(source) => {
            return Err(ArtifactPathError::Io {
                operation: "inspect latest snapshot pointer",
                path: current,
                source,
            });
        }
    };
    if metadata.len() > 512 {
        return Err(ArtifactPathError::InvalidLatestPointer { path: current });
    }
    let generation = fs::read_to_string(&current)
        .map_err(|source| ArtifactPathError::Io {
            operation: "read latest snapshot pointer",
            path: current.clone(),
            source,
        })?
        .trim()
        .to_owned();
    ArtifactId::new(generation.clone()).map_err(|_| ArtifactPathError::InvalidLatestPointer {
        path: current.clone(),
    })?;

    let generation_path = latest_root
        .path()
        .join(LATEST_GENERATIONS_DIRECTORY)
        .join(&generation);
    match fs::symlink_metadata(&generation_path) {
        Ok(metadata) if metadata.file_type().is_symlink() => {
            return Err(ArtifactPathError::SymlinkComponent {
                path: generation_path,
            });
        }
        Ok(metadata) if !metadata.is_dir() => {
            return Err(ArtifactPathError::DirectoryComponentNotDirectory {
                path: generation_path,
            });
        }
        Ok(_) => {}
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
            return Err(ArtifactPathError::InvalidLatestPointer { path: current });
        }
        Err(source) => {
            return Err(ArtifactPathError::Io {
                operation: "inspect latest generation",
                path: generation_path,
                source,
            });
        }
    }
    let manifest = validate_latest_manifest(&generation_path, &generation)?;
    validate_predecessor_chain(&latest_root, &manifest)?;
    Ok(Some(make_latest_snapshot(
        root.clone(),
        generation_path,
        manifest,
    )?))
}

fn make_latest_snapshot(
    root: ApprovedRoot,
    generation_path: PathBuf,
    manifest: LatestManifest,
) -> Result<LatestSnapshot, ArtifactPathError> {
    let lease_path = generation_path.join(LATEST_READER_LOCK_FILE);
    let reader_lease = Arc::new(OpenOptions::new().read(true).open(&lease_path).map_err(
        |source| ArtifactPathError::Io {
            operation: "open latest-generation reader lease",
            path: lease_path.clone(),
            source,
        },
    )?);
    FileExt::lock_shared(reader_lease.as_ref()).map_err(|source| ArtifactPathError::Io {
        operation: "lock latest-generation reader lease",
        path: lease_path,
        source,
    })?;
    let source_run_lease = open_shared_lease(
        &root
            .path()
            .join(&manifest.source_publication_id)
            .join(RUN_READER_LOCK_FILE),
        "open latest source-run reader lease",
        "lock latest source-run reader lease",
    )?;
    #[cfg(unix)]
    let generation_directory = Arc::new(open_directory_no_follow(&generation_path).map_err(
        |source| ArtifactPathError::Io {
            operation: "pin latest generation directory",
            path: generation_path.clone(),
            source,
        },
    )?);
    Ok(LatestSnapshot {
        root,
        generation_path,
        manifest,
        _reader_lease: reader_lease,
        _source_run_lease: source_run_lease,
        #[cfg(unix)]
        generation_directory,
    })
}

fn open_shared_lease(
    path: &Path,
    open_operation: &'static str,
    lock_operation: &'static str,
) -> Result<Arc<File>, ArtifactPathError> {
    let lease = Arc::new(OpenOptions::new().read(true).open(path).map_err(|source| {
        ArtifactPathError::Io {
            operation: open_operation,
            path: path.to_path_buf(),
            source,
        }
    })?);
    FileExt::lock_shared(lease.as_ref()).map_err(|source| ArtifactPathError::Io {
        operation: lock_operation,
        path: path.to_path_buf(),
        source,
    })?;
    Ok(lease)
}

fn create_run_reader_lease_file(directory: &Path) -> Result<(), ArtifactPathError> {
    create_lease_file(
        directory,
        RUN_READER_LOCK_FILE,
        "create published-run reader lease",
    )
}

fn create_reader_lease_file(directory: &Path) -> Result<(), ArtifactPathError> {
    create_lease_file(
        directory,
        LATEST_READER_LOCK_FILE,
        "create latest-generation reader lease",
    )
}

fn create_lease_file(
    directory: &Path,
    name: &str,
    operation: &'static str,
) -> Result<(), ArtifactPathError> {
    let path = directory.join(name);
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create_new(true)
        .open(&path)
        .map_err(|source| ArtifactPathError::Io {
            operation,
            path: path.clone(),
            source,
        })?;
    file.sync_all().map_err(|source| ArtifactPathError::Io {
        operation: "sync latest-generation reader lease",
        path,
        source,
    })
}

fn prune_latest_generations(
    latest_root: &ApprovedRoot,
    current: &LatestManifest,
) -> Result<(), ArtifactPathError> {
    let generations_root = latest_root.path().join(LATEST_GENERATIONS_DIRECTORY);
    let mut chain = Vec::new();
    let mut cursor = current.clone();
    loop {
        let path = generations_root.join(&cursor.generation);
        let boundary = load_retention_boundary(&path, &cursor)?;
        chain.push((path, cursor.clone()));
        if boundary.is_some() {
            break;
        }
        let Some(predecessor) = cursor.predecessor_generation.as_ref() else {
            break;
        };
        let predecessor_path = generations_root.join(predecessor);
        cursor = validate_latest_manifest(&predecessor_path, predecessor)?;
    }
    if chain.len() <= RETAIN_LATEST_GENERATIONS {
        return Ok(());
    }

    // Retention is lease-aware and all-or-nothing. Keeping the complete tail
    // temporarily is preferable to stranding a leased generation outside the
    // retained chain.
    let mut leases = Vec::new();
    for (path, _) in &chain[RETAIN_LATEST_GENERATIONS..] {
        let lease_path = path.join(LATEST_READER_LOCK_FILE);
        let lease = OpenOptions::new()
            .read(true)
            .write(true)
            .open(&lease_path)
            .map_err(|source| ArtifactPathError::Io {
                operation: "open latest-generation retention lease",
                path: lease_path.clone(),
                source,
            })?;
        match FileExt::try_lock_exclusive(&lease) {
            Ok(()) => leases.push(lease),
            Err(source) if source.kind() == std::io::ErrorKind::WouldBlock => return Ok(()),
            Err(source) => {
                return Err(ArtifactPathError::Io {
                    operation: "lock latest generation for retention",
                    path: lease_path,
                    source,
                });
            }
        }
    }

    let (oldest_retained_path, oldest_retained) = &chain[RETAIN_LATEST_GENERATIONS - 1];
    let predecessor = oldest_retained
        .predecessor_generation
        .clone()
        .expect("a prunable chain has a predecessor after the retention boundary");
    let boundary = RetentionBoundary {
        format_version: 1,
        predecessor_generation: predecessor,
    };
    let boundary_path = oldest_retained_path.join(LATEST_RETENTION_BOUNDARY_FILE);
    let boundary_temp =
        oldest_retained_path.join(format!(".retention-boundary-{}", workspace_nonce()));
    write_json_file(
        &boundary_temp,
        &boundary,
        "write latest-generation retention boundary",
    )?;
    replace_file_atomically(&boundary_temp, &boundary_path).map_err(|source| {
        ArtifactPathError::Io {
            operation: "commit latest-generation retention boundary",
            path: boundary_path.clone(),
            source,
        }
    })?;
    sync_directory(oldest_retained_path)?;

    let quarantine = latest_root.prepare_dir(LATEST_QUARANTINE_DIRECTORY)?;
    let mut retired = Vec::new();
    for (path, _) in &chain[RETAIN_LATEST_GENERATIONS..] {
        let name = path
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("generation");
        let destination = quarantine.join(format!("retired-{name}--{}", workspace_nonce()));
        fs::rename(path, &destination).map_err(|source| ArtifactPathError::Io {
            operation: "retire latest generation",
            path: path.clone(),
            source,
        })?;
        retired.push(destination);
    }
    sync_directory(&generations_root)?;
    sync_directory(&quarantine)?;
    drop(leases);

    for path in retired {
        fs::remove_dir_all(&path).map_err(|source| ArtifactPathError::Io {
            operation: "delete retired latest generation",
            path,
            source,
        })?;
    }
    sync_directory(&quarantine)
}

fn prune_published_runs(root: &ApprovedRoot) -> Result<(), ArtifactPathError> {
    let mut runs = Vec::new();
    for entry in fs::read_dir(root.path()).map_err(|source| ArtifactPathError::Io {
        operation: "list published runs for retention",
        path: root.path().to_path_buf(),
        source,
    })? {
        let entry = entry.map_err(|source| ArtifactPathError::Io {
            operation: "inspect published run for retention",
            path: root.path().to_path_buf(),
            source,
        })?;
        let path = entry.path();
        let name = entry.file_name().to_string_lossy().into_owned();
        if name.starts_with('.') {
            continue;
        }
        let metadata = fs::symlink_metadata(&path).map_err(|source| ArtifactPathError::Io {
            operation: "inspect published run type for retention",
            path: path.clone(),
            source,
        })?;
        if metadata.file_type().is_symlink() || !metadata.is_dir() {
            continue;
        }
        if !path.join(RUN_MANIFEST_FILE).is_file() || !path.join(RUN_READER_LOCK_FILE).is_file() {
            continue;
        }
        // Never delete a directory merely because its name resembles a run.
        // Full manifest verification proves Mobench owns the complete tree.
        if validate_run_manifest(&path).is_err() {
            continue;
        }
        let order_key = name
            .rsplit_once("--")
            .map(|(_, nonce)| nonce.to_owned())
            .unwrap_or_else(|| name.clone());
        runs.push((order_key, path));
    }
    runs.sort_by(|left, right| right.0.cmp(&left.0));
    if runs.len() <= RETAIN_PUBLISHED_RUNS {
        return Ok(());
    }

    let quarantine = root.prepare_dir(RUN_RETENTION_QUARANTINE_DIRECTORY)?;
    for (_, path) in &runs[RETAIN_PUBLISHED_RUNS..] {
        let lease_path = path.join(RUN_READER_LOCK_FILE);
        let lease = OpenOptions::new()
            .read(true)
            .write(true)
            .open(&lease_path)
            .map_err(|source| ArtifactPathError::Io {
                operation: "open published-run retention lease",
                path: lease_path.clone(),
                source,
            })?;
        match FileExt::try_lock_exclusive(&lease) {
            Ok(()) => {}
            Err(source) if source.kind() == std::io::ErrorKind::WouldBlock => continue,
            Err(source) => {
                return Err(ArtifactPathError::Io {
                    operation: "lock published run for retention",
                    path: lease_path,
                    source,
                });
            }
        }
        let name = path
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("run");
        let retired = quarantine.join(format!("retired-{name}--{}", workspace_nonce()));
        fs::rename(path, &retired).map_err(|source| ArtifactPathError::Io {
            operation: "retire published run",
            path: path.clone(),
            source,
        })?;
        drop(lease);
        fs::remove_dir_all(&retired).map_err(|source| ArtifactPathError::Io {
            operation: "delete retired published run",
            path: retired,
            source,
        })?;
    }
    sync_directory(root.path())?;
    sync_directory(&quarantine)?;
    prune_quarantine_entries(&quarantine, RETAIN_QUARANTINE_ENTRIES)
}

fn prune_quarantine_entries(directory: &Path, retain: usize) -> Result<(), ArtifactPathError> {
    let mut entries = fs::read_dir(directory)
        .map_err(|source| ArtifactPathError::Io {
            operation: "list artifact quarantine for retention",
            path: directory.to_path_buf(),
            source,
        })?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|source| ArtifactPathError::Io {
            operation: "inspect artifact quarantine for retention",
            path: directory.to_path_buf(),
            source,
        })?;
    entries.sort_by_key(|entry| std::cmp::Reverse(entry.file_name()));
    for entry in entries.into_iter().skip(retain) {
        let path = entry.path();
        let metadata = fs::symlink_metadata(&path).map_err(|source| ArtifactPathError::Io {
            operation: "inspect quarantined artifact for deletion",
            path: path.clone(),
            source,
        })?;
        let result = if metadata.file_type().is_symlink() || metadata.is_file() {
            fs::remove_file(&path)
        } else if metadata.is_dir() {
            fs::remove_dir_all(&path)
        } else {
            fs::remove_file(&path)
        };
        result.map_err(|source| ArtifactPathError::Io {
            operation: "delete expired quarantined artifact",
            path,
            source,
        })?;
    }
    sync_directory(directory)
}

fn validate_predecessor_chain(
    latest_root: &ApprovedRoot,
    tip: &LatestManifest,
) -> Result<(), ArtifactPathError> {
    let mut visited = BTreeSet::new();
    let mut child = tip.clone();
    loop {
        if !visited.insert(child.generation.clone()) {
            return Err(ArtifactPathError::GenerationChainCycle {
                generation: child.generation,
            });
        }
        let Some(predecessor) = child.predecessor_generation.as_ref() else {
            return Ok(());
        };
        let child_path = latest_root
            .path()
            .join(LATEST_GENERATIONS_DIRECTORY)
            .join(&child.generation);
        if load_retention_boundary(&child_path, &child)?.is_some() {
            return Ok(());
        }
        let predecessor_path = latest_root
            .path()
            .join(LATEST_GENERATIONS_DIRECTORY)
            .join(predecessor);
        let predecessor_manifest = match fs::symlink_metadata(&predecessor_path) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                return Err(ArtifactPathError::SymlinkComponent {
                    path: predecessor_path,
                });
            }
            Ok(metadata) if !metadata.is_dir() => {
                return Err(ArtifactPathError::DirectoryComponentNotDirectory {
                    path: predecessor_path,
                });
            }
            Ok(_) => validate_latest_manifest(&predecessor_path, predecessor)?,
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
                return Err(ArtifactPathError::BrokenGenerationChain {
                    generation: child.generation,
                    predecessor: predecessor.clone(),
                });
            }
            Err(source) => {
                return Err(ArtifactPathError::Io {
                    operation: "inspect predecessor generation",
                    path: predecessor_path,
                    source,
                });
            }
        };
        reject_chain_downgrade(&predecessor_manifest, &child)?;
        child = predecessor_manifest;
    }
}

fn load_retention_boundary(
    generation_path: &Path,
    manifest: &LatestManifest,
) -> Result<Option<RetentionBoundary>, ArtifactPathError> {
    let path = generation_path.join(LATEST_RETENTION_BOUNDARY_FILE);
    let metadata = match fs::symlink_metadata(&path) {
        Ok(metadata) => metadata,
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(source) => {
            return Err(ArtifactPathError::Io {
                operation: "inspect latest-generation retention boundary",
                path,
                source,
            });
        }
    };
    if metadata.file_type().is_symlink() {
        return Err(ArtifactPathError::SymlinkComponent { path });
    }
    if !metadata.is_file() {
        return Err(ArtifactPathError::FileDestinationNotFile { path });
    }
    let body = fs::read(&path).map_err(|source| ArtifactPathError::Io {
        operation: "read latest-generation retention boundary",
        path: path.clone(),
        source,
    })?;
    let boundary: RetentionBoundary =
        serde_json::from_slice(&body).map_err(|source| ArtifactPathError::ManifestJson {
            path: path.clone(),
            source,
        })?;
    if boundary.format_version != 1
        || manifest.predecessor_generation.as_deref()
            != Some(boundary.predecessor_generation.as_str())
    {
        return Err(ArtifactPathError::CorruptGeneration {
            path,
            detail: "retention boundary does not match the manifest predecessor".to_owned(),
        });
    }
    Ok(Some(boundary))
}

fn reject_chain_downgrade(
    predecessor: &LatestManifest,
    child: &LatestManifest,
) -> Result<(), ArtifactPathError> {
    if parse_producer_version(&predecessor.producer_version)?
        > parse_producer_version(&child.producer_version)?
    {
        return Err(ArtifactPathError::ProducerDowngrade {
            existing: predecessor.producer_version.clone(),
            attempted: child.producer_version.clone(),
        });
    }
    Ok(())
}

fn reject_producer_downgrade(existing: &str) -> Result<(), ArtifactPathError> {
    let existing_version = parse_producer_version(existing)?;
    let producer_version = parse_producer_version(env!("CARGO_PKG_VERSION"))?;
    if existing_version > producer_version {
        return Err(ArtifactPathError::ProducerDowngrade {
            existing: existing.to_owned(),
            attempted: env!("CARGO_PKG_VERSION").to_owned(),
        });
    }
    Ok(())
}

fn install_stable_aliases_transactional(
    root: &ApprovedRoot,
    latest_root: &ApprovedRoot,
    snapshot: &LatestSnapshot,
) -> Result<StableAliasTransaction, ArtifactPathError> {
    let current_aliases: BTreeSet<ArtifactId> = match load_current_snapshot(root, true) {
        Ok(Some(current)) => current
            .manifest
            .artifacts
            .iter()
            .map(|artifact| ArtifactId::new(artifact.destination_relative_path.clone()))
            .collect::<Result<_, _>>()?,
        Ok(None) => BTreeSet::new(),
        Err(error) if is_recoverable_pointer_error(&error) => BTreeSet::new(),
        Err(error) => return Err(error),
    };
    let next_aliases: BTreeSet<ArtifactId> = snapshot
        .manifest
        .artifacts
        .iter()
        .map(|artifact| ArtifactId::new(artifact.destination_relative_path.clone()))
        .collect::<Result<_, _>>()?;

    let staging_root = latest_root.prepare_dir(LATEST_STAGING_DIRECTORY)?;
    let transaction_path = staging_root.join(format!("aliases-{}", workspace_nonce()));
    fs::create_dir(&transaction_path).map_err(|source| ArtifactPathError::Io {
        operation: "create stable-alias transaction",
        path: transaction_path.clone(),
        source,
    })?;
    let transaction_root = ApprovedRoot::existing(&transaction_path)?;
    let new_root = transaction_root.prepare_dir("new")?;
    let backup_root = transaction_root.prepare_dir("backup")?;

    let mut prepared = Vec::with_capacity(snapshot.manifest.artifacts.len());
    for artifact in &snapshot.manifest.artifacts {
        let id = ArtifactId::new(artifact.destination_relative_path.clone())?;
        let source = snapshot.generation_path.join(id.as_str());
        let destination = root.prepare_file(id.as_str())?;
        let staged = new_root.join(id.as_str());
        if let Err(error) = copy_new_synced(&source, &staged, "stage stable latest alias") {
            let _ = fs::remove_dir_all(&transaction_path);
            return Err(error);
        }
        prepared.push((staged, destination, id));
    }
    sync_artifact_tree(&transaction_path)?;

    let mut transaction = StableAliasTransaction {
        path: transaction_path,
        root_path: root.path().to_path_buf(),
        installed: Vec::new(),
        backups: Vec::new(),
    };

    // Aliases owned by the previous committed generation but omitted by the
    // candidate must disappear in the same rollback-capable transaction. Their
    // backups restore the old alias set if the pointer does not commit.
    for id in current_aliases.difference(&next_aliases) {
        let destination = root.prepare_file(id.as_str())?;
        match fs::symlink_metadata(&destination) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                let original = ArtifactPathError::SymlinkComponent { path: destination };
                return Err(transaction.rollback(original));
            }
            Ok(metadata) if !metadata.is_file() => {
                let original = ArtifactPathError::FileDestinationNotFile { path: destination };
                return Err(transaction.rollback(original));
            }
            Ok(_) => {
                let backup = backup_root.join(id.as_str());
                if let Err(source) = fs::rename(&destination, &backup) {
                    let original = ArtifactPathError::Io {
                        operation: "retire obsolete stable latest alias",
                        path: destination,
                        source,
                    };
                    return Err(transaction.rollback(original));
                }
                transaction.backups.push((destination, backup));
                if let Err(error) =
                    sync_directory(root.path()).and_then(|()| sync_directory(&backup_root))
                {
                    return Err(transaction.rollback(error));
                }
            }
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
            Err(source) => {
                let original = ArtifactPathError::Io {
                    operation: "inspect obsolete stable latest alias",
                    path: destination,
                    source,
                };
                return Err(transaction.rollback(original));
            }
        }
    }

    for (staged, destination, id) in prepared {
        match fs::symlink_metadata(&destination) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                let original = ArtifactPathError::SymlinkComponent { path: destination };
                return Err(transaction.rollback(original));
            }
            Ok(metadata) if !metadata.is_file() => {
                let original = ArtifactPathError::FileDestinationNotFile { path: destination };
                return Err(transaction.rollback(original));
            }
            Ok(_) => {
                let backup = backup_root.join(id.as_str());
                if let Err(source) = fs::rename(&destination, &backup) {
                    let original = ArtifactPathError::Io {
                        operation: "back up stable latest alias",
                        path: destination,
                        source,
                    };
                    return Err(transaction.rollback(original));
                }
                transaction.backups.push((destination.clone(), backup));
                if let Err(error) =
                    sync_directory(root.path()).and_then(|()| sync_directory(&backup_root))
                {
                    return Err(transaction.rollback(error));
                }
            }
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
            Err(source) => {
                let original = ArtifactPathError::Io {
                    operation: "inspect stable latest alias",
                    path: destination,
                    source,
                };
                return Err(transaction.rollback(original));
            }
        }

        if let Err(original) = maybe_fail_alias_install(transaction.installed.len(), &destination) {
            return Err(transaction.rollback(original));
        }
        if let Err(source) = fs::rename(&staged, &destination) {
            let original = ArtifactPathError::Io {
                operation: "install stable latest alias",
                path: destination,
                source,
            };
            return Err(transaction.rollback(original));
        }
        transaction.installed.push(destination);
        if let Err(error) = sync_directory(root.path()) {
            return Err(transaction.rollback(error));
        }
    }
    record_durability_event("install_aliases");
    Ok(transaction)
}

fn remove_installed_latest(installed: &[PathBuf]) -> Result<(), ArtifactPathError> {
    let mut first_error = None;
    for destination in installed.iter().rev() {
        match fs::remove_file(destination) {
            Ok(()) => {}
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
            Err(source) => {
                first_error.get_or_insert_with(|| ArtifactPathError::Io {
                    operation: "roll back installed latest artifact",
                    path: destination.clone(),
                    source,
                });
            }
        }
    }
    first_error.map_or(Ok(()), Err)
}

fn restore_latest_backups(backups: &[(PathBuf, PathBuf)]) -> Result<(), ArtifactPathError> {
    let mut first_error = None;
    for (destination, backup) in backups.iter().rev() {
        if let Err(source) = fs::rename(backup, destination) {
            first_error.get_or_insert_with(|| ArtifactPathError::Io {
                operation: "restore previous latest artifact",
                path: destination.clone(),
                source,
            });
        }
    }
    first_error.map_or(Ok(()), Err)
}

fn latest_update_failure(
    original: ArtifactPathError,
    installed: &[PathBuf],
    backups: &[(PathBuf, PathBuf)],
    recovery_path: PathBuf,
) -> ArtifactPathError {
    let remove_error = remove_installed_latest(installed).err();
    let restore_error = restore_latest_backups(backups).err();
    let rollback = remove_error.or(restore_error);

    match rollback {
        Some(rollback) => ArtifactPathError::LatestRollback {
            original: Box::new(original),
            rollback: Box::new(rollback),
            recovery_path,
        },
        None => original,
    }
}

fn validate_run_manifest(run_path: &Path) -> Result<RunManifest, ArtifactPathError> {
    let manifest_path = run_path.join(RUN_MANIFEST_FILE);
    let manifest: RunManifest = read_json_file(&manifest_path, "read run manifest")?;
    if manifest.format_version != RUN_MANIFEST_VERSION {
        return Err(ArtifactPathError::UnknownManifestVersion {
            path: manifest_path,
            found: manifest.format_version,
            supported: RUN_MANIFEST_VERSION,
        });
    }
    parse_producer_version(&manifest.producer_version)?;
    ArtifactId::new(manifest.logical_id.clone())?;
    ArtifactId::new(manifest.publication_id.clone())?;
    if let Some(expected) = manifest.expected_latest_generation.as_ref() {
        ArtifactId::new(expected.clone())?;
    }
    let expected_publication = run_path
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or_else(|| ArtifactPathError::NonUtf8ArtifactPath {
            path: run_path.to_path_buf(),
        })?;
    if manifest.publication_id != expected_publication {
        return Err(ArtifactPathError::ManifestIntegrity {
            path: manifest_path,
            detail: "publication identity does not match its directory".to_owned(),
        });
    }

    let actual = inspect_artifact_tree(run_path, &[RUN_MANIFEST_FILE, RUN_READER_LOCK_FILE])?;
    if manifest.artifacts != actual {
        return Err(ArtifactPathError::ManifestIntegrity {
            path: manifest_path,
            detail: "run artifact paths, sizes, or digests do not match".to_owned(),
        });
    }
    Ok(manifest)
}

fn validate_latest_manifest(
    generation_path: &Path,
    expected_generation: &str,
) -> Result<LatestManifest, ArtifactPathError> {
    let manifest_path = generation_path.join(LATEST_MANIFEST_FILE);
    let manifest: LatestManifest = read_json_file(&manifest_path, "read latest manifest")?;
    if manifest.format_version != LATEST_MANIFEST_VERSION {
        return Err(ArtifactPathError::UnknownManifestVersion {
            path: manifest_path,
            found: manifest.format_version,
            supported: LATEST_MANIFEST_VERSION,
        });
    }
    parse_producer_version(&manifest.producer_version)?;
    ArtifactId::new(manifest.generation.clone())?;
    ArtifactId::new(manifest.source_logical_id.clone())?;
    ArtifactId::new(manifest.source_publication_id.clone())?;
    if let Some(predecessor) = manifest.predecessor_generation.as_ref() {
        ArtifactId::new(predecessor.clone())?;
    }
    if manifest.generation != expected_generation {
        return Err(ArtifactPathError::CorruptGeneration {
            path: generation_path.to_path_buf(),
            detail: "manifest generation does not match current pointer".to_owned(),
        });
    }

    let actual = inspect_artifact_tree(
        generation_path,
        &[
            LATEST_MANIFEST_FILE,
            LATEST_READER_LOCK_FILE,
            LATEST_RETENTION_BOUNDARY_FILE,
        ],
    )?;
    let mut expected = Vec::with_capacity(manifest.artifacts.len());
    for artifact in &manifest.artifacts {
        ArtifactId::new(artifact.source_relative_path.clone())?;
        ArtifactId::new(artifact.destination_relative_path.clone())?;
        expected.push(ManifestArtifact {
            relative_path: artifact.destination_relative_path.clone(),
            size: artifact.size,
            sha256: artifact.sha256.clone(),
        });
    }
    expected.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
    if expected != actual {
        return Err(ArtifactPathError::CorruptGeneration {
            path: generation_path.to_path_buf(),
            detail: "generation artifact paths, sizes, or digests do not match".to_owned(),
        });
    }
    Ok(manifest)
}

fn parse_producer_version(version: &str) -> Result<Version, ArtifactPathError> {
    Version::parse(version).map_err(|source| ArtifactPathError::InvalidProducerVersion {
        version: version.to_owned(),
        source,
    })
}

fn read_json_file<T: for<'de> Deserialize<'de>>(
    path: &Path,
    operation: &'static str,
) -> Result<T, ArtifactPathError> {
    let metadata = fs::symlink_metadata(path).map_err(|source| ArtifactPathError::Io {
        operation,
        path: path.to_path_buf(),
        source,
    })?;
    if metadata.file_type().is_symlink() {
        return Err(ArtifactPathError::SymlinkComponent {
            path: path.to_path_buf(),
        });
    }
    if !metadata.is_file() {
        return Err(ArtifactPathError::FileDestinationNotFile {
            path: path.to_path_buf(),
        });
    }
    let file = File::open(path).map_err(|source| ArtifactPathError::Io {
        operation,
        path: path.to_path_buf(),
        source,
    })?;
    serde_json::from_reader(BufReader::new(file)).map_err(|source| {
        ArtifactPathError::ManifestJson {
            path: path.to_path_buf(),
            source,
        }
    })
}

fn write_json_file<T: Serialize>(
    path: &Path,
    value: &T,
    operation: &'static str,
) -> Result<(), ArtifactPathError> {
    let mut encoded =
        serde_json::to_vec_pretty(value).map_err(|source| ArtifactPathError::ManifestJson {
            path: path.to_path_buf(),
            source,
        })?;
    encoded.push(b'\n');
    let mut file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .map_err(|source| ArtifactPathError::Io {
            operation,
            path: path.to_path_buf(),
            source,
        })?;
    file.write_all(&encoded)
        .map_err(|source| ArtifactPathError::Io {
            operation,
            path: path.to_path_buf(),
            source,
        })?;
    file.sync_all().map_err(|source| ArtifactPathError::Io {
        operation: "sync manifest",
        path: path.to_path_buf(),
        source,
    })?;
    record_durability_event("sync_manifest");
    Ok(())
}

fn inspect_artifact_tree(
    root: &Path,
    excluded_relative_paths: &[&str],
) -> Result<Vec<ManifestArtifact>, ArtifactPathError> {
    let mut artifacts = Vec::new();
    inspect_artifact_tree_recursive(root, root, excluded_relative_paths, &mut artifacts)?;
    artifacts.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
    Ok(artifacts)
}

fn inspect_artifact_tree_recursive(
    root: &Path,
    directory: &Path,
    excluded_relative_paths: &[&str],
    artifacts: &mut Vec<ManifestArtifact>,
) -> Result<(), ArtifactPathError> {
    let mut entries = fs::read_dir(directory)
        .map_err(|source| ArtifactPathError::Io {
            operation: "list artifact directory",
            path: directory.to_path_buf(),
            source,
        })?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|source| ArtifactPathError::Io {
            operation: "inspect artifact directory entry",
            path: directory.to_path_buf(),
            source,
        })?;
    entries.sort_by_key(|entry| entry.file_name());
    for entry in entries {
        let path = entry.path();
        let metadata = fs::symlink_metadata(&path).map_err(|source| ArtifactPathError::Io {
            operation: "inspect artifact tree entry",
            path: path.clone(),
            source,
        })?;
        if metadata.file_type().is_symlink() {
            return Err(ArtifactPathError::SymlinkComponent { path });
        }
        if metadata.is_dir() {
            inspect_artifact_tree_recursive(root, &path, excluded_relative_paths, artifacts)?;
            continue;
        }
        if !metadata.is_file() {
            return Err(ArtifactPathError::FileDestinationNotFile { path });
        }
        reject_hardlinked_regular_file(&metadata, &path)?;
        let relative_path = manifest_relative_path(root, &path)?;
        if excluded_relative_paths.contains(&relative_path.as_str()) {
            continue;
        }
        let (size, sha256) = digest_file(&path)?;
        artifacts.push(ManifestArtifact {
            relative_path,
            size,
            sha256,
        });
    }
    Ok(())
}

fn manifest_relative_path(root: &Path, path: &Path) -> Result<String, ArtifactPathError> {
    let relative = path
        .strip_prefix(root)
        .map_err(|_| ArtifactPathError::InvalidRelativePath {
            path: path.to_path_buf(),
        })?;
    let mut components = Vec::new();
    for component in relative.components() {
        let std::path::Component::Normal(component) = component else {
            return Err(ArtifactPathError::InvalidRelativePath {
                path: relative.to_path_buf(),
            });
        };
        components.push(component.to_str().ok_or_else(|| {
            ArtifactPathError::NonUtf8ArtifactPath {
                path: path.to_path_buf(),
            }
        })?);
    }
    Ok(components.join("/"))
}

fn digest_file(path: &Path) -> Result<(u64, String), ArtifactPathError> {
    let metadata = fs::symlink_metadata(path).map_err(|source| ArtifactPathError::Io {
        operation: "inspect artifact for digest",
        path: path.to_path_buf(),
        source,
    })?;
    if metadata.file_type().is_symlink() {
        return Err(ArtifactPathError::SymlinkComponent {
            path: path.to_path_buf(),
        });
    }
    if !metadata.is_file() {
        return Err(ArtifactPathError::FileDestinationNotFile {
            path: path.to_path_buf(),
        });
    }
    reject_hardlinked_regular_file(&metadata, path)?;
    let mut file = File::open(path).map_err(|source| ArtifactPathError::Io {
        operation: "open artifact for digest",
        path: path.to_path_buf(),
        source,
    })?;
    let mut digest = Sha256::new();
    let mut buffer = [0_u8; 64 * 1024];
    loop {
        let read = file
            .read(&mut buffer)
            .map_err(|source| ArtifactPathError::Io {
                operation: "read artifact for digest",
                path: path.to_path_buf(),
                source,
            })?;
        if read == 0 {
            break;
        }
        digest.update(&buffer[..read]);
    }
    Ok((metadata.len(), format!("{:x}", digest.finalize())))
}

fn sha256_bytes(bytes: &[u8]) -> String {
    let mut digest = Sha256::new();
    digest.update(bytes);
    format!("{:x}", digest.finalize())
}

#[cfg(unix)]
fn open_directory_no_follow(path: &Path) -> std::io::Result<File> {
    use std::os::unix::fs::OpenOptionsExt;

    OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
        .open(path)
}

#[cfg(unix)]
fn open_snapshot_artifact(snapshot: &LatestSnapshot, id: &ArtifactId) -> std::io::Result<File> {
    use std::ffi::CString;
    use std::os::fd::{AsRawFd, FromRawFd};

    let name = CString::new(id.as_str())
        .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "name contains NUL"))?;
    // SAFETY: `generation_directory` pins a real directory descriptor and the
    // validated artifact ID is exactly one child component. O_NOFOLLOW rejects
    // a raced symlink at the leaf.
    let fd = unsafe {
        libc::openat(
            snapshot.generation_directory.as_raw_fd(),
            name.as_ptr(),
            libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
        )
    };
    if fd < 0 {
        return Err(std::io::Error::last_os_error());
    }
    // SAFETY: `openat` returned a new owned descriptor.
    let file = unsafe { File::from_raw_fd(fd) };
    if !file.metadata()?.is_file() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "snapshot artifact is not a regular file",
        ));
    }
    Ok(file)
}

#[cfg(not(unix))]
fn open_snapshot_artifact(snapshot: &LatestSnapshot, id: &ArtifactId) -> std::io::Result<File> {
    File::open(snapshot.generation_path.join(id.as_str()))
}

#[cfg(any(target_os = "macos", target_os = "ios"))]
fn rename_directory_noreplace(source: &Path, destination: &Path) -> std::io::Result<()> {
    use std::ffi::CString;
    use std::os::unix::ffi::OsStrExt;

    let source = CString::new(source.as_os_str().as_bytes()).map_err(|_| {
        std::io::Error::new(std::io::ErrorKind::InvalidInput, "source contains NUL")
    })?;
    let destination = CString::new(destination.as_os_str().as_bytes()).map_err(|_| {
        std::io::Error::new(std::io::ErrorKind::InvalidInput, "destination contains NUL")
    })?;
    // SAFETY: both C strings remain alive for the duration of the call. The
    // platform flag provides an atomic no-replace directory rename.
    let result =
        unsafe { libc::renamex_np(source.as_ptr(), destination.as_ptr(), libc::RENAME_EXCL) };
    if result == 0 {
        Ok(())
    } else {
        Err(std::io::Error::last_os_error())
    }
}

#[cfg(any(target_os = "linux", target_os = "android"))]
fn rename_directory_noreplace(source: &Path, destination: &Path) -> std::io::Result<()> {
    use std::ffi::CString;
    use std::os::unix::ffi::OsStrExt;

    let source = CString::new(source.as_os_str().as_bytes()).map_err(|_| {
        std::io::Error::new(std::io::ErrorKind::InvalidInput, "source contains NUL")
    })?;
    let destination = CString::new(destination.as_os_str().as_bytes()).map_err(|_| {
        std::io::Error::new(std::io::ErrorKind::InvalidInput, "destination contains NUL")
    })?;
    // SAFETY: the arguments are valid C strings and AT_FDCWD selects their
    // absolute paths. RENAME_NOREPLACE makes collision handling atomic.
    let result = unsafe {
        libc::syscall(
            libc::SYS_renameat2,
            libc::AT_FDCWD,
            source.as_ptr(),
            libc::AT_FDCWD,
            destination.as_ptr(),
            libc::RENAME_NOREPLACE,
        )
    };
    if result == 0 {
        Ok(())
    } else {
        Err(std::io::Error::last_os_error())
    }
}

#[cfg(not(any(
    target_os = "macos",
    target_os = "ios",
    target_os = "linux",
    target_os = "android",
    windows
)))]
fn rename_directory_noreplace(source: &Path, destination: &Path) -> std::io::Result<()> {
    // These targets retain the preflight check but cannot promise an atomic
    // no-replace rename through Rust's portable API.
    fs::rename(source, destination)
}

#[cfg(windows)]
fn rename_directory_noreplace(source: &Path, destination: &Path) -> std::io::Result<()> {
    use std::os::windows::ffi::OsStrExt;
    use windows_sys::Win32::Storage::FileSystem::{MOVEFILE_WRITE_THROUGH, MoveFileExW};

    let source: Vec<u16> = source
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    let destination: Vec<u16> = destination
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    // Without REPLACE_EXISTING, this is an atomic no-replace move. The
    // write-through flag requests durable completion before returning.
    let result = unsafe {
        MoveFileExW(
            source.as_ptr(),
            destination.as_ptr(),
            MOVEFILE_WRITE_THROUGH,
        )
    };
    if result != 0 {
        Ok(())
    } else {
        Err(std::io::Error::last_os_error())
    }
}

#[cfg(windows)]
fn replace_file_atomically(source: &Path, destination: &Path) -> std::io::Result<()> {
    use std::os::windows::ffi::OsStrExt;
    use windows_sys::Win32::Storage::FileSystem::{
        MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW,
    };

    let source: Vec<u16> = source
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    let destination: Vec<u16> = destination
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    // SAFETY: both UTF-16 buffers are NUL-terminated and alive for the call.
    let result = unsafe {
        MoveFileExW(
            source.as_ptr(),
            destination.as_ptr(),
            MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
        )
    };
    if result != 0 {
        Ok(())
    } else {
        Err(std::io::Error::last_os_error())
    }
}

#[cfg(not(windows))]
fn replace_file_atomically(source: &Path, destination: &Path) -> std::io::Result<()> {
    fs::rename(source, destination)
}

fn copy_new_synced(
    source: &Path,
    destination: &Path,
    operation: &'static str,
) -> Result<(), ArtifactPathError> {
    let source_metadata =
        fs::symlink_metadata(source).map_err(|source_error| ArtifactPathError::Io {
            operation,
            path: source.to_path_buf(),
            source: source_error,
        })?;
    if source_metadata.file_type().is_symlink() {
        return Err(ArtifactPathError::SymlinkComponent {
            path: source.to_path_buf(),
        });
    }
    if !source_metadata.is_file() {
        return Err(ArtifactPathError::FileDestinationNotFile {
            path: source.to_path_buf(),
        });
    }
    reject_hardlinked_regular_file(&source_metadata, source)?;
    let mut source_file = File::open(source).map_err(|source_error| ArtifactPathError::Io {
        operation,
        path: source.to_path_buf(),
        source: source_error,
    })?;
    let mut destination_file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(destination)
        .map_err(|source_error| ArtifactPathError::Io {
            operation,
            path: destination.to_path_buf(),
            source: source_error,
        })?;
    std::io::copy(&mut source_file, &mut destination_file).map_err(|source_error| {
        ArtifactPathError::Io {
            operation,
            path: destination.to_path_buf(),
            source: source_error,
        }
    })?;
    destination_file
        .sync_all()
        .map_err(|source_error| ArtifactPathError::Io {
            operation: "sync copied artifact",
            path: destination.to_path_buf(),
            source: source_error,
        })?;
    record_durability_event("sync_file");
    Ok(())
}

fn sync_artifact_tree(root: &Path) -> Result<(), ArtifactPathError> {
    sync_artifact_tree_recursive(root)
}

#[cfg(unix)]
fn reject_hardlinked_regular_file(
    metadata: &fs::Metadata,
    path: &Path,
) -> Result<(), ArtifactPathError> {
    use std::os::unix::fs::MetadataExt;

    if metadata.nlink() > 1 {
        return Err(ArtifactPathError::HardLinkedArtifact {
            path: path.to_path_buf(),
            links: metadata.nlink(),
        });
    }
    Ok(())
}

#[cfg(not(unix))]
fn reject_hardlinked_regular_file(
    _metadata: &fs::Metadata,
    _path: &Path,
) -> Result<(), ArtifactPathError> {
    Ok(())
}

fn sync_artifact_tree_recursive(directory: &Path) -> Result<(), ArtifactPathError> {
    let entries = fs::read_dir(directory)
        .map_err(|source| ArtifactPathError::Io {
            operation: "list artifact tree for sync",
            path: directory.to_path_buf(),
            source,
        })?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|source| ArtifactPathError::Io {
            operation: "inspect artifact tree entry for sync",
            path: directory.to_path_buf(),
            source,
        })?;
    for entry in entries {
        let path = entry.path();
        let metadata = fs::symlink_metadata(&path).map_err(|source| ArtifactPathError::Io {
            operation: "inspect artifact tree entry for sync",
            path: path.clone(),
            source,
        })?;
        if metadata.file_type().is_symlink() {
            return Err(ArtifactPathError::SymlinkComponent { path });
        }
        if metadata.is_dir() {
            sync_artifact_tree_recursive(&path)?;
        } else if metadata.is_file() {
            File::open(&path)
                .and_then(|file| file.sync_all())
                .map_err(|source| ArtifactPathError::Io {
                    operation: "sync artifact file",
                    path: path.clone(),
                    source,
                })?;
            record_durability_event("sync_file");
        } else {
            return Err(ArtifactPathError::FileDestinationNotFile { path });
        }
    }
    sync_directory(directory)
}

#[cfg(unix)]
fn sync_directory(path: &Path) -> Result<(), ArtifactPathError> {
    maybe_fail_directory_sync(path)?;
    File::open(path)
        .and_then(|directory| directory.sync_all())
        .map_err(|source| ArtifactPathError::Io {
            operation: "sync artifact directory",
            path: path.to_path_buf(),
            source,
        })?;
    record_durability_event("sync_directory");
    Ok(())
}

#[cfg(not(unix))]
fn sync_directory(_path: &Path) -> Result<(), ArtifactPathError> {
    maybe_fail_directory_sync(_path)?;
    // Rust's portable filesystem API does not expose a directory handle that
    // can be flushed on every non-Unix target. File contents are still synced;
    // power-loss durability of directory entries is therefore weaker there.
    record_durability_event("directory_sync_unavailable");
    Ok(())
}

#[cfg(test)]
thread_local! {
    static DURABILITY_EVENTS: std::cell::RefCell<Vec<&'static str>> = const {
        std::cell::RefCell::new(Vec::new())
    };
    static FAIL_ALIAS_INSTALL_AFTER: std::cell::Cell<Option<usize>> = const {
        std::cell::Cell::new(None)
    };
    static MUTATE_LATEST_SOURCE_AFTER_VALIDATION: std::cell::RefCell<Option<(PathBuf, Vec<u8>)>> =
        const { std::cell::RefCell::new(None) };
    static FAIL_DIRECTORY_SYNC_AFTER_EVENT: std::cell::Cell<Option<&'static str>> =
        const { std::cell::Cell::new(None) };
    static FAIL_NEXT_DIRECTORY_SYNC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

#[cfg(test)]
fn record_durability_event(event: &'static str) {
    DURABILITY_EVENTS.with(|events| events.borrow_mut().push(event));
    FAIL_DIRECTORY_SYNC_AFTER_EVENT.with(|target| {
        if target.get() == Some(event) {
            target.set(None);
            FAIL_NEXT_DIRECTORY_SYNC.with(|fail| fail.set(true));
        }
    });
}

#[cfg(not(test))]
fn record_durability_event(_event: &'static str) {}

#[cfg(test)]
fn maybe_fail_directory_sync(path: &Path) -> Result<(), ArtifactPathError> {
    let fail = FAIL_NEXT_DIRECTORY_SYNC.with(|fail| fail.replace(false));
    if fail {
        return Err(ArtifactPathError::Io {
            operation: "sync artifact directory",
            path: path.to_path_buf(),
            source: std::io::Error::other("injected post-commit directory sync failure"),
        });
    }
    Ok(())
}

#[cfg(not(test))]
fn maybe_fail_directory_sync(_path: &Path) -> Result<(), ArtifactPathError> {
    Ok(())
}

#[cfg(test)]
fn maybe_fail_alias_install(installed: usize, path: &Path) -> Result<(), ArtifactPathError> {
    let should_fail = FAIL_ALIAS_INSTALL_AFTER.with(|fail_after| {
        let should_fail = fail_after.get() == Some(installed);
        if should_fail {
            fail_after.set(None);
        }
        should_fail
    });
    if should_fail {
        return Err(ArtifactPathError::Io {
            operation: "install stable latest alias",
            path: path.to_path_buf(),
            source: std::io::Error::other("injected stable-alias failure"),
        });
    }
    Ok(())
}

#[cfg(test)]
fn maybe_mutate_latest_source_after_validation() {
    MUTATE_LATEST_SOURCE_AFTER_VALIDATION.with(|mutation| {
        if let Some((path, contents)) = mutation.borrow_mut().take() {
            fs::write(path, contents).expect("apply injected post-validation source mutation");
        }
    });
}

#[cfg(not(test))]
fn maybe_mutate_latest_source_after_validation() {}

#[cfg(not(test))]
fn maybe_fail_alias_install(_installed: usize, _path: &Path) -> Result<(), ArtifactPathError> {
    Ok(())
}

fn active_workspaces() -> &'static Mutex<BTreeSet<PathBuf>> {
    ACTIVE_WORKSPACES.get_or_init(|| Mutex::new(BTreeSet::new()))
}

fn register_active_workspace(path: &Path) {
    active_workspaces()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .insert(path.to_path_buf());
}

fn unregister_active_workspace(path: &Path) {
    active_workspaces()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .remove(path);
}

fn is_active_workspace(path: &Path) -> bool {
    active_workspaces()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .contains(path)
}

fn workspace_nonce() -> String {
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let sequence = WORKSPACE_SEQUENCE.fetch_add(1, Ordering::Relaxed);
    format!("{timestamp:x}-{:x}-{sequence:x}", std::process::id())
}

/// An existing directory approved as the boundary for artifact writes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApprovedRoot {
    path: PathBuf,
}

impl ApprovedRoot {
    /// Approve an existing, non-symlink directory and retain its canonical path.
    pub fn existing(path: impl AsRef<Path>) -> Result<Self, ArtifactPathError> {
        let path = path.as_ref();
        let metadata = fs::symlink_metadata(path).map_err(|source| ArtifactPathError::Io {
            operation: "inspect approved root",
            path: path.to_path_buf(),
            source,
        })?;
        if metadata.file_type().is_symlink() {
            return Err(ArtifactPathError::SymlinkComponent {
                path: path.to_path_buf(),
            });
        }
        if !metadata.is_dir() {
            return Err(ArtifactPathError::RootNotDirectory(path.to_path_buf()));
        }

        let path = fs::canonicalize(path).map_err(|source| ArtifactPathError::Io {
            operation: "canonicalize approved root",
            path: path.to_path_buf(),
            source,
        })?;
        Ok(Self { path })
    }

    /// Return the canonical approved root.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Resolve a relative directory beneath this root without creating it.
    ///
    /// Existing components must be real directories, never symbolic links.
    /// Once a missing component is reached there cannot be a deeper existing
    /// component, so the remaining validated path can be projected safely.
    pub fn project_dir(&self, relative: impl AsRef<Path>) -> Result<PathBuf, ArtifactPathError> {
        let relative = relative.as_ref();
        validate_relative_path(relative)?;

        let mut current = self.path.clone();
        for component in relative.components() {
            let std::path::Component::Normal(name) = component else {
                unreachable!("relative path was validated before directory projection")
            };
            current.push(name);

            match fs::symlink_metadata(&current) {
                Ok(metadata) if metadata.file_type().is_symlink() => {
                    return Err(ArtifactPathError::SymlinkComponent {
                        path: current.clone(),
                    });
                }
                Ok(metadata) if !metadata.is_dir() => {
                    return Err(ArtifactPathError::DirectoryComponentNotDirectory {
                        path: current.clone(),
                    });
                }
                Ok(_) => {}
                Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
                    return Ok(self.path.join(relative));
                }
                Err(source) => {
                    return Err(ArtifactPathError::Io {
                        operation: "inspect projected artifact directory",
                        path: current,
                        source,
                    });
                }
            }
        }

        Ok(current)
    }

    /// Prepare a relative directory, rejecting traversal and symlink components.
    pub fn prepare_dir(&self, relative: impl AsRef<Path>) -> Result<PathBuf, ArtifactPathError> {
        let relative = relative.as_ref();
        validate_relative_path(relative)?;
        prepare_directory_components(&self.path, relative)
    }

    /// Prepare a relative file's parent directories and validate its destination.
    ///
    /// This does not create or truncate the file. An existing destination must
    /// be a regular file and must not be a symlink.
    pub fn prepare_file(&self, relative: impl AsRef<Path>) -> Result<PathBuf, ArtifactPathError> {
        let relative = relative.as_ref();
        validate_relative_path(relative)?;
        if let Some(parent) = relative
            .parent()
            .filter(|parent| !parent.as_os_str().is_empty())
        {
            prepare_directory_components(&self.path, parent)?;
        }
        let path = self.path.join(relative);
        match fs::symlink_metadata(&path) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                Err(ArtifactPathError::SymlinkComponent { path })
            }
            Ok(metadata) if !metadata.is_file() => {
                Err(ArtifactPathError::FileDestinationNotFile { path })
            }
            Ok(_) => Ok(path),
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(path),
            Err(source) => Err(ArtifactPathError::Io {
                operation: "inspect artifact file",
                path,
                source,
            }),
        }
    }
}

/// Failure to approve a root or safely prepare one of its descendants.
#[derive(Debug, Error)]
pub enum ArtifactPathError {
    #[error("artifact identifier must be one non-empty relative path component: {value:?}")]
    InvalidArtifactId { value: String },
    #[error("could not allocate a unique workspace for logical run ID {logical_id}")]
    WorkspaceAllocationExhausted { logical_id: ArtifactId },
    #[error("artifact publication destination already exists: {path}")]
    PublicationDestinationExists { path: PathBuf },
    #[error("staged run already contains the reserved manifest path: {path}")]
    ReservedManifestPath { path: PathBuf },
    #[error("required staged artifact is missing: {path}")]
    RequiredArtifactMissing { path: PathBuf },
    #[error("latest artifact destination was requested more than once: {id}")]
    DuplicateLatestDestination { id: ArtifactId },
    #[error("could not allocate a unique latest-artifact transaction")]
    LatestTransactionAllocationExhausted,
    #[error("timed out waiting for the latest-artifact update lock at {path}")]
    LatestLockTimeout { path: PathBuf },
    #[error("no committed latest snapshot is available at {path}")]
    LatestSnapshotUnavailable { path: PathBuf },
    #[error("latest pointer is not one valid generation identity: {path}")]
    InvalidLatestPointer { path: PathBuf },
    #[error("latest snapshot does not contain alias {id}")]
    LatestArtifactNotInSnapshot { id: ArtifactId },
    #[error("latest generation is corrupt at {path}: {detail}")]
    CorruptGeneration { path: PathBuf, detail: String },
    #[error("latest-generation chain is broken at {generation}: missing {predecessor}")]
    BrokenGenerationChain {
        generation: String,
        predecessor: String,
    },
    #[error("latest-generation chain contains a cycle at {generation}")]
    GenerationChainCycle { generation: String },
    #[error("latest-generation chain forks after {predecessor} into {children:?}")]
    AmbiguousGenerationFork {
        predecessor: String,
        children: Vec<String>,
    },
    #[error("latest-generation recovery has ambiguous tips: {tips:?}")]
    AmbiguousGenerationTips { tips: Vec<String> },
    #[error(
        "published run has stale latest-generation token: expected {expected:?}, observed {observed:?}"
    )]
    StaleLatestGeneration {
        expected: Option<String>,
        observed: Option<String>,
    },
    #[error("refusing latest-generation producer downgrade from {existing} to {attempted}")]
    ProducerDowngrade { existing: String, attempted: String },
    #[error("invalid artifact producer version {version:?}: {source}")]
    InvalidProducerVersion {
        version: String,
        #[source]
        source: semver::Error,
    },
    #[error("unsupported manifest version {found} at {path}; supported version is {supported}")]
    UnknownManifestVersion {
        path: PathBuf,
        found: u32,
        supported: u32,
    },
    #[error("artifact manifest integrity check failed at {path}: {detail}")]
    ManifestIntegrity { path: PathBuf, detail: String },
    #[error("could not encode or decode artifact manifest at {path}: {source}")]
    ManifestJson {
        path: PathBuf,
        #[source]
        source: serde_json::Error,
    },
    #[error(
        "latest-artifact update failed ({original}) and rollback was incomplete ({rollback}); recovery material retained at {recovery_path}"
    )]
    LatestRollback {
        original: Box<ArtifactPathError>,
        rollback: Box<ArtifactPathError>,
        /// Transaction directory retained with any unrestored backups.
        recovery_path: PathBuf,
    },
    #[error(
        "latest-generation preparation failed ({original}) and staging cleanup failed ({cleanup}) at {staging_path}"
    )]
    LatestStagingCleanup {
        original: Box<ArtifactPathError>,
        cleanup: Box<ArtifactPathError>,
        staging_path: PathBuf,
    },
    #[error("run is committed at {path}, but directory durability is uncertain: {source}")]
    PublicationDurabilityUncertain {
        path: PathBuf,
        #[source]
        source: Box<ArtifactPathError>,
    },
    #[error("run is committed at {path}, but post-commit retention maintenance failed: {source}")]
    PublicationPostCommitMaintenance {
        path: PathBuf,
        #[source]
        source: Box<ArtifactPathError>,
    },
    #[error(
        "latest generation {generation} is committed, but pointer durability is uncertain: {source}"
    )]
    LatestCommitDurabilityUncertain {
        generation: String,
        #[source]
        source: Box<ArtifactPathError>,
    },
    #[error("latest generation {generation} is committed, but retention failed: {source}")]
    LatestRetentionAfterCommit {
        generation: String,
        #[source]
        source: Box<ArtifactPathError>,
    },
    #[error("approved artifact root is not a directory: {0}")]
    RootNotDirectory(PathBuf),
    #[error(
        "artifact child path must be a non-empty relative path without parent traversal: {path}"
    )]
    InvalidRelativePath { path: PathBuf },
    #[error("artifact path component is a symbolic link: {path}")]
    SymlinkComponent { path: PathBuf },
    #[error("artifact directory component is not a directory: {path}")]
    DirectoryComponentNotDirectory { path: PathBuf },
    #[error("artifact file destination is not a regular file: {path}")]
    FileDestinationNotFile { path: PathBuf },
    #[error("artifact file has {links} hard links and is not publication-private: {path}")]
    HardLinkedArtifact { path: PathBuf, links: u64 },
    #[error("artifact path is not valid UTF-8 and cannot be recorded in a manifest: {path:?}")]
    NonUtf8ArtifactPath { path: PathBuf },
    #[error("failed to {operation} at {path}: {source}")]
    Io {
        operation: &'static str,
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
}

fn validate_relative_path(path: &Path) -> Result<(), ArtifactPathError> {
    if path.as_os_str().is_empty()
        || path
            .components()
            .any(|component| !matches!(component, std::path::Component::Normal(_)))
    {
        return Err(ArtifactPathError::InvalidRelativePath {
            path: path.to_path_buf(),
        });
    }
    Ok(())
}

fn prepare_directory_components(
    root: &Path,
    relative: &Path,
) -> Result<PathBuf, ArtifactPathError> {
    let mut current = root.to_path_buf();

    for component in relative.components() {
        let std::path::Component::Normal(name) = component else {
            unreachable!("relative path was validated before directory preparation")
        };
        current.push(name);

        match fs::symlink_metadata(&current) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                return Err(ArtifactPathError::SymlinkComponent {
                    path: current.clone(),
                });
            }
            Ok(metadata) if !metadata.is_dir() => {
                return Err(ArtifactPathError::DirectoryComponentNotDirectory {
                    path: current.clone(),
                });
            }
            Ok(_) => {}
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
                match fs::create_dir(&current) {
                    Ok(()) => {}
                    Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => {
                        match fs::symlink_metadata(&current) {
                            Ok(metadata) if metadata.file_type().is_symlink() => {
                                return Err(ArtifactPathError::SymlinkComponent {
                                    path: current.clone(),
                                });
                            }
                            Ok(metadata) if !metadata.is_dir() => {
                                return Err(ArtifactPathError::DirectoryComponentNotDirectory {
                                    path: current.clone(),
                                });
                            }
                            Ok(_) => {}
                            Err(source) => {
                                return Err(ArtifactPathError::Io {
                                    operation: "inspect raced artifact directory",
                                    path: current.clone(),
                                    source,
                                });
                            }
                        }
                    }
                    Err(source) => {
                        return Err(ArtifactPathError::Io {
                            operation: "create artifact directory",
                            path: current.clone(),
                            source,
                        });
                    }
                }
            }
            Err(source) => {
                return Err(ArtifactPathError::Io {
                    operation: "inspect artifact directory",
                    path: current.clone(),
                    source,
                });
            }
        }
    }

    Ok(current)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn artifact_id_rejects_an_empty_component() {
        assert!(matches!(
            ArtifactId::new(""),
            Err(ArtifactPathError::InvalidArtifactId { .. })
        ));
    }

    #[test]
    fn artifact_id_rejects_values_that_are_not_one_normal_path_component() {
        for invalid in [
            ".",
            "..",
            "/absolute",
            "nested/child",
            r"nested\child",
            r"C:\absolute",
        ] {
            assert!(
                matches!(
                    ArtifactId::new(invalid),
                    Err(ArtifactPathError::InvalidArtifactId { .. })
                ),
                "accepted invalid artifact ID {invalid:?}"
            );
        }
    }

    #[test]
    fn repeated_run_workspace_allocations_are_isolated() {
        let temp = tempfile::tempdir().expect("tempdir");
        let logical_id = ArtifactId::new("android-sample").expect("valid logical ID");

        let first = RunWorkspace::allocate(temp.path(), &logical_id).expect("first workspace");
        let second = RunWorkspace::allocate(temp.path(), &logical_id).expect("second workspace");

        assert_ne!(first.staging_path(), second.staging_path());
        assert_ne!(first.published_path(), second.published_path());
        assert!(first.staging_path().is_dir());
        assert!(second.staging_path().is_dir());
        assert!(!first.published_path().exists());
        assert!(!second.published_path().exists());
    }

    #[test]
    fn concurrent_run_workspace_allocations_are_isolated() {
        use std::collections::BTreeSet;
        use std::sync::{Arc, Barrier};

        let temp = tempfile::tempdir().expect("tempdir");
        let root = Arc::new(temp.path().to_path_buf());
        let barrier = Arc::new(Barrier::new(8));
        let handles: Vec<_> = (0..8)
            .map(|_| {
                let root = Arc::clone(&root);
                let barrier = Arc::clone(&barrier);
                std::thread::spawn(move || {
                    let logical_id = ArtifactId::new("android-sample").expect("valid logical ID");
                    barrier.wait();
                    let workspace =
                        RunWorkspace::allocate(root.as_ref(), &logical_id).expect("workspace");
                    (
                        workspace.staging_path().to_path_buf(),
                        workspace.published_path().to_path_buf(),
                    )
                })
            })
            .collect();

        let paths: Vec<_> = handles
            .into_iter()
            .map(|handle| handle.join().expect("allocation thread"))
            .collect();
        let staging_paths: BTreeSet<_> = paths.iter().map(|(path, _)| path).collect();
        let published_paths: BTreeSet<_> = paths.iter().map(|(_, path)| path).collect();

        assert_eq!(staging_paths.len(), paths.len());
        assert_eq!(published_paths.len(), paths.len());
    }

    #[test]
    fn repeated_published_runs_do_not_inherit_stale_artifacts() {
        let temp = tempfile::tempdir().expect("tempdir");
        let logical_id = ArtifactId::new("android-sample").expect("valid logical ID");
        let required = [
            ArtifactId::new("profile.json").expect("valid profile ID"),
            ArtifactId::new("summary.md").expect("valid summary ID"),
        ];
        let first = RunWorkspace::allocate(temp.path(), &logical_id).expect("first workspace");
        fs::write(first.staging_path().join("profile.json"), "first profile")
            .expect("write first profile");
        fs::write(first.staging_path().join("summary.md"), "first summary")
            .expect("write first summary");
        fs::write(first.staging_path().join("stale.data"), "stale").expect("write stale artifact");
        let first = first.publish(&required).expect("publish first run");

        let second = RunWorkspace::allocate(temp.path(), &logical_id).expect("second workspace");
        fs::write(second.staging_path().join("profile.json"), "second profile")
            .expect("write second profile");
        fs::write(second.staging_path().join("summary.md"), "second summary")
            .expect("write second summary");
        let second = second.publish(&required).expect("publish second run");

        assert_ne!(first.path(), second.path());
        assert!(first.path().join("stale.data").is_file());
        assert!(!second.path().join("stale.data").exists());
    }

    #[cfg(unix)]
    #[test]
    fn run_workspace_rejects_a_symlink_publication_collision() {
        use std::os::unix::fs::symlink;

        let temp = tempfile::tempdir().expect("tempdir");
        let outside = tempfile::tempdir().expect("outside tempdir");
        let logical_id = ArtifactId::new("android-sample").expect("valid logical ID");
        let workspace =
            RunWorkspace::allocate(temp.path(), &logical_id).expect("allocate workspace");
        fs::write(workspace.staging_path().join("profile.json"), "complete")
            .expect("write staged manifest");
        symlink(outside.path(), workspace.published_path()).expect("create collision symlink");

        let required = [ArtifactId::new("profile.json").expect("valid required file")];
        let error = workspace
            .publish(&required)
            .expect_err("reject symlink collision");

        assert!(matches!(error, ArtifactPathError::SymlinkComponent { .. }));
        assert!(outside.path().is_dir());
        assert!(!outside.path().join("profile.json").exists());
    }

    #[test]
    fn incomplete_run_workspace_does_not_replace_latest_artifacts() {
        let temp = tempfile::tempdir().expect("tempdir");
        fs::write(temp.path().join("profile.json"), "old profile").expect("seed latest profile");
        fs::write(temp.path().join("summary.md"), "old summary").expect("seed latest summary");
        let logical_id = ArtifactId::new("android-sample").expect("valid logical ID");
        let workspace =
            RunWorkspace::allocate(temp.path(), &logical_id).expect("allocate workspace");
        let published_path = workspace.published_path().to_path_buf();
        fs::write(workspace.staging_path().join("profile.json"), "new profile")
            .expect("write staged profile");
        let required = [
            ArtifactId::new("profile.json").expect("valid profile ID"),
            ArtifactId::new("summary.md").expect("valid summary ID"),
        ];

        let error = workspace
            .publish(&required)
            .expect_err("reject incomplete run");

        assert!(matches!(
            error,
            ArtifactPathError::RequiredArtifactMissing { .. }
        ));
        assert!(!published_path.exists());
        assert_eq!(
            fs::read_to_string(temp.path().join("profile.json")).expect("read latest profile"),
            "old profile"
        );
        assert_eq!(
            fs::read_to_string(temp.path().join("summary.md")).expect("read latest summary"),
            "old summary"
        );
    }

    #[test]
    fn published_run_refreshes_stable_latest_artifacts() {
        let temp = tempfile::tempdir().expect("tempdir");
        let logical_id = ArtifactId::new("android-sample").expect("valid logical ID");
        let workspace =
            RunWorkspace::allocate(temp.path(), &logical_id).expect("allocate workspace");
        fs::write(workspace.staging_path().join("profile.json"), "new profile")
            .expect("write staged profile");
        fs::write(workspace.staging_path().join("summary.md"), "new summary")
            .expect("write staged summary");
        let required = [
            ArtifactId::new("profile.json").expect("valid profile ID"),
            ArtifactId::new("summary.md").expect("valid summary ID"),
        ];

        let published = workspace.publish(&required).expect("publish complete run");
        published
            .refresh_latest(&[
                LatestArtifact::same(required[0].clone()),
                LatestArtifact::same(required[1].clone()),
            ])
            .expect("refresh latest artifacts");

        assert!(published.path().join("profile.json").is_file());
        assert!(published.path().join("summary.md").is_file());
        assert_eq!(
            fs::read_to_string(temp.path().join("profile.json")).expect("read latest profile"),
            "new profile"
        );
        assert_eq!(
            fs::read_to_string(temp.path().join("summary.md")).expect("read latest summary"),
            "new summary"
        );
    }

    #[test]
    fn latest_refresh_removes_aliases_omitted_by_the_next_generation() {
        let temp = tempfile::tempdir().expect("tempdir");
        let first = publish_pair(temp.path(), "first-run", "first");
        refresh_pair(&first).expect("refresh initial aliases");
        assert!(temp.path().join("summary.md").is_file());

        let logical_id = ArtifactId::new("profile-only-run").expect("logical ID");
        let workspace = RunWorkspace::allocate(temp.path(), &logical_id).expect("workspace");
        fs::write(workspace.staging_path().join("profile.json"), "second").expect("write profile");
        let profile = ArtifactId::new("profile.json").expect("profile ID");
        let published = workspace
            .publish(std::slice::from_ref(&profile))
            .expect("publish profile-only run");
        published
            .refresh_latest(&[LatestArtifact::same(profile)])
            .expect("refresh profile-only aliases");

        assert_eq!(
            fs::read_to_string(temp.path().join("profile.json")).expect("profile alias"),
            "second"
        );
        assert!(
            !temp.path().join("summary.md").exists(),
            "obsolete alias survived the generation change"
        );
    }

    #[test]
    fn latest_generation_retention_keeps_a_bounded_valid_chain() {
        let temp = tempfile::tempdir().expect("tempdir");
        for index in 0..(RETAIN_LATEST_GENERATIONS + 4) {
            let published = publish_pair(
                temp.path(),
                &format!("retained-run-{index}"),
                &format!("receipt-{index}"),
            );
            refresh_pair(&published).expect("refresh retained generation");
        }

        let generations = temp
            .path()
            .join(LATEST_DIRECTORY)
            .join(LATEST_GENERATIONS_DIRECTORY);
        assert_eq!(
            fs::read_dir(&generations)
                .expect("list retained generations")
                .count(),
            RETAIN_LATEST_GENERATIONS
        );
        let snapshot = LatestSnapshot::open(temp.path()).expect("open retained latest snapshot");
        assert_eq!(
            snapshot
                .read_artifact(&ArtifactId::new("profile.json").expect("profile ID"))
                .expect("read retained latest artifact"),
            format!("receipt-{}", RETAIN_LATEST_GENERATIONS + 3).as_bytes()
        );
        validate_predecessor_chain(
            &ApprovedRoot::existing(temp.path().join(LATEST_DIRECTORY)).expect("open latest root"),
            snapshot.manifest(),
        )
        .expect("retained predecessor chain remains valid");
    }

    #[test]
    fn latest_generation_retention_defers_while_an_old_reader_is_leased() {
        let temp = tempfile::tempdir().expect("tempdir");
        let first = publish_pair(temp.path(), "leased-run-0", "receipt-0");
        refresh_pair(&first).expect("refresh first generation");
        let old_reader = LatestSnapshot::open(temp.path()).expect("lease first generation");

        for index in 1..=RETAIN_LATEST_GENERATIONS {
            let published = publish_pair(
                temp.path(),
                &format!("leased-run-{index}"),
                &format!("receipt-{index}"),
            );
            refresh_pair(&published).expect("refresh while old reader is leased");
        }
        let generations = temp
            .path()
            .join(LATEST_DIRECTORY)
            .join(LATEST_GENERATIONS_DIRECTORY);
        assert_eq!(
            fs::read_dir(&generations)
                .expect("list deferred generations")
                .count(),
            RETAIN_LATEST_GENERATIONS + 1
        );
        assert_eq!(
            old_reader
                .read_artifact(&ArtifactId::new("profile.json").expect("profile ID"))
                .expect("read leased generation"),
            b"receipt-0"
        );
        drop(old_reader);

        let final_run = publish_pair(temp.path(), "leased-run-final", "receipt-final");
        refresh_pair(&final_run).expect("refresh after releasing old reader");
        assert_eq!(
            fs::read_dir(&generations)
                .expect("list pruned generations")
                .count(),
            RETAIN_LATEST_GENERATIONS
        );
    }

    #[test]
    fn published_run_retention_is_bounded_and_defers_leased_runs() {
        let temp = tempfile::tempdir().expect("tempdir");
        let leased = publish_pair(temp.path(), "published-run-0", "receipt-0");
        for index in 1..=RETAIN_PUBLISHED_RUNS {
            drop(publish_pair(
                temp.path(),
                &format!("published-run-{index}"),
                &format!("receipt-{index}"),
            ));
        }

        let count_runs = || {
            fs::read_dir(temp.path())
                .expect("list artifact root")
                .filter_map(Result::ok)
                .filter(|entry| entry.path().join(RUN_MANIFEST_FILE).is_file())
                .count()
        };
        assert_eq!(count_runs(), RETAIN_PUBLISHED_RUNS + 1);
        assert_eq!(
            fs::read_to_string(leased.path().join("profile.json")).expect("read leased run"),
            "receipt-0"
        );
        drop(leased);

        drop(publish_pair(
            temp.path(),
            "published-run-final",
            "receipt-final",
        ));
        assert_eq!(count_runs(), RETAIN_PUBLISHED_RUNS);
    }

    #[test]
    fn abandoned_workspace_quarantine_is_bounded() {
        let temp = tempfile::tempdir().expect("tempdir");
        let staging = temp.path().join(STAGING_DIRECTORY);
        fs::create_dir_all(&staging).expect("create staging root");
        for index in 0..(RETAIN_QUARANTINE_ENTRIES + 5) {
            let crashed = staging.join(format!("crashed-{index}"));
            fs::create_dir(&crashed).expect("create crashed workspace");
            fs::write(crashed.join(WORKSPACE_LOCK_FILE), "").expect("write released lock");
        }

        let workspace = RunWorkspace::allocate(
            temp.path(),
            &ArtifactId::new("quarantine-writer").expect("logical ID"),
        )
        .expect("recover abandoned workspaces");
        assert_eq!(
            fs::read_dir(temp.path().join(STAGING_QUARANTINE_DIRECTORY))
                .expect("list bounded quarantine")
                .count(),
            RETAIN_QUARANTINE_ENTRIES
        );
        drop(workspace);
    }

    #[test]
    fn concurrent_latest_refreshes_leave_one_complete_alias_pair() {
        use std::sync::{Arc, Barrier};

        const WRITERS: usize = 8;
        let temp = tempfile::tempdir().expect("tempdir");
        let required = [
            ArtifactId::new("profile.json").expect("valid profile ID"),
            ArtifactId::new("summary.md").expect("valid summary ID"),
        ];
        let mut published = Vec::new();
        for index in 0..WRITERS {
            let logical_id = ArtifactId::new(format!("run-{index}")).expect("valid logical ID");
            let workspace =
                RunWorkspace::allocate(temp.path(), &logical_id).expect("allocate workspace");
            let receipt = format!("run-{index}");
            fs::write(workspace.staging_path().join("profile.json"), &receipt)
                .expect("write staged profile");
            fs::write(workspace.staging_path().join("summary.md"), &receipt)
                .expect("write staged summary");
            published.push(workspace.publish(&required).expect("publish complete run"));
        }

        let barrier = Arc::new(Barrier::new(WRITERS));
        let handles: Vec<_> = published
            .into_iter()
            .map(|published| {
                let barrier = Arc::clone(&barrier);
                let required = required.clone();
                std::thread::spawn(move || {
                    barrier.wait();
                    published.refresh_latest(&[
                        LatestArtifact::same(required[0].clone()),
                        LatestArtifact::same(required[1].clone()),
                    ])
                })
            })
            .collect();

        let mut committed = 0;
        let mut rejected_as_stale = 0;
        for handle in handles {
            match handle.join().expect("latest refresh thread") {
                Ok(()) => committed += 1,
                Err(ArtifactPathError::StaleLatestGeneration { .. }) => rejected_as_stale += 1,
                Err(error) => panic!("unexpected latest refresh error: {error}"),
            }
        }
        assert_eq!(committed, 1, "exactly one shared CAS token may commit");
        assert_eq!(rejected_as_stale, WRITERS - 1);

        let profile =
            fs::read_to_string(temp.path().join("profile.json")).expect("read latest profile");
        let summary =
            fs::read_to_string(temp.path().join("summary.md")).expect("read latest summary");
        assert_eq!(profile, summary, "latest aliases came from different runs");
        assert!(profile.starts_with("run-"));
    }

    #[test]
    fn rollback_restores_other_backups_after_installed_file_removal_fails() {
        let temp = tempfile::tempdir().expect("tempdir");
        let blocked_destination = temp.path().join("blocked");
        let restorable_destination = temp.path().join("restorable");
        let blocked_backup = temp.path().join("blocked.backup");
        let restorable_backup = temp.path().join("restorable.backup");
        fs::create_dir(&blocked_destination).expect("create removal failure directory");
        fs::write(&restorable_destination, "new").expect("write installed file");
        fs::write(&blocked_backup, "old blocked").expect("write blocked backup");
        fs::write(&restorable_backup, "old restored").expect("write restorable backup");
        let original = ArtifactPathError::Io {
            operation: "install latest artifact",
            path: restorable_destination.clone(),
            source: std::io::Error::other("simulated install failure"),
        };

        let error = latest_update_failure(
            original,
            &[restorable_destination.clone(), blocked_destination.clone()],
            &[
                (blocked_destination.clone(), blocked_backup.clone()),
                (restorable_destination.clone(), restorable_backup),
            ],
            temp.path().join("retained-rollback"),
        );

        assert!(matches!(error, ArtifactPathError::LatestRollback { .. }));
        assert_eq!(
            fs::read_to_string(&restorable_destination).expect("read restored backup"),
            "old restored"
        );
        assert!(blocked_backup.is_file());
    }

    #[test]
    fn incomplete_transaction_rollback_retains_backup_directory() {
        let temp = tempfile::tempdir().expect("tempdir");
        let transaction_path = temp.path().join("alias-transaction");
        let backup_root = transaction_path.join("backup");
        fs::create_dir_all(&backup_root).expect("create transaction backup root");
        let destination = temp.path().join("profile.json");
        fs::create_dir(&destination).expect("create blocking destination directory");
        let backup = backup_root.join("profile.json");
        fs::write(&backup, "previous").expect("write backup");
        let transaction = StableAliasTransaction {
            path: transaction_path.clone(),
            root_path: temp.path().to_path_buf(),
            installed: vec![destination.clone()],
            backups: vec![(destination, backup.clone())],
        };
        let original = ArtifactPathError::Io {
            operation: "install stable latest alias",
            path: temp.path().join("profile.json"),
            source: std::io::Error::other("injected install failure"),
        };

        let error = transaction.rollback(original);
        assert!(matches!(
            error,
            ArtifactPathError::LatestRollback {
                ref recovery_path,
                ..
            } if recovery_path == &transaction_path
        ));
        assert!(transaction_path.is_dir());
        assert_eq!(
            fs::read_to_string(backup).expect("read retained backup"),
            "previous"
        );
    }

    #[test]
    fn latest_refresh_prepares_every_source_before_replacing_destinations() {
        let temp = tempfile::tempdir().expect("tempdir");
        fs::write(temp.path().join("profile.json"), "old profile").expect("seed latest profile");
        fs::write(temp.path().join("summary.md"), "old summary").expect("seed latest summary");
        let logical_id = ArtifactId::new("android-sample").expect("valid logical ID");
        let workspace =
            RunWorkspace::allocate(temp.path(), &logical_id).expect("allocate workspace");
        fs::write(workspace.staging_path().join("profile.json"), "new profile")
            .expect("write staged profile");
        fs::write(workspace.staging_path().join("summary.md"), "new summary")
            .expect("write staged summary");
        let required = [
            ArtifactId::new("profile.json").expect("valid profile ID"),
            ArtifactId::new("summary.md").expect("valid summary ID"),
        ];
        let published = workspace.publish(&required).expect("publish complete run");
        fs::remove_file(published.path().join("summary.md"))
            .expect("remove second published source");

        let error = published
            .refresh_latest(&[
                LatestArtifact::same(required[0].clone()),
                LatestArtifact::same(required[1].clone()),
            ])
            .expect_err("reject incomplete latest source set");

        assert!(matches!(
            error,
            ArtifactPathError::RequiredArtifactMissing { .. }
        ));
        assert_eq!(
            fs::read_to_string(temp.path().join("profile.json")).expect("read latest profile"),
            "old profile"
        );
        assert_eq!(
            fs::read_to_string(temp.path().join("summary.md")).expect("read latest summary"),
            "old summary"
        );
    }

    #[test]
    fn approved_root_prepares_nested_directory_beneath_root() {
        let temp = tempfile::tempdir().expect("tempdir");
        let root = ApprovedRoot::existing(temp.path()).expect("approve root");

        let prepared = root
            .prepare_dir("plots/nested")
            .expect("prepare nested directory");

        assert_eq!(prepared, root.path().join("plots/nested"));
        assert!(prepared.is_dir());
    }

    #[test]
    fn approved_root_projects_a_missing_directory_without_creating_it() {
        let temp = tempfile::tempdir().expect("tempdir");
        let root = ApprovedRoot::existing(temp.path()).expect("approve root");

        let projected = root
            .project_dir("target/mobench")
            .expect("project output directory");

        assert_eq!(projected, root.path().join("target/mobench"));
        assert!(!projected.exists());
        assert!(!root.path().join("target").exists());
    }

    #[test]
    fn approved_root_rejects_paths_that_are_not_relative_descendants() {
        let temp = tempfile::tempdir().expect("tempdir");
        let root = ApprovedRoot::existing(temp.path()).expect("approve root");

        for invalid in [Path::new("../escape"), Path::new("/absolute/escape")] {
            assert!(matches!(
                root.prepare_dir(invalid),
                Err(ArtifactPathError::InvalidRelativePath { .. })
            ));
        }

        assert!(!root.path().join("../escape").exists());
    }

    #[test]
    fn approved_root_projection_rejects_paths_that_are_not_relative_descendants() {
        let temp = tempfile::tempdir().expect("tempdir");
        let root = ApprovedRoot::existing(temp.path()).expect("approve root");

        for invalid in [Path::new("../escape"), Path::new("/absolute/escape")] {
            assert!(matches!(
                root.project_dir(invalid),
                Err(ArtifactPathError::InvalidRelativePath { .. })
            ));
        }
    }

    #[cfg(unix)]
    #[test]
    fn approved_root_rejects_symlink_directory_components_without_following_them() {
        use std::os::unix::fs::symlink;

        let temp = tempfile::tempdir().expect("tempdir");
        let outside = tempfile::tempdir().expect("outside tempdir");
        symlink(outside.path(), temp.path().join("linked")).expect("create symlink");
        let root = ApprovedRoot::existing(temp.path()).expect("approve root");

        assert!(matches!(
            root.prepare_dir("linked/nested"),
            Err(ArtifactPathError::SymlinkComponent { .. })
        ));
        assert!(!outside.path().join("nested").exists());
    }

    #[cfg(unix)]
    #[test]
    fn approved_root_projection_rejects_symlink_directory_components_without_writing() {
        use std::os::unix::fs::symlink;

        let temp = tempfile::tempdir().expect("tempdir");
        let outside = tempfile::tempdir().expect("outside tempdir");
        symlink(outside.path(), temp.path().join("linked")).expect("create symlink");
        let root = ApprovedRoot::existing(temp.path()).expect("approve root");

        assert!(matches!(
            root.project_dir("linked/nested"),
            Err(ArtifactPathError::SymlinkComponent { .. })
        ));
        assert!(!outside.path().join("nested").exists());
    }

    #[test]
    fn approved_root_prepares_file_parent_without_creating_the_file() {
        let temp = tempfile::tempdir().expect("tempdir");
        let root = ApprovedRoot::existing(temp.path()).expect("approve root");

        let prepared = root
            .prepare_file("plots/nested/chart.svg")
            .expect("prepare artifact file");

        assert_eq!(prepared, root.path().join("plots/nested/chart.svg"));
        assert!(prepared.parent().expect("parent").is_dir());
        assert!(!prepared.exists());
    }

    #[cfg(unix)]
    #[test]
    fn approved_root_rejects_preexisting_symlink_file_without_following_it() {
        use std::os::unix::fs::symlink;

        let temp = tempfile::tempdir().expect("tempdir");
        let root = ApprovedRoot::existing(temp.path()).expect("approve root");
        let plots = root.prepare_dir("plots").expect("prepare plots");
        let outside = tempfile::NamedTempFile::new().expect("outside file");
        fs::write(outside.path(), "unchanged").expect("seed outside file");
        symlink(outside.path(), plots.join("chart.svg")).expect("create symlink");

        assert!(matches!(
            root.prepare_file("plots/chart.svg"),
            Err(ArtifactPathError::SymlinkComponent { .. })
        ));
        assert_eq!(
            fs::read_to_string(outside.path()).expect("read outside file"),
            "unchanged"
        );
    }

    #[cfg(unix)]
    #[test]
    fn approved_root_rejects_a_symlink_as_the_root() {
        use std::os::unix::fs::symlink;

        let parent = tempfile::tempdir().expect("parent tempdir");
        let actual_root = tempfile::tempdir().expect("actual root");
        let linked_root = parent.path().join("linked-root");
        symlink(actual_root.path(), &linked_root).expect("create root symlink");

        assert!(matches!(
            ApprovedRoot::existing(&linked_root),
            Err(ArtifactPathError::SymlinkComponent { path }) if path == linked_root
        ));
    }

    fn publish_pair(root: &Path, logical: &str, receipt: &str) -> PublishedRun {
        let logical_id = ArtifactId::new(logical).expect("valid logical ID");
        let workspace = RunWorkspace::allocate(root, &logical_id).expect("allocate workspace");
        fs::write(workspace.staging_path().join("profile.json"), receipt).expect("write profile");
        fs::write(workspace.staging_path().join("summary.md"), receipt).expect("write summary");
        workspace
            .publish(&[
                ArtifactId::new("profile.json").expect("profile ID"),
                ArtifactId::new("summary.md").expect("summary ID"),
            ])
            .expect("publish pair")
    }

    fn refresh_pair(published: &PublishedRun) -> Result<(), ArtifactPathError> {
        published.refresh_latest(&[
            LatestArtifact::same(ArtifactId::new("profile.json").expect("profile ID")),
            LatestArtifact::same(ArtifactId::new("summary.md").expect("summary ID")),
        ])
    }

    fn durability_events() -> Vec<&'static str> {
        DURABILITY_EVENTS.with(|events| std::mem::take(&mut *events.borrow_mut()))
    }

    fn rewrite_latest_manifest(generation_path: &Path, update: impl FnOnce(&mut LatestManifest)) {
        let manifest_path = generation_path.join(LATEST_MANIFEST_FILE);
        let mut manifest: LatestManifest =
            read_json_file(&manifest_path, "read test manifest").expect("read manifest");
        update(&mut manifest);
        fs::remove_file(&manifest_path).expect("remove old manifest");
        write_json_file(&manifest_path, &manifest, "rewrite test manifest")
            .expect("rewrite manifest");
    }

    fn clone_generation(
        source: &LatestSnapshot,
        generation: &str,
        predecessor: Option<&str>,
    ) -> PathBuf {
        let generations = source
            .path()
            .parent()
            .expect("generation parent")
            .to_path_buf();
        let destination = generations.join(generation);
        fs::create_dir(&destination).expect("create cloned generation");
        for artifact in &source.manifest().artifacts {
            fs::copy(
                source.path().join(&artifact.destination_relative_path),
                destination.join(&artifact.destination_relative_path),
            )
            .expect("copy generation artifact");
        }
        create_reader_lease_file(&destination).expect("create cloned generation lease");
        let mut manifest = source.manifest().clone();
        manifest.generation = generation.to_owned();
        manifest.predecessor_generation = predecessor.map(str::to_owned);
        write_json_file(
            &destination.join(LATEST_MANIFEST_FILE),
            &manifest,
            "write cloned generation manifest",
        )
        .expect("write cloned manifest");
        destination
    }

    #[test]
    fn writer_startup_quarantines_an_unlocked_crash_workspace() {
        let temp = tempfile::tempdir().expect("tempdir");
        let staging = temp.path().join(STAGING_DIRECTORY);
        let crashed = staging.join("crashed-workspace");
        fs::create_dir_all(&crashed).expect("create crashed workspace");
        fs::write(crashed.join(WORKSPACE_LOCK_FILE), "").expect("create released lock");
        fs::write(crashed.join("partial.data"), "partial").expect("write partial artifact");

        let workspace = RunWorkspace::allocate(
            temp.path(),
            &ArtifactId::new("recovery-writer").expect("logical ID"),
        )
        .expect("allocate after crash");
        assert!(!crashed.exists());
        let quarantine = temp.path().join(STAGING_QUARANTINE_DIRECTORY);
        assert!(
            fs::read_dir(quarantine)
                .expect("read run quarantine")
                .any(|entry| entry
                    .expect("quarantine entry")
                    .file_name()
                    .to_string_lossy()
                    .starts_with("crashed-workspace--"))
        );
        drop(workspace);
    }

    #[test]
    fn writer_startup_never_quarantines_an_active_workspace() {
        let temp = tempfile::tempdir().expect("tempdir");
        let first = RunWorkspace::allocate(
            temp.path(),
            &ArtifactId::new("active-first").expect("logical ID"),
        )
        .expect("first workspace");
        let first_path = first.staging_path().to_path_buf();

        let second = RunWorkspace::allocate(
            temp.path(),
            &ArtifactId::new("active-second").expect("logical ID"),
        )
        .expect("second workspace");
        assert!(first_path.is_dir(), "active workspace was moved");
        assert!(first_path.join(WORKSPACE_LOCK_FILE).is_file());
        drop(second);
        drop(first);
    }

    #[test]
    fn run_manifest_records_deterministic_recursive_digests_and_identity() {
        let temp = tempfile::tempdir().expect("tempdir");
        let logical_id = ArtifactId::new("android-sample").expect("logical ID");
        let workspace = RunWorkspace::allocate(temp.path(), &logical_id).expect("workspace");
        fs::write(workspace.staging_path().join("profile.json"), "hello").expect("write profile");
        fs::create_dir(workspace.staging_path().join("nested")).expect("create nested");
        fs::write(workspace.staging_path().join("nested/notes.txt"), "notes").expect("write notes");
        let published = workspace
            .publish(&[ArtifactId::new("profile.json").expect("profile ID")])
            .expect("publish");

        let manifest = published.manifest().expect("verified manifest");
        assert_eq!(manifest.format_version, RUN_MANIFEST_VERSION);
        assert_eq!(manifest.producer_version, env!("CARGO_PKG_VERSION"));
        assert_eq!(manifest.logical_id, "android-sample");
        assert_eq!(
            manifest.publication_id,
            published
                .path()
                .file_name()
                .expect("publication name")
                .to_string_lossy()
        );
        assert_eq!(
            manifest
                .artifacts
                .iter()
                .map(|artifact| artifact.relative_path.as_str())
                .collect::<Vec<_>>(),
            ["nested/notes.txt", "profile.json"]
        );
        let profile = manifest
            .artifacts
            .iter()
            .find(|artifact| artifact.relative_path == "profile.json")
            .expect("profile manifest entry");
        assert_eq!(profile.size, 5);
        assert_eq!(
            profile.sha256,
            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
        );
    }

    #[test]
    fn publication_syncs_files_and_directories_before_the_atomic_rename() {
        let temp = tempfile::tempdir().expect("tempdir");
        let logical_id = ArtifactId::new("ordered-run").expect("logical ID");
        let workspace = RunWorkspace::allocate(temp.path(), &logical_id).expect("workspace");
        fs::write(workspace.staging_path().join("profile.json"), "complete")
            .expect("write profile");
        durability_events();

        workspace
            .publish(&[ArtifactId::new("profile.json").expect("profile ID")])
            .expect("publish");
        let events = durability_events();
        let publication = events
            .iter()
            .position(|event| *event == "publish_run")
            .expect("publication event");
        assert!(events[..publication].contains(&"sync_manifest"));
        assert!(events[..publication].contains(&"sync_file"));
        assert!(events[..publication].contains(&"sync_directory"));
        assert!(events[publication + 1..].contains(&"sync_directory"));
    }

    #[test]
    fn post_rename_sync_failure_reports_committed_run_explicitly() {
        let temp = tempfile::tempdir().expect("tempdir");
        let logical_id = ArtifactId::new("uncertain-run").expect("logical ID");
        let workspace = RunWorkspace::allocate(temp.path(), &logical_id).expect("workspace");
        fs::write(workspace.staging_path().join("profile.json"), "complete")
            .expect("write profile");
        let expected_path = workspace.published_path().to_path_buf();
        FAIL_DIRECTORY_SYNC_AFTER_EVENT.with(|target| target.set(Some("publish_run")));

        let error = workspace
            .publish(&[ArtifactId::new("profile.json").expect("profile ID")])
            .expect_err("surface post-commit durability uncertainty");
        assert!(matches!(
            error,
            ArtifactPathError::PublicationDurabilityUncertain { ref path, .. }
                if path == &expected_path
        ));
        assert!(expected_path.join(RUN_MANIFEST_FILE).is_file());
        validate_run_manifest(&expected_path).expect("committed run remains valid");
    }

    #[test]
    fn latest_commit_orders_generation_sync_before_the_single_pointer_swap() {
        let temp = tempfile::tempdir().expect("tempdir");
        let published = publish_pair(temp.path(), "ordered-latest", "receipt");
        durability_events();

        refresh_pair(&published).expect("refresh latest");
        let events = durability_events();
        let generation = events
            .iter()
            .position(|event| *event == "publish_generation")
            .expect("generation publication event");
        let pointer_sync = events
            .iter()
            .position(|event| *event == "sync_pointer_file")
            .expect("pointer sync event");
        let pointer_commit = events
            .iter()
            .position(|event| *event == "commit_pointer")
            .expect("pointer commit event");
        assert!(events[..generation].contains(&"sync_manifest"));
        assert!(events[generation + 1..pointer_sync].contains(&"sync_directory"));
        let aliases = events
            .iter()
            .position(|event| *event == "install_aliases")
            .expect("alias install event");
        assert!(generation < pointer_sync);
        assert!(
            aliases < pointer_sync,
            "aliases must precede pointer commit"
        );
        assert!(pointer_sync < pointer_commit);
        assert!(events[pointer_commit + 1..].contains(&"sync_directory"));
    }

    #[test]
    fn post_pointer_sync_failure_reports_committed_generation_explicitly() {
        let temp = tempfile::tempdir().expect("tempdir");
        let published = publish_pair(temp.path(), "uncertain-latest", "receipt");
        FAIL_DIRECTORY_SYNC_AFTER_EVENT.with(|target| target.set(Some("commit_pointer")));

        let error = refresh_pair(&published).expect_err("surface pointer durability uncertainty");
        let generation = match error {
            ArtifactPathError::LatestCommitDurabilityUncertain { generation, .. } => generation,
            other => panic!("unexpected error: {other}"),
        };
        let snapshot = LatestSnapshot::open(temp.path()).expect("committed snapshot remains open");
        assert_eq!(snapshot.generation(), generation);
        assert_eq!(
            snapshot
                .read_artifact(&ArtifactId::new("profile.json").expect("profile ID"))
                .expect("read committed artifact"),
            b"receipt"
        );
    }

    #[test]
    fn latest_snapshot_pins_one_generation_across_concurrent_refreshes() {
        let temp = tempfile::tempdir().expect("tempdir");
        let first = publish_pair(temp.path(), "first-run", "first");
        refresh_pair(&first).expect("first refresh");
        let pinned = LatestSnapshot::open(temp.path()).expect("first snapshot");

        let second = publish_pair(temp.path(), "second-run", "second");
        refresh_pair(&second).expect("second refresh");
        let current = LatestSnapshot::open(temp.path()).expect("second snapshot");

        assert_ne!(pinned.generation(), current.generation());
        for id in ["profile.json", "summary.md"] {
            let id = ArtifactId::new(id).expect("artifact ID");
            assert_eq!(pinned.read_artifact(&id).expect("pinned read"), b"first");
            assert_eq!(current.read_artifact(&id).expect("current read"), b"second");
        }
    }

    #[cfg(unix)]
    #[test]
    fn latest_snapshot_open_succeeds_with_a_read_only_artifact_root() {
        use std::os::unix::fs::PermissionsExt;

        fn set_tree_mode(path: &Path, directory_mode: u32, file_mode: u32) {
            let metadata = fs::symlink_metadata(path).expect("tree metadata");
            if metadata.is_dir() {
                for entry in fs::read_dir(path).expect("read tree") {
                    set_tree_mode(
                        &entry.expect("tree entry").path(),
                        directory_mode,
                        file_mode,
                    );
                }
                fs::set_permissions(path, fs::Permissions::from_mode(directory_mode))
                    .expect("set directory mode");
            } else {
                fs::set_permissions(path, fs::Permissions::from_mode(file_mode))
                    .expect("set file mode");
            }
        }

        let temp = tempfile::tempdir().expect("tempdir");
        let published = publish_pair(temp.path(), "read-only", "receipt");
        refresh_pair(&published).expect("refresh latest");
        set_tree_mode(temp.path(), 0o555, 0o444);

        let opened = LatestSnapshot::open(temp.path()).expect("read-only snapshot open");
        assert_eq!(
            opened
                .read_artifact(&ArtifactId::new("profile.json").expect("profile ID"))
                .expect("read snapshot artifact"),
            b"receipt"
        );

        set_tree_mode(temp.path(), 0o755, 0o644);
    }

    #[test]
    fn writer_allocation_recovers_mixed_legacy_aliases() {
        let temp = tempfile::tempdir().expect("tempdir");
        let published = publish_pair(temp.path(), "recover-run", "committed");
        refresh_pair(&published).expect("refresh latest");
        fs::write(temp.path().join("profile.json"), "interrupted-new")
            .expect("simulate interrupted alias install");
        fs::write(temp.path().join("summary.md"), "committed").expect("retain old alias");

        LatestSnapshot::open(temp.path()).expect("read-only open");
        assert_eq!(
            fs::read_to_string(temp.path().join("profile.json")).expect("unrecovered profile"),
            "interrupted-new",
            "reader open must not mutate compatibility aliases"
        );

        let recovery_probe = RunWorkspace::allocate(
            temp.path(),
            &ArtifactId::new("recovery-probe").expect("probe ID"),
        )
        .expect("writer startup recovers aliases");
        drop(recovery_probe);
        let recovered = LatestSnapshot::open(temp.path()).expect("open recovered snapshot");
        assert_eq!(
            fs::read(temp.path().join("profile.json")).expect("profile alias"),
            b"committed"
        );
        assert_eq!(
            fs::read(temp.path().join("summary.md")).expect("summary alias"),
            b"committed"
        );
        assert_eq!(
            recovered
                .read_artifact(&ArtifactId::new("profile.json").expect("profile ID"))
                .expect("read recovered snapshot"),
            b"committed"
        );
    }

    #[test]
    fn missing_current_recovers_the_unique_highest_chain_tip() {
        let temp = tempfile::tempdir().expect("tempdir");
        let first = publish_pair(temp.path(), "first-chain-run", "first");
        refresh_pair(&first).expect("first refresh");
        let second = publish_pair(temp.path(), "second-chain-run", "second");
        refresh_pair(&second).expect("second refresh");
        let expected = LatestSnapshot::open(temp.path()).expect("tip snapshot");
        let expected_generation = expected.generation().to_owned();
        let current = temp.path().join(LATEST_DIRECTORY).join(LATEST_CURRENT_FILE);
        fs::remove_file(&current).expect("remove current pointer");
        fs::write(temp.path().join("profile.json"), "interrupted")
            .expect("tamper compatibility alias");

        assert!(matches!(
            LatestSnapshot::open(temp.path()),
            Err(ArtifactPathError::LatestSnapshotUnavailable { .. })
        ));
        let recovered =
            LatestSnapshot::recover_stable_aliases(temp.path()).expect("recover missing pointer");
        assert_eq!(recovered.generation(), expected_generation);
        assert_eq!(
            fs::read_to_string(temp.path().join("profile.json")).expect("recovered profile"),
            "second"
        );
    }

    #[test]
    fn corrupt_current_recovers_the_unique_valid_chain_tip() {
        let temp = tempfile::tempdir().expect("tempdir");
        let published = publish_pair(temp.path(), "corrupt-pointer-run", "receipt");
        refresh_pair(&published).expect("refresh latest");
        let expected = LatestSnapshot::open(temp.path())
            .expect("snapshot")
            .generation()
            .to_owned();
        let current = temp.path().join(LATEST_DIRECTORY).join(LATEST_CURRENT_FILE);
        fs::write(&current, "../../invalid\n").expect("corrupt pointer");

        assert!(matches!(
            LatestSnapshot::open(temp.path()),
            Err(ArtifactPathError::InvalidLatestPointer { .. })
        ));
        let recovered =
            LatestSnapshot::recover_stable_aliases(temp.path()).expect("recover corrupt pointer");
        assert_eq!(recovered.generation(), expected);
        assert_eq!(
            fs::read_to_string(current)
                .expect("read repaired pointer")
                .trim(),
            expected
        );
    }

    #[test]
    fn missing_current_fails_closed_on_an_ambiguous_generation_fork() {
        let temp = tempfile::tempdir().expect("tempdir");
        let published = publish_pair(temp.path(), "fork-root-run", "root");
        refresh_pair(&published).expect("refresh root");
        let root_snapshot = LatestSnapshot::open(temp.path()).expect("root snapshot");
        let root_generation = root_snapshot.generation().to_owned();
        clone_generation(&root_snapshot, "fork-child-a", Some(&root_generation));
        clone_generation(&root_snapshot, "fork-child-b", Some(&root_generation));
        fs::remove_file(temp.path().join(LATEST_DIRECTORY).join(LATEST_CURRENT_FILE))
            .expect("remove current pointer");

        assert!(matches!(
            LatestSnapshot::recover_stable_aliases(temp.path()),
            Err(ArtifactPathError::AmbiguousGenerationFork { .. })
        ));
    }

    #[test]
    fn predecessor_cycle_is_rejected_by_open_and_recovery() {
        let temp = tempfile::tempdir().expect("tempdir");
        let first = publish_pair(temp.path(), "cycle-first", "first");
        refresh_pair(&first).expect("first refresh");
        let first_snapshot = LatestSnapshot::open(temp.path()).expect("first snapshot");
        let first_generation = first_snapshot.generation().to_owned();
        let second = publish_pair(temp.path(), "cycle-second", "second");
        refresh_pair(&second).expect("second refresh");
        let second_snapshot = LatestSnapshot::open(temp.path()).expect("second snapshot");
        let second_generation = second_snapshot.generation().to_owned();
        rewrite_latest_manifest(&first_snapshot.generation_path, |manifest| {
            manifest.predecessor_generation = Some(second_generation.clone());
        });

        assert!(matches!(
            LatestSnapshot::open(temp.path()),
            Err(ArtifactPathError::GenerationChainCycle { .. })
        ));
        fs::remove_file(temp.path().join(LATEST_DIRECTORY).join(LATEST_CURRENT_FILE))
            .expect("remove current pointer");
        assert!(matches!(
            LatestSnapshot::recover_stable_aliases(temp.path()),
            Err(ArtifactPathError::GenerationChainCycle { .. })
        ));
        assert_ne!(first_generation, second_generation);
    }

    #[test]
    fn broken_predecessor_chain_fails_closed_during_recovery() {
        let temp = tempfile::tempdir().expect("tempdir");
        let published = publish_pair(temp.path(), "broken-chain", "receipt");
        refresh_pair(&published).expect("refresh latest");
        let snapshot = LatestSnapshot::open(temp.path()).expect("snapshot");
        rewrite_latest_manifest(snapshot.path(), |manifest| {
            manifest.predecessor_generation = Some("missing-predecessor".to_owned());
        });
        fs::remove_file(temp.path().join(LATEST_DIRECTORY).join(LATEST_CURRENT_FILE))
            .expect("remove current pointer");

        assert!(matches!(
            LatestSnapshot::recover_stable_aliases(temp.path()),
            Err(ArtifactPathError::BrokenGenerationChain { .. })
        ));
    }

    #[test]
    fn alias_install_failure_rolls_back_before_pointer_commit() {
        let temp = tempfile::tempdir().expect("tempdir");
        let first = publish_pair(temp.path(), "first-run", "first");
        refresh_pair(&first).expect("first refresh");
        let before = LatestSnapshot::open(temp.path()).expect("snapshot before failure");
        let before_generation = before.generation().to_owned();
        let second = publish_pair(temp.path(), "second-run", "second");

        FAIL_ALIAS_INSTALL_AFTER.with(|fail_after| fail_after.set(Some(1)));
        let error = refresh_pair(&second).expect_err("injected alias failure");
        assert!(matches!(error, ArtifactPathError::Io { .. }));

        let after = LatestSnapshot::open(temp.path()).expect("snapshot after rollback");
        assert_eq!(after.generation(), before_generation);
        assert_eq!(
            fs::read_to_string(temp.path().join("profile.json")).expect("profile alias"),
            "first"
        );
        assert_eq!(
            fs::read_to_string(temp.path().join("summary.md")).expect("summary alias"),
            "first"
        );
    }

    #[test]
    fn stale_allocated_run_cannot_replace_a_newer_generation() {
        let temp = tempfile::tempdir().expect("tempdir");
        let stale = publish_pair(temp.path(), "stale-run", "stale");
        let winner = publish_pair(temp.path(), "winner-run", "winner");
        refresh_pair(&winner).expect("winner refresh");
        let winner_generation = LatestSnapshot::open(temp.path())
            .expect("winner snapshot")
            .generation()
            .to_owned();

        let error = refresh_pair(&stale).expect_err("reject stale CAS token");
        assert!(matches!(
            error,
            ArtifactPathError::StaleLatestGeneration {
                expected: None,
                observed: Some(_)
            }
        ));
        let current = LatestSnapshot::open(temp.path()).expect("current snapshot");
        assert_eq!(current.generation(), winner_generation);
        assert_eq!(
            current
                .read_artifact(&ArtifactId::new("profile.json").expect("profile ID"))
                .expect("read winner"),
            b"winner"
        );
    }

    #[test]
    fn abandoned_latest_staging_is_quarantined_before_the_next_commit() {
        let temp = tempfile::tempdir().expect("tempdir");
        let first = publish_pair(temp.path(), "first-run", "first");
        refresh_pair(&first).expect("first refresh");
        let staging = temp
            .path()
            .join(LATEST_DIRECTORY)
            .join(LATEST_STAGING_DIRECTORY);
        let abandoned = staging.join("abandoned");
        fs::create_dir(&abandoned).expect("create abandoned staging");
        fs::write(abandoned.join("partial"), "partial").expect("write partial staging");

        let second = publish_pair(temp.path(), "second-run", "second");
        refresh_pair(&second).expect("second refresh");
        assert!(!abandoned.exists());
        let quarantine = temp
            .path()
            .join(LATEST_DIRECTORY)
            .join(LATEST_QUARANTINE_DIRECTORY);
        assert!(
            fs::read_dir(quarantine)
                .expect("read quarantine")
                .any(|entry| entry
                    .expect("quarantine entry")
                    .file_name()
                    .to_string_lossy()
                    .starts_with("abandoned--"))
        );
    }

    #[test]
    fn active_latest_staging_lease_defers_recovery_quarantine() {
        let temp = tempfile::tempdir().expect("tempdir");
        let root = ApprovedRoot::existing(temp.path()).expect("approved root");
        let latest_path = root
            .prepare_dir(LATEST_DIRECTORY)
            .expect("latest directory");
        let latest_root = ApprovedRoot::existing(latest_path).expect("approved latest root");
        latest_root
            .prepare_dir(LATEST_QUARANTINE_DIRECTORY)
            .expect("quarantine directory");
        let (_, staging_path) = allocate_latest_generation(&latest_root).expect("staging path");
        create_reader_lease_file(&staging_path).expect("staging lease file");
        let lease_path = staging_path.join(LATEST_READER_LOCK_FILE);
        let lease = OpenOptions::new()
            .read(true)
            .write(true)
            .open(&lease_path)
            .expect("open staging lease");
        FileExt::lock_exclusive(&lease).expect("lock active staging lease");

        quarantine_abandoned_latest_staging(&latest_root).expect("active staging recovery pass");
        assert!(staging_path.exists(), "active staging was quarantined");

        FileExt::unlock(&lease).expect("unlock staging lease");
        drop(lease);
        quarantine_abandoned_latest_staging(&latest_root).expect("abandoned staging recovery pass");
        assert!(!staging_path.exists(), "abandoned staging was retained");
    }

    #[test]
    fn newer_latest_producer_version_rejects_a_downgrade() {
        let temp = tempfile::tempdir().expect("tempdir");
        let first = publish_pair(temp.path(), "first-run", "first");
        refresh_pair(&first).expect("first refresh");
        let second = publish_pair(temp.path(), "second-run", "second");
        let snapshot = LatestSnapshot::open(temp.path()).expect("snapshot");
        let manifest_path = snapshot.path().join(LATEST_MANIFEST_FILE);
        let mut manifest: LatestManifest =
            read_json_file(&manifest_path, "read test manifest").expect("manifest");
        manifest.producer_version = "999.0.0".to_owned();
        fs::remove_file(&manifest_path).expect("remove old manifest");
        write_json_file(&manifest_path, &manifest, "rewrite test manifest")
            .expect("write newer producer manifest");

        let error = refresh_pair(&second).expect_err("reject producer downgrade");
        assert!(matches!(error, ArtifactPathError::ProducerDowngrade { .. }));
        assert_eq!(
            fs::read_to_string(temp.path().join("profile.json")).expect("stable profile"),
            "first"
        );
    }

    #[test]
    fn unknown_latest_manifest_version_fails_closed() {
        let temp = tempfile::tempdir().expect("tempdir");
        let published = publish_pair(temp.path(), "unknown-version", "receipt");
        refresh_pair(&published).expect("refresh latest");
        let snapshot = LatestSnapshot::open(temp.path()).expect("snapshot");
        let manifest_path = snapshot.path().join(LATEST_MANIFEST_FILE);
        let mut manifest: LatestManifest =
            read_json_file(&manifest_path, "read test manifest").expect("manifest");
        manifest.format_version = LATEST_MANIFEST_VERSION + 1;
        fs::remove_file(&manifest_path).expect("remove old manifest");
        write_json_file(&manifest_path, &manifest, "rewrite test manifest")
            .expect("write unknown manifest");

        assert!(matches!(
            LatestSnapshot::open(temp.path()),
            Err(ArtifactPathError::UnknownManifestVersion { .. })
        ));
    }

    #[test]
    fn corrupt_latest_generation_fails_digest_validation() {
        let temp = tempfile::tempdir().expect("tempdir");
        let published = publish_pair(temp.path(), "corrupt-generation", "receipt");
        refresh_pair(&published).expect("refresh latest");
        let snapshot = LatestSnapshot::open(temp.path()).expect("snapshot");
        fs::write(snapshot.path().join("profile.json"), "tampered").expect("tamper artifact");

        assert!(matches!(
            LatestSnapshot::open(temp.path()),
            Err(ArtifactPathError::CorruptGeneration { .. })
        ));
    }

    #[test]
    fn pinned_snapshot_rejects_bytes_changed_after_open() {
        let temp = tempfile::tempdir().expect("tempdir");
        let published = publish_pair(temp.path(), "mutated-after-open", "original");
        refresh_pair(&published).expect("refresh latest");
        let snapshot = LatestSnapshot::open(temp.path()).expect("open pinned snapshot");
        fs::write(snapshot.path().join("profile.json"), "changed").expect("mutate artifact");

        assert!(matches!(
            snapshot.read_artifact(&ArtifactId::new("profile.json").expect("profile ID")),
            Err(ArtifactPathError::CorruptGeneration { .. })
        ));
    }

    #[test]
    fn latest_refresh_rejects_source_changed_after_run_validation() {
        let temp = tempfile::tempdir().expect("tempdir");
        let published = publish_pair(temp.path(), "mutated-source", "original");
        MUTATE_LATEST_SOURCE_AFTER_VALIDATION.with(|mutation| {
            mutation.replace(Some((
                published.path().join("profile.json"),
                b"changed after validation".to_vec(),
            )));
        });

        let error = refresh_pair(&published).expect_err("reject changed source");
        assert!(matches!(error, ArtifactPathError::ManifestIntegrity { .. }));
        assert!(matches!(
            LatestSnapshot::open(temp.path()),
            Err(ArtifactPathError::LatestSnapshotUnavailable { .. })
        ));
    }

    #[test]
    fn invalid_current_directory_does_not_block_first_commit() {
        let temp = tempfile::tempdir().expect("tempdir");
        let latest = temp.path().join(LATEST_DIRECTORY);
        fs::create_dir_all(latest.join(LATEST_CURRENT_FILE)).expect("seed invalid pointer dir");
        let published = publish_pair(temp.path(), "first-after-invalid-pointer", "receipt");

        refresh_pair(&published).expect("commit after quarantining invalid pointer");
        let snapshot = LatestSnapshot::open(temp.path()).expect("open committed snapshot");
        assert_eq!(
            snapshot
                .read_artifact(&ArtifactId::new("profile.json").expect("profile ID"))
                .expect("read committed artifact"),
            b"receipt"
        );
        assert!(
            fs::read_dir(latest.join(LATEST_QUARANTINE_DIRECTORY))
                .expect("read quarantine")
                .any(|entry| entry
                    .expect("quarantine entry")
                    .file_name()
                    .to_string_lossy()
                    .starts_with("current-corrupt--"))
        );
    }

    #[test]
    fn corrupt_off_chain_generation_is_quarantined_without_blocking_writer() {
        let temp = tempfile::tempdir().expect("tempdir");
        let first = publish_pair(temp.path(), "anchored", "first");
        refresh_pair(&first).expect("anchor current generation");
        let orphan = temp
            .path()
            .join(LATEST_DIRECTORY)
            .join(LATEST_GENERATIONS_DIRECTORY)
            .join("generation-corrupt-orphan");
        fs::create_dir(&orphan).expect("create corrupt orphan");
        fs::write(orphan.join(LATEST_MANIFEST_FILE), b"not-json").expect("write corrupt orphan");

        let second = publish_pair(temp.path(), "after-orphan", "second");
        refresh_pair(&second).expect("refresh despite corrupt orphan");
        assert!(!orphan.exists());
        let snapshot = LatestSnapshot::open(temp.path()).expect("open latest snapshot");
        assert_eq!(
            snapshot
                .read_artifact(&ArtifactId::new("profile.json").expect("profile ID"))
                .expect("read latest artifact"),
            b"second"
        );
    }

    #[cfg(unix)]
    #[test]
    fn recursive_publication_validation_rejects_nested_symlinks() {
        use std::os::unix::fs::symlink;

        let temp = tempfile::tempdir().expect("tempdir");
        let outside = tempfile::NamedTempFile::new().expect("outside file");
        let logical_id = ArtifactId::new("nested-symlink").expect("logical ID");
        let workspace = RunWorkspace::allocate(temp.path(), &logical_id).expect("workspace");
        fs::write(workspace.staging_path().join("profile.json"), "complete")
            .expect("write profile");
        fs::create_dir(workspace.staging_path().join("nested")).expect("nested directory");
        symlink(
            outside.path(),
            workspace.staging_path().join("nested/linked"),
        )
        .expect("nested symlink");

        assert!(matches!(
            workspace.publish(&[ArtifactId::new("profile.json").expect("profile ID")]),
            Err(ArtifactPathError::SymlinkComponent { .. })
        ));
    }

    #[cfg(unix)]
    #[test]
    fn publication_rejects_artifacts_hardlinked_outside_the_workspace() {
        let temp = tempfile::tempdir().expect("tempdir");
        let outside = tempfile::tempdir().expect("outside tempdir");
        let logical_id = ArtifactId::new("hardlinked-artifact").expect("logical ID");
        let workspace = RunWorkspace::allocate(temp.path(), &logical_id).expect("workspace");
        let profile = workspace.staging_path().join("profile.json");
        fs::write(&profile, "complete").expect("write profile");
        fs::hard_link(&profile, outside.path().join("alias.json")).expect("create hard link");

        assert!(matches!(
            workspace.publish(&[ArtifactId::new("profile.json").expect("profile ID")]),
            Err(ArtifactPathError::HardLinkedArtifact { .. })
        ));
    }

    #[cfg(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "linux",
        target_os = "android"
    ))]
    #[test]
    fn platform_publication_rename_never_replaces_a_raced_directory() {
        let temp = tempfile::tempdir().expect("tempdir");
        let source = temp.path().join("source");
        let destination = temp.path().join("destination");
        fs::create_dir(&source).expect("create source");
        fs::create_dir(&destination).expect("create raced destination");
        fs::write(source.join("source.txt"), "source").expect("write source");
        fs::write(destination.join("destination.txt"), "destination").expect("write destination");

        let error = rename_directory_noreplace(&source, &destination)
            .expect_err("no-replace rename must reject collision");
        assert!(matches!(
            error.kind(),
            std::io::ErrorKind::AlreadyExists | std::io::ErrorKind::Other
        ));
        assert!(source.join("source.txt").is_file());
        assert_eq!(
            fs::read_to_string(destination.join("destination.txt"))
                .expect("read original destination"),
            "destination"
        );
    }

    #[cfg(unix)]
    #[test]
    fn latest_reader_rejects_a_symlink_pointer() {
        use std::os::unix::fs::symlink;

        let temp = tempfile::tempdir().expect("tempdir");
        let outside = tempfile::NamedTempFile::new().expect("outside pointer");
        fs::write(outside.path(), "generation-attacker").expect("write outside pointer");
        let published = publish_pair(temp.path(), "symlink-pointer", "receipt");
        refresh_pair(&published).expect("refresh latest");
        let current = temp.path().join(LATEST_DIRECTORY).join(LATEST_CURRENT_FILE);
        fs::remove_file(&current).expect("remove current pointer");
        symlink(outside.path(), &current).expect("install pointer symlink");

        assert!(matches!(
            LatestSnapshot::open(temp.path()),
            Err(ArtifactPathError::SymlinkComponent { .. })
        ));
    }
}