tirith 0.4.1

Terminal security - catches homograph attacks, pipe-to-shell, ANSI injection
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
//! Windows filesystem helpers for `tirith setup` — the same public API as
//! `fs_helpers.rs` using held Windows handles and explicit DACL handling.

use std::ffi::{OsStr, OsString};
use std::fmt::Write as _;
use std::fs;
use std::io::{Read, Seek, SeekFrom, Write};
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, FromRawHandle, RawHandle};
use std::path::{Path, PathBuf};
use std::{cell::RefCell, rc::Rc};

use sha2::{Digest, Sha256};

use super::fs_transaction::PublicationOutcome;
pub(crate) use super::fs_transaction::{
    transactional_update, transactional_update_checked, FileUpdate,
};

#[path = "fs_helpers_windows_path.rs"]
mod path_rules;

use windows::core::{BOOL, HRESULT, PCWSTR, PWSTR};
use windows::Win32::Foundation::{
    CloseHandle, LocalFree, ERROR_ALREADY_EXISTS, ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND,
    ERROR_UNABLE_TO_MOVE_REPLACEMENT, ERROR_UNABLE_TO_MOVE_REPLACEMENT_2, HANDLE, HLOCAL,
    WAIT_ABANDONED, WAIT_OBJECT_0,
};
use windows::Win32::Security::Authorization::{
    ConvertSecurityDescriptorToStringSecurityDescriptorW, ConvertSidToStringSidW,
    ConvertStringSecurityDescriptorToSecurityDescriptorW, GetSecurityInfo, SDDL_REVISION_1,
    SE_FILE_OBJECT,
};
use windows::Win32::Security::{
    AclSizeInformation, EqualSid, GetAce, GetAclInformation, GetSecurityDescriptorControl,
    GetSecurityDescriptorDacl, GetSecurityDescriptorGroup, GetSecurityDescriptorLength,
    GetSecurityDescriptorOwner, GetTokenInformation, SetKernelObjectSecurity,
    SetSecurityDescriptorControl, TokenUser, ACCESS_ALLOWED_ACE, ACL, ACL_SIZE_INFORMATION,
    DACL_SECURITY_INFORMATION, GROUP_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
    PSECURITY_DESCRIPTOR, PSID, SECURITY_ATTRIBUTES, SE_DACL_AUTO_INHERITED,
    SE_DACL_AUTO_INHERIT_REQ, SE_DACL_PROTECTED, TOKEN_QUERY, TOKEN_USER,
};
use windows::Win32::Storage::FileSystem::{
    CreateDirectoryW, CreateFileW, FileAttributeTagInfo, FileDispositionInfo, FlushFileBuffers,
    GetFileInformationByHandle, GetFileInformationByHandleEx, GetFinalPathNameByHandleW,
    MoveFileExW, ReplaceFileW, SetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, CREATE_NEW,
    DELETE, FILE_ALL_ACCESS, FILE_ATTRIBUTE_NORMAL, FILE_ATTRIBUTE_REPARSE_POINT,
    FILE_ATTRIBUTE_TAG_INFO, FILE_DISPOSITION_INFO, FILE_FLAG_BACKUP_SEMANTICS,
    FILE_FLAG_OPEN_REPARSE_POINT, FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_LIST_DIRECTORY,
    FILE_READ_ATTRIBUTES, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_TRAVERSE, MOVEFILE_WRITE_THROUGH,
    OPEN_EXISTING, READ_CONTROL, WRITE_DAC, WRITE_OWNER,
};
use windows::Win32::System::Threading::{
    CreateMutexW, GetCurrentProcess, OpenProcessToken, ReleaseMutex, WaitForSingleObject, INFINITE,
};

struct OwnedHandle(HANDLE);

impl OwnedHandle {
    fn into_file(self) -> fs::File {
        let raw = self.0 .0 as RawHandle;
        std::mem::forget(self);
        unsafe { fs::File::from_raw_handle(raw) }
    }
}

impl Drop for OwnedHandle {
    fn drop(&mut self) {
        unsafe {
            let _ = CloseHandle(self.0);
        }
    }
}

struct LocalSecurityDescriptor(PSECURITY_DESCRIPTOR);

impl Drop for LocalSecurityDescriptor {
    fn drop(&mut self) {
        unsafe {
            let _ = LocalFree(Some(HLOCAL(self.0 .0)));
        }
    }
}

struct ValidatedParent {
    path: PathBuf,
    handles: Vec<OwnedHandle>,
    root_final: String,
}

fn wide(path: &Path) -> Vec<u16> {
    path.as_os_str().encode_wide().chain(Some(0)).collect()
}

#[cfg(test)]
thread_local! {
    static REPLACE_FILE_TEST_HOOK: std::cell::RefCell<
        Option<Box<dyn FnMut(&Path, &Path, &Path) -> Result<(), u32>>>,
    > = std::cell::RefCell::new(None);
    static OLD_BACKUP_CLEANUP_TEST_HOOK: std::cell::RefCell<
        Option<Box<dyn FnMut(&Path)>>,
    > = std::cell::RefCell::new(None);
    static CREATED_ARTIFACT_CAPTURE_TEST_HOOK: std::cell::RefCell<
        Option<Box<dyn FnMut(&Path)>>,
    > = std::cell::RefCell::new(None);
    static DELETE_FAILURE_TEST_HOOK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

fn replace_file_call(
    destination: &Path,
    replacement: &Path,
    displaced: &Path,
) -> Result<(), windows::core::Error> {
    #[cfg(test)]
    if let Some(result) = REPLACE_FILE_TEST_HOOK.with(|slot| {
        slot.borrow_mut()
            .as_mut()
            .map(|hook| hook(destination, replacement, displaced))
    }) {
        return result
            .map_err(|code| windows::core::Error::from_hresult(HRESULT::from_win32(code)));
    }

    let destination_wide = wide(destination);
    let replacement_wide = wide(replacement);
    let displaced_wide = wide(displaced);
    unsafe {
        ReplaceFileW(
            PCWSTR(destination_wide.as_ptr()),
            PCWSTR(replacement_wide.as_ptr()),
            PCWSTR(displaced_wide.as_ptr()),
            Default::default(),
            None,
            None,
        )
    }
}

const BACKUP_MARKER: &str = ".tirith-backup-v2-";
const DISPLACED_MARKER: &str = ".tirith-displaced-v2-";
const ARTIFACT_RETENTION_LIMIT: usize = 5;

fn hex_bytes(bytes: &[u8]) -> String {
    let mut encoded = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        let _ = write!(&mut encoded, "{byte:02x}");
    }
    encoded
}

fn destination_tag(destination: &Path) -> String {
    let mut hasher = Sha256::new();
    for unit in destination
        .file_name()
        .unwrap_or_default()
        .to_string_lossy()
        .to_lowercase()
        .encode_utf16()
    {
        hasher.update(unit.to_le_bytes());
    }
    let digest = hasher.finalize();
    hex_bytes(&digest[..16])
}

fn content_binding(destination: &Path, size: u64, digest: &[u8; 32]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(b"tirith-setup-backup-v2\0");
    hasher.update(destination_tag(destination).as_bytes());
    hasher.update(size.to_le_bytes());
    hasher.update(digest);
    hex_bytes(&hasher.finalize())
}

fn recovery_binding(destination: &Path, generation: &FileGeneration) -> String {
    let mut hasher = Sha256::new();
    hasher.update(b"tirith-setup-displaced-v2\0");
    hasher.update(destination_tag(destination).as_bytes());
    hasher.update(generation.volume_serial.to_le_bytes());
    hasher.update(generation.file_index.to_le_bytes());
    hasher.update(generation.size.to_le_bytes());
    hasher.update(generation.attributes.to_le_bytes());
    hasher.update(generation.reparse_tag.unwrap_or_default().to_le_bytes());
    hasher.update(generation.digest);
    hasher.update(&generation.security_descriptor);
    hex_bytes(&hasher.finalize())
}

fn timestamp_is_valid(timestamp: &str) -> bool {
    timestamp.len() == 25
        && timestamp.as_bytes()[8] == b'-'
        && timestamp.as_bytes()[15] == b'-'
        && timestamp
            .bytes()
            .enumerate()
            .all(|(index, byte)| index == 8 || index == 15 || byte.is_ascii_digit())
}

fn with_current_user_sid<T>(use_sid: impl FnOnce(PSID) -> T) -> Result<T, String> {
    let mut token = HANDLE::default();
    unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) }
        .map_err(|error| format!("open current process token: {error}"))?;
    let token = OwnedHandle(token);

    let mut required = 0u32;
    let _ = unsafe { GetTokenInformation(token.0, TokenUser, None, 0, &mut required) };
    if required < std::mem::size_of::<TOKEN_USER>() as u32 {
        return Err("query current-user SID size returned an invalid length".into());
    }
    let word = std::mem::size_of::<usize>();
    let mut storage = vec![0usize; (required as usize + word - 1) / word];
    unsafe {
        GetTokenInformation(
            token.0,
            TokenUser,
            Some(storage.as_mut_ptr().cast()),
            required,
            &mut required,
        )
    }
    .map_err(|error| format!("read current-user SID: {error}"))?;
    let token_user = unsafe { &*storage.as_ptr().cast::<TOKEN_USER>() };
    if token_user.User.Sid.0.is_null() {
        return Err("current process token returned a null user SID".into());
    }
    Ok(use_sid(token_user.User.Sid))
}

fn current_user_sid_string() -> Result<String, String> {
    with_current_user_sid(|sid| {
        let mut encoded = PWSTR::null();
        unsafe { ConvertSidToStringSidW(sid, &mut encoded) }
            .map_err(|error| format!("format current-user SID: {error}"))?;
        let decoded = unsafe { encoded.to_string() }
            .map_err(|error| format!("decode current-user SID: {error}"));
        unsafe {
            let _ = LocalFree(Some(HLOCAL(encoded.0.cast())));
        }
        decoded
    })?
}

/// Re-apply a preserved owner + group + DACL to the file `ReplaceFileW` just
/// published, and return the refreshed generation observed through the same
/// held handle after the write.
///
/// `ReplaceFileW` MERGES ACLs rather than preserving them: the replaced file's
/// ACEs are copied onto the replacement as EXPLICIT entries, auto-inheritance
/// re-applies the parent's inheritable ACEs on top, and the owner is not
/// restored at all. Asserting byte-identity after the call therefore asserts
/// something the API never promised — it holds only where the parent has no
/// inheritable ACEs AND the owner happens to match. The same trap applies to
/// `SetSecurityInfo`: it feeds the provided DACL through the auto-inheritance
/// machinery, which strips `INHERITED_ACE` flags into explicit entries and
/// appends freshly recomputed inherited ACEs — the result is never the
/// preserved bytes. `SetKernelObjectSecurity` writes the descriptor literally
/// (no inheritance recomputation), so the preserved DACL — including its
/// `INHERITED_ACE`-flagged entries and `SE_DACL_PROTECTED` state — lands
/// byte-for-byte. `SE_DACL_AUTO_INHERITED` is the one control bit a literal
/// write clears unless explicitly re-requested, so it is carried across via
/// `SE_DACL_AUTO_INHERIT_REQ`. The caller's byte-for-byte comparison then
/// verifies that all of this actually landed.
///
/// The handle is opened no-reparse, share-read only, and its generation must
/// equal the replacement that was just installed, so the restore cannot be
/// redirected onto a different file between the replace and this call.
/// `WRITE_OWNER` is requested only when the owner or group actually needs to
/// change, so an unprivileged publication over a file the caller owns never
/// demands rights it does not have.
fn restore_preserved_security(
    path: &Path,
    installed: &FileGeneration,
    preserved: &[u8],
) -> Result<FileGeneration, String> {
    let mut owned = preserved.to_vec();
    let descriptor = PSECURITY_DESCRIPTOR(owned.as_mut_ptr().cast());

    let mut control = 0u16;
    let mut revision = 0u32;
    unsafe { GetSecurityDescriptorControl(descriptor, &mut control, &mut revision) }
        .map_err(|error| format!("read preserved descriptor control: {error}"))?;

    let mut preserved_owner = PSID::default();
    let mut defaulted = BOOL(0);
    unsafe { GetSecurityDescriptorOwner(descriptor, &mut preserved_owner, &mut defaulted) }
        .map_err(|error| format!("read preserved owner: {error}"))?;
    let mut preserved_group = PSID::default();
    unsafe { GetSecurityDescriptorGroup(descriptor, &mut preserved_group, &mut defaulted) }
        .map_err(|error| format!("read preserved group: {error}"))?;

    // Decide whether the principal components actually changed, using the
    // installed descriptor the caller just captured. Owner/group writes need
    // `WRITE_OWNER`; a DACL write only needs `WRITE_DAC`, which the file's
    // owner always holds. Restoring only what drifted keeps the common
    // unprivileged path (same owner, merged DACL) working.
    let mut installed_bytes = installed.security_descriptor.clone();
    let installed_descriptor = PSECURITY_DESCRIPTOR(installed_bytes.as_mut_ptr().cast());
    let mut installed_owner = PSID::default();
    unsafe {
        GetSecurityDescriptorOwner(installed_descriptor, &mut installed_owner, &mut defaulted)
    }
    .map_err(|error| format!("read installed owner: {error}"))?;
    let mut installed_group = PSID::default();
    unsafe {
        GetSecurityDescriptorGroup(installed_descriptor, &mut installed_group, &mut defaulted)
    }
    .map_err(|error| format!("read installed group: {error}"))?;
    let sids_equal = |a: PSID, b: PSID| -> bool {
        if a.is_invalid() || b.is_invalid() {
            return a.is_invalid() && b.is_invalid();
        }
        unsafe { EqualSid(a, b) }.is_ok()
    };
    let owner_changes = !sids_equal(preserved_owner, installed_owner);
    let group_changes = !sids_equal(preserved_group, installed_group);
    let needs_write_owner = owner_changes || group_changes;

    let path_wide = wide(path);
    let open_with = |rights: u32| unsafe {
        CreateFileW(
            PCWSTR(path_wide.as_ptr()),
            rights,
            FILE_SHARE_READ,
            None,
            OPEN_EXISTING,
            FILE_FLAG_OPEN_REPARSE_POINT,
            None,
        )
    };
    let base_rights = FILE_GENERIC_READ | READ_CONTROL | FILE_READ_ATTRIBUTES | WRITE_DAC;
    let handle = if needs_write_owner {
        open_with((base_rights | WRITE_OWNER).0).map_err(|error| {
            format!(
                "reopen {} with WRITE_OWNER to restore its preserved owner: {error}",
                path.display()
            )
        })?
    } else {
        open_with(base_rights.0).map_err(|error| {
            format!(
                "reopen {} to restore its preserved security descriptor: {error}",
                path.display()
            )
        })?
    };
    let held = OwnedHandle(handle).into_file();
    let (held, _, generation) = capture_stable_file(held, path)?;
    if !generation.same_identity(installed) {
        return Err(format!(
            "{} is no longer the identity just published; refusing to write its security descriptor",
            path.display()
        ));
    }

    // A literal descriptor write stores `SE_DACL_AUTO_INHERITED` only when the
    // request bit accompanies it; without this, restoring a descriptor from an
    // auto-inherited tree would drop the flag and fail the byte comparison.
    if control & SE_DACL_AUTO_INHERITED.0 != 0 {
        unsafe {
            SetSecurityDescriptorControl(
                descriptor,
                SE_DACL_AUTO_INHERIT_REQ,
                SE_DACL_AUTO_INHERIT_REQ,
            )
        }
        .map_err(|error| format!("request preserved auto-inherit state: {error}"))?;
    }

    let mut information = DACL_SECURITY_INFORMATION;
    if owner_changes {
        information |= OWNER_SECURITY_INFORMATION;
    }
    if group_changes {
        information |= GROUP_SECURITY_INFORMATION;
    }
    unsafe { SetKernelObjectSecurity(HANDLE(held.as_raw_handle()), information, descriptor) }
        .map_err(|error| {
            format!(
                "restore preserved security descriptor on {}: {error}",
                path.display()
            )
        })?;

    // Re-observe through the SAME handle so the caller compares the exact
    // post-restore state with no path re-resolution in between.
    let (_held, _, refreshed) = capture_stable_file(held, path)?;
    if !refreshed.same_identity(installed) {
        return Err(format!(
            "{} changed identity while its security descriptor was being restored",
            path.display()
        ));
    }
    Ok(refreshed)
}

/// Render a self-relative security descriptor as SDDL for diagnostics.
///
/// A byte length names nothing an operator can act on. SDDL names the owner,
/// the group, and every ACE, so a publication mismatch reports WHICH access
/// changed. This is diagnostic only: on failure it falls back to the length so
/// the renderer can never be the reason a mismatch goes unreported.
fn describe_security_descriptor(bytes: &[u8]) -> String {
    if bytes.is_empty() {
        return "<empty>".to_string();
    }
    let mut owned = bytes.to_vec();
    let descriptor = PSECURITY_DESCRIPTOR(owned.as_mut_ptr().cast());
    let mut encoded = PWSTR::null();
    if unsafe {
        ConvertSecurityDescriptorToStringSecurityDescriptorW(
            descriptor,
            SDDL_REVISION_1,
            OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
            &mut encoded,
            None,
        )
    }
    .is_err()
    {
        return format!("{} bytes, unrenderable", bytes.len());
    }
    let rendered = unsafe { encoded.to_string() };
    unsafe {
        let _ = LocalFree(Some(HLOCAL(encoded.0.cast())));
    }
    rendered.unwrap_or_else(|_| format!("{} bytes, undecodable", bytes.len()))
}

fn owner_is_current_user(owner: PSID) -> bool {
    with_current_user_sid(|current| unsafe { EqualSid(owner, current) }.is_ok()).unwrap_or(false)
}

fn owner_only_security_descriptor(bytes: &[u8]) -> bool {
    if bytes.is_empty() {
        return false;
    }
    let mut descriptor_bytes = bytes.to_vec();
    let descriptor = PSECURITY_DESCRIPTOR(descriptor_bytes.as_mut_ptr().cast());
    let mut control = 0u16;
    let mut revision = 0u32;
    if unsafe { GetSecurityDescriptorControl(descriptor, &mut control, &mut revision) }.is_err()
        || control & SE_DACL_PROTECTED.0 == 0
    {
        return false;
    }
    let mut present = BOOL(0);
    let mut defaulted = BOOL(0);
    let mut dacl: *mut ACL = std::ptr::null_mut();
    if unsafe { GetSecurityDescriptorDacl(descriptor, &mut present, &mut dacl, &mut defaulted) }
        .is_err()
        || !present.as_bool()
        || dacl.is_null()
    {
        return false;
    }
    let mut size = ACL_SIZE_INFORMATION::default();
    if unsafe {
        GetAclInformation(
            dacl,
            (&mut size as *mut ACL_SIZE_INFORMATION).cast(),
            std::mem::size_of::<ACL_SIZE_INFORMATION>() as u32,
            AclSizeInformation,
        )
    }
    .is_err()
        || size.AceCount != 1
    {
        return false;
    }
    let mut ace: *mut std::ffi::c_void = std::ptr::null_mut();
    if unsafe { GetAce(dacl, 0, &mut ace) }.is_err() || ace.is_null() {
        return false;
    }
    let ace = ace.cast::<ACCESS_ALLOWED_ACE>();
    if unsafe { (*ace).Header.AceType != 0 || (*ace).Mask != FILE_ALL_ACCESS.0 } {
        return false;
    }
    let mut owner = PSID::default();
    if unsafe { GetSecurityDescriptorOwner(descriptor, &mut owner, &mut defaulted) }.is_err()
        || owner.0.is_null()
    {
        return false;
    }
    let ace_sid = unsafe { PSID((&mut (*ace).SidStart as *mut u32).cast()) };
    owner_is_current_user(owner) && unsafe { EqualSid(owner, ace_sid) }.is_ok()
}

fn backup_name(destination: &Path, bytes: &[u8]) -> String {
    let digest: [u8; 32] = Sha256::digest(bytes).into();
    format!(
        "{BACKUP_MARKER}{}-{}_{}_{}",
        destination_tag(destination),
        chrono::Local::now().format("%Y%m%d-%H%M%S-%9f"),
        content_binding(destination, bytes.len() as u64, &digest),
        uuid::Uuid::new_v4().simple()
    )
}

fn backup_name_matches(path: &Path, destination: &Path, generation: &FileGeneration) -> bool {
    let candidate = path.file_name().unwrap_or_default().to_string_lossy();
    let prefix = format!("{BACKUP_MARKER}{}-", destination_tag(destination));
    let Some(rest) = candidate.strip_prefix(&prefix) else {
        return false;
    };
    let mut fields = rest.split('_');
    let timestamp = fields.next();
    let binding = fields.next();
    let nonce = fields.next();
    fields.next().is_none()
        && timestamp.is_some_and(timestamp_is_valid)
        && binding
            == Some(content_binding(destination, generation.size, &generation.digest).as_str())
        && nonce.is_some_and(|value| {
            value.len() == 32 && value.bytes().all(|byte| byte.is_ascii_hexdigit())
        })
        && generation.reparse_tag.is_none()
        && path_rules::attributes_are_safe(generation.attributes, false)
        && owner_only_security_descriptor(&generation.security_descriptor)
}

fn displaced_name_matches(path: &Path, destination: &Path, generation: &FileGeneration) -> bool {
    let candidate = path.file_name().unwrap_or_default().to_string_lossy();
    let prefix = format!("{DISPLACED_MARKER}{}-", destination_tag(destination));
    let Some(rest) = candidate.strip_prefix(&prefix) else {
        return false;
    };
    let mut fields = rest.split('_');
    let timestamp = fields.next();
    let binding = fields.next();
    let nonce = fields.next();
    fields.next().is_none()
        && timestamp.is_some_and(timestamp_is_valid)
        && binding == Some(recovery_binding(destination, generation).as_str())
        && nonce.is_some_and(|value| {
            value.len() == 32 && value.bytes().all(|byte| byte.is_ascii_hexdigit())
        })
}

fn new_displaced_path(destination: &Path, expected: &FileGeneration) -> Result<PathBuf, String> {
    let parent = destination
        .parent()
        .ok_or_else(|| format!("no parent for {}", destination.display()))?;
    // The UUID is passed directly to ReplaceFileW. A preflight existence
    // check would merely create a check/use race and is deliberately absent.
    Ok(parent.join(format!(
        "{DISPLACED_MARKER}{}-{}_{}_{}",
        destination_tag(destination),
        chrono::Local::now().format("%Y%m%d-%H%M%S-%9f"),
        recovery_binding(destination, expected),
        uuid::Uuid::new_v4().simple()
    )))
}

fn is_win32(error: &windows::core::Error, code: u32) -> bool {
    error.code() == HRESULT::from_win32(code)
}

fn final_path(handle: HANDLE) -> Result<String, String> {
    let mut buffer = vec![0u16; 512];
    loop {
        let length = unsafe { GetFinalPathNameByHandleW(handle, &mut buffer, Default::default()) };
        if length == 0 {
            return Err(format!(
                "GetFinalPathNameByHandleW: {}",
                std::io::Error::last_os_error()
            ));
        }
        if (length as usize) < buffer.len() {
            return Ok(String::from_utf16_lossy(&buffer[..length as usize]));
        }
        buffer.resize(length as usize + 1, 0);
    }
}

fn reparse_tag(handle: HANDLE) -> Result<u32, String> {
    let mut info = FILE_ATTRIBUTE_TAG_INFO::default();
    unsafe {
        GetFileInformationByHandleEx(
            handle,
            FileAttributeTagInfo,
            (&mut info as *mut FILE_ATTRIBUTE_TAG_INFO).cast(),
            std::mem::size_of::<FILE_ATTRIBUTE_TAG_INFO>() as u32,
        )
    }
    .map_err(|error| format!("inspect reparse tag: {error}"))?;
    Ok(info.ReparseTag)
}

fn open_directory(path: &Path) -> Result<Option<OwnedHandle>, String> {
    let path_wide = wide(path);
    let handle = match unsafe {
        CreateFileW(
            PCWSTR(path_wide.as_ptr()),
            (FILE_LIST_DIRECTORY | FILE_TRAVERSE | FILE_READ_ATTRIBUTES).0,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            None,
            OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
            None,
        )
    } {
        Ok(handle) => handle,
        Err(error)
            if is_win32(&error, ERROR_FILE_NOT_FOUND.0)
                || is_win32(&error, ERROR_PATH_NOT_FOUND.0) =>
        {
            return Ok(None)
        }
        Err(error) => return Err(format!("open directory handle {}: {error}", path.display())),
    };
    let owned = OwnedHandle(handle);
    let mut info = BY_HANDLE_FILE_INFORMATION::default();
    unsafe { GetFileInformationByHandle(handle, &mut info) }
        .map_err(|e| format!("inspect directory handle {}: {e}", path.display()))?;
    if !path_rules::attributes_are_safe(info.dwFileAttributes, true) {
        if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT.0 != 0 {
            let tag = reparse_tag(handle)?;
            let redirects = path_rules::reparse_tag_redirects_name(tag);
            return Err(format!(
                "{} is a reparse point (tag 0x{tag:08x}, name_redirect={redirects}) — refusing for safety",
                path.display(),
            ));
        }
        return Err(format!("{} is not a directory", path.display()));
    }
    Ok(Some(owned))
}

fn open_or_create_directory(
    current: &mut PathBuf,
    component: &OsStr,
    handles: &mut Vec<OwnedHandle>,
    create: bool,
) -> Result<bool, String> {
    current.push(component);
    let component_handle = match open_directory(current)? {
        Some(handle) => handle,
        None if !create => return Ok(false),
        None => {
            let current_wide = wide(current);
            if let Err(error) = unsafe { CreateDirectoryW(PCWSTR(current_wide.as_ptr()), None) } {
                if !is_win32(&error, ERROR_ALREADY_EXISTS.0) {
                    return Err(format!("create directory {}: {error}", current.display()));
                }
            }
            open_directory(current)?.ok_or_else(|| {
                format!("{} disappeared after directory creation", current.display())
            })?
        }
    };
    handles.push(component_handle);
    Ok(true)
}

fn validated_parent(
    path: &Path,
    scope_root: &Path,
    create: bool,
) -> Result<Option<ValidatedParent>, String> {
    let path = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(|e| format!("current_dir: {e}"))?
            .join(path)
    };
    let root = if scope_root.is_absolute() {
        scope_root.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(|e| format!("current_dir: {e}"))?
            .join(scope_root)
    };
    let relative = path.strip_prefix(&root).map_err(|_| {
        format!(
            "{} is outside trusted setup root {}",
            path.display(),
            root.display()
        )
    })?;
    let mut relative_parts: Vec<_> = relative.components().collect();
    if relative_parts.pop().is_none() {
        return Err(format!(
            "{} names the trusted root, not a file",
            path.display()
        ));
    }
    if relative_parts
        .iter()
        .any(|part| !matches!(part, std::path::Component::Normal(_)))
    {
        return Err(format!(
            "{} contains a non-normal path component",
            path.display()
        ));
    }

    let mut anchor = root.clone();
    let mut missing = Vec::new();
    while !anchor.exists() {
        missing.push(
            anchor
                .file_name()
                .ok_or_else(|| format!("cannot resolve {}", root.display()))?
                .to_os_string(),
        );
        if !anchor.pop() {
            return Err(format!("cannot resolve {}", root.display()));
        }
    }
    if !missing.is_empty() && !create {
        return Ok(None);
    }
    let mut current = anchor
        .canonicalize()
        .map_err(|e| format!("canonicalize trusted root {}: {e}", anchor.display()))?;
    let mut handles = vec![open_directory(&current)?
        .ok_or_else(|| format!("trusted root {} disappeared", current.display()))?];

    for component in missing.iter().rev() {
        if !open_or_create_directory(&mut current, component, &mut handles, create)? {
            return Ok(None);
        }
    }
    // Capture the final path of the requested scope root itself, rather than
    // its nearest pre-existing ancestor when the scope had to be created.
    let root_final = final_path(handles.last().expect("root handle exists").0)?;

    for component in relative_parts.iter().filter_map(|part| match part {
        std::path::Component::Normal(name) => Some(*name),
        _ => None,
    }) {
        if !open_or_create_directory(&mut current, component, &mut handles, create)? {
            return Ok(None);
        }
    }

    let parent_final = final_path(handles.last().expect("anchor handle exists").0)?;
    if !path_rules::final_path_within(&root_final, &parent_final) {
        return Err(format!(
            "{} resolves outside trusted setup root",
            current.display()
        ));
    }
    Ok(Some(ValidatedParent {
        path: current,
        handles,
        root_final,
    }))
}

fn open_existing(path: &Path) -> Result<Option<OwnedHandle>, String> {
    let path_wide = wide(path);
    let handle = match unsafe {
        CreateFileW(
            PCWSTR(path_wide.as_ptr()),
            (FILE_GENERIC_READ | READ_CONTROL | FILE_READ_ATTRIBUTES).0,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            None,
            OPEN_EXISTING,
            FILE_FLAG_OPEN_REPARSE_POINT,
            None,
        )
    } {
        Ok(handle) => handle,
        Err(error)
            if is_win32(&error, ERROR_FILE_NOT_FOUND.0)
                || is_win32(&error, ERROR_PATH_NOT_FOUND.0) =>
        {
            return Ok(None)
        }
        Err(error) => return Err(format!("open destination {}: {error}", path.display())),
    };
    let owned = OwnedHandle(handle);
    let mut info = BY_HANDLE_FILE_INFORMATION::default();
    unsafe { GetFileInformationByHandle(handle, &mut info) }
        .map_err(|e| format!("inspect destination {}: {e}", path.display()))?;
    if !path_rules::attributes_are_safe(info.dwFileAttributes, false) {
        if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT.0 != 0 {
            let tag = reparse_tag(handle)?;
            let redirects = path_rules::reparse_tag_redirects_name(tag);
            return Err(format!(
                "{} is a reparse point (tag 0x{tag:08x}, name_redirect={redirects}) — refusing for safety",
                path.display(),
            ));
        }
        return Err(format!("{} is not a regular file", path.display()));
    }
    Ok(Some(owned))
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct FileGeneration {
    volume_serial: u32,
    file_index: u64,
    size: u64,
    last_write: u64,
    attributes: u32,
    reparse_tag: Option<u32>,
    digest: [u8; 32],
    security_descriptor: Vec<u8>,
}

impl FileGeneration {
    fn from_observation(
        info: &BY_HANDLE_FILE_INFORMATION,
        reparse_tag: Option<u32>,
        digest: [u8; 32],
        security_descriptor: Vec<u8>,
    ) -> Self {
        Self {
            volume_serial: info.dwVolumeSerialNumber,
            file_index: ((info.nFileIndexHigh as u64) << 32) | info.nFileIndexLow as u64,
            size: ((info.nFileSizeHigh as u64) << 32) | info.nFileSizeLow as u64,
            last_write: ((info.ftLastWriteTime.dwHighDateTime as u64) << 32)
                | info.ftLastWriteTime.dwLowDateTime as u64,
            attributes: info.dwFileAttributes,
            reparse_tag,
            digest,
            security_descriptor,
        }
    }

    fn same_identity(&self, other: &Self) -> bool {
        self.volume_serial == other.volume_serial && self.file_index == other.file_index
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum SnapshotGeneration {
    Absent,
    Present(FileGeneration),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PlatformSnapshot {
    pub(crate) bytes: Option<Vec<u8>>,
    pub(crate) mode: Option<u32>,
    generation: SnapshotGeneration,
}

impl PlatformSnapshot {
    fn absent() -> Self {
        Self {
            bytes: None,
            mode: None,
            generation: SnapshotGeneration::Absent,
        }
    }
}

fn handle_information(handle: HANDLE, path: &Path) -> Result<BY_HANDLE_FILE_INFORMATION, String> {
    let mut info = BY_HANDLE_FILE_INFORMATION::default();
    unsafe { GetFileInformationByHandle(handle, &mut info) }
        .map_err(|error| format!("inspect {} through open handle: {error}", path.display()))?;
    Ok(info)
}

fn security_descriptor(handle: HANDLE, path: &Path) -> Result<Vec<u8>, String> {
    let mut descriptor = PSECURITY_DESCRIPTOR::default();
    let status = unsafe {
        GetSecurityInfo(
            handle,
            SE_FILE_OBJECT,
            OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
            None,
            None,
            None,
            None,
            Some(&mut descriptor),
        )
    };
    if status.0 != 0 {
        return Err(format!(
            "read {} DACL security metadata: error {}",
            path.display(),
            status.0
        ));
    }
    let descriptor = LocalSecurityDescriptor(descriptor);
    let length = unsafe { GetSecurityDescriptorLength(descriptor.0) } as usize;
    if length == 0 {
        return Err(format!("read {} empty security descriptor", path.display()));
    }
    let bytes =
        unsafe { std::slice::from_raw_parts(descriptor.0 .0.cast::<u8>(), length).to_vec() };
    Ok(bytes)
}

fn optional_reparse_tag(
    handle: HANDLE,
    info: &BY_HANDLE_FILE_INFORMATION,
) -> Result<Option<u32>, String> {
    if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT.0 == 0 {
        Ok(None)
    } else {
        reparse_tag(handle).map(Some)
    }
}

/// Whether a live observation proves the exact competing file object landed
/// back, for the post-rollback verification specifically. The rollback is
/// itself a `ReplaceFileW`, which rewrites the security descriptor of
/// whichever file it installs (the same merge behavior the publication
/// restore exists to undo), so byte-identical generations — descriptor and
/// timestamps included — are not something a rollback can promise. Identity,
/// size, content digest, and reparse state are what prove the competitor is
/// back; the descriptor it then carries is its own business.
fn rollback_landed(live: Option<&FileGeneration>, expected: Option<&FileGeneration>) -> bool {
    match (live, expected) {
        (Some(live), Some(expected)) => {
            live.same_identity(expected)
                && live.size == expected.size
                && live.digest == expected.digest
                && live.reparse_tag == expected.reparse_tag
        }
        _ => false,
    }
}

fn capture_once(file: &mut fs::File, path: &Path) -> Result<(Vec<u8>, FileGeneration), String> {
    let handle = HANDLE(file.as_raw_handle());
    file.seek(SeekFrom::Start(0))
        .map_err(|error| format!("seek {} through open handle: {error}", path.display()))?;
    let before = handle_information(handle, path)?;
    let before_security = security_descriptor(handle, path)?;
    let before_reparse = optional_reparse_tag(handle, &before)?;
    let before_size = ((before.nFileSizeHigh as u64) << 32) | before.nFileSizeLow as u64;
    if before_size > super::fs_transaction::MAX_SETUP_FILE_BYTES as u64 {
        return Err(format!(
            "{} exceeds setup file limit of {} bytes",
            path.display(),
            super::fs_transaction::MAX_SETUP_FILE_BYTES
        ));
    }

    let mut bytes = Vec::with_capacity(before_size as usize);
    (&mut *file)
        .take(super::fs_transaction::MAX_SETUP_FILE_BYTES as u64 + 1)
        .read_to_end(&mut bytes)
        .map_err(|error| format!("read {} through open handle: {error}", path.display()))?;
    if bytes.len() > super::fs_transaction::MAX_SETUP_FILE_BYTES {
        return Err(format!(
            "{} exceeds setup file limit of {} bytes",
            path.display(),
            super::fs_transaction::MAX_SETUP_FILE_BYTES
        ));
    }

    let after = handle_information(handle, path)?;
    let after_security = security_descriptor(handle, path)?;
    let after_reparse = optional_reparse_tag(handle, &after)?;
    let stable_metadata = before.dwVolumeSerialNumber == after.dwVolumeSerialNumber
        && before.nFileIndexHigh == after.nFileIndexHigh
        && before.nFileIndexLow == after.nFileIndexLow
        && before.nFileSizeHigh == after.nFileSizeHigh
        && before.nFileSizeLow == after.nFileSizeLow
        && before.ftLastWriteTime == after.ftLastWriteTime
        && before.dwFileAttributes == after.dwFileAttributes
        && before_security == after_security
        && before_reparse == after_reparse;
    let after_size = ((after.nFileSizeHigh as u64) << 32) | after.nFileSizeLow as u64;
    if !stable_metadata || bytes.len() as u64 != after_size {
        return Err(format!("{} changed while being read", path.display()));
    }
    let digest: [u8; 32] = Sha256::digest(&bytes).into();
    Ok((
        bytes,
        FileGeneration::from_observation(&after, after_reparse, digest, after_security),
    ))
}

fn capture_stable_file(
    mut file: fs::File,
    path: &Path,
) -> Result<(fs::File, Vec<u8>, FileGeneration), String> {
    let mut previous = capture_once(&mut file, path)?;
    for _ in 0..3 {
        let current = capture_once(&mut file, path)?;
        if current == previous {
            return Ok((file, current.0, current.1));
        }
        previous = current;
    }
    Err(format!(
        "{} changed repeatedly while being read; retry setup",
        path.display()
    ))
}

fn generation_at(path: &Path) -> Result<Option<FileGeneration>, String> {
    let Some(handle) = open_existing(path)? else {
        return Ok(None);
    };
    let (_, _, generation) = capture_stable_file(handle.into_file(), path)?;
    Ok(Some(generation))
}

fn open_cleanup_handle(path: &Path) -> Result<Option<OwnedHandle>, String> {
    let path_wide = wide(path);
    let handle = match unsafe {
        CreateFileW(
            PCWSTR(path_wide.as_ptr()),
            (FILE_GENERIC_READ | READ_CONTROL | FILE_READ_ATTRIBUTES | DELETE).0,
            // Cleanup and recovery artifacts must never grant write sharing.
            // The held DELETE-capable handle therefore blocks both pathname
            // replacement and non-cooperating writers until commit/release.
            FILE_SHARE_READ,
            None,
            OPEN_EXISTING,
            FILE_FLAG_OPEN_REPARSE_POINT,
            None,
        )
    } {
        Ok(handle) => handle,
        Err(error)
            if is_win32(&error, ERROR_FILE_NOT_FOUND.0)
                || is_win32(&error, ERROR_PATH_NOT_FOUND.0) =>
        {
            return Ok(None)
        }
        Err(error) => {
            return Err(format!(
                "open {} for identity-bound cleanup: {error}",
                path.display()
            ))
        }
    };
    let owned = OwnedHandle(handle);
    let info = handle_information(handle, path)?;
    if !path_rules::attributes_are_safe(info.dwFileAttributes, false) {
        return Err(format!(
            "{} is not a safe regular file for cleanup",
            path.display()
        ));
    }
    Ok(Some(owned))
}

fn mark_held_file_for_deletion(file: &fs::File) -> Result<(), String> {
    #[cfg(test)]
    if DELETE_FAILURE_TEST_HOOK.with(std::cell::Cell::get) {
        return Err("injected exact-handle deletion failure".into());
    }
    let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
    unsafe {
        SetFileInformationByHandle(
            HANDLE(file.as_raw_handle()),
            FileDispositionInfo,
            (&disposition as *const FILE_DISPOSITION_INFO).cast(),
            std::mem::size_of::<FILE_DISPOSITION_INFO>() as u32,
        )
    }
    .map_err(|error| format!("delete exact held transaction identity: {error}"))
}

struct CleanupCapability {
    file: fs::File,
    generation: FileGeneration,
}

impl CleanupCapability {
    fn from_created(file: fs::File, path: &Path, intended: &[u8]) -> Result<Self, String> {
        #[cfg(test)]
        CREATED_ARTIFACT_CAPTURE_TEST_HOOK.with(|slot| {
            if let Some(hook) = slot.borrow_mut().as_mut() {
                hook(path);
            }
        });

        // Capture through a duplicate while retaining the original creation
        // handle. There is no close/reopen interval in which the pathname can
        // be swapped and subsequently trusted as Tirith's artifact.
        let duplicate = match file.try_clone() {
            Ok(duplicate) => duplicate,
            Err(error) => {
                let cleanup = mark_held_file_for_deletion(&file)
                    .err()
                    .map(|cleanup| format!("; cleanup also failed: {cleanup}"))
                    .unwrap_or_default();
                return Err(format!(
                    "clone newly-created artifact handle: {error}{cleanup}"
                ));
            }
        };
        let captured = capture_stable_file(duplicate, path);
        let (_, bytes, generation) = match captured {
            Ok(captured) => captured,
            Err(error) => {
                let cleanup = mark_held_file_for_deletion(&file)
                    .err()
                    .map(|cleanup| format!("; cleanup also failed: {cleanup}"))
                    .unwrap_or_default();
                return Err(format!(
                    "validate newly-created transaction artifact: {error}{cleanup}"
                ));
            }
        };
        if bytes != intended {
            let cleanup = mark_held_file_for_deletion(&file)
                .err()
                .map(|cleanup| format!("; cleanup also failed: {cleanup}"))
                .unwrap_or_default();
            return Err(format!(
                "newly-created transaction artifact did not contain the intended bytes{cleanup}"
            ));
        }
        if generation.reparse_tag.is_some()
            || !path_rules::attributes_are_safe(generation.attributes, false)
            || !owner_only_security_descriptor(&generation.security_descriptor)
        {
            let cleanup = mark_held_file_for_deletion(&file)
                .err()
                .map(|cleanup| format!("; cleanup also failed: {cleanup}"))
                .unwrap_or_default();
            return Err(format!(
                "newly-created transaction artifact did not retain its intended owner-only non-reparse security state{cleanup}"
            ));
        }
        Ok(Self { file, generation })
    }

    fn open(path: &Path) -> Result<Self, String> {
        let handle = open_cleanup_handle(path)?
            .ok_or_else(|| format!("transaction artifact disappeared at {}", path.display()))?;
        let (file, _, generation) = capture_stable_file(handle.into_file(), path)?;
        Ok(Self { file, generation })
    }

    fn open_exact(path: &Path, expected: &FileGeneration) -> Result<Option<Self>, String> {
        let Some(handle) = open_cleanup_handle(path)? else {
            return Ok(None);
        };
        let (file, _, generation) = capture_stable_file(handle.into_file(), path)?;
        let capability = Self { file, generation };
        if &capability.generation != expected {
            return Ok(None);
        }
        Ok(Some(capability))
    }

    fn validate(&mut self, path: &Path) -> Result<(), String> {
        let (_, _, generation) = capture_stable_file(
            self.file
                .try_clone()
                .map_err(|error| format!("clone held cleanup handle: {error}"))?,
            path,
        )?;
        if generation != self.generation {
            return Err(format!(
                "{} changed through its held cleanup handle",
                path.display()
            ));
        }
        Ok(())
    }

    fn delete(self) -> Result<(), String> {
        mark_held_file_for_deletion(&self.file)
    }
}

struct HeldIdentity {
    path: PathBuf,
    file: fs::File,
    generation: FileGeneration,
}

impl HeldIdentity {
    fn open_exact(path: PathBuf, expected: &FileGeneration) -> Result<Self, String> {
        let handle = open_existing(&path)?
            .ok_or_else(|| format!("exact recovery identity disappeared at {}", path.display()))?;
        let (file, _, generation) = capture_stable_file(handle.into_file(), &path)?;
        if &generation != expected {
            return Err(format!(
                "recovery identity at {} did not match the displaced original",
                path.display()
            ));
        }
        Ok(Self {
            path,
            file,
            generation,
        })
    }

    fn validate(&self) -> Result<(), String> {
        let (_, _, generation) = capture_stable_file(
            self.file
                .try_clone()
                .map_err(|error| format!("clone held recovery handle: {error}"))?,
            &self.path,
        )?;
        if generation != self.generation {
            return Err(format!(
                "held recovery identity at {} changed",
                self.path.display()
            ));
        }
        Ok(())
    }
}

fn snapshot_destination(
    destination: &Path,
    display_path: &Path,
) -> Result<PlatformSnapshot, String> {
    let Some(handle) = open_existing(destination)? else {
        return Ok(PlatformSnapshot::absent());
    };
    let (_, bytes, generation) = capture_stable_file(handle.into_file(), display_path)?;
    Ok(PlatformSnapshot {
        bytes: Some(bytes),
        mode: None,
        generation: SnapshotGeneration::Present(generation),
    })
}

pub(crate) fn read_snapshot_scoped(
    path: &Path,
    scope_root: &Path,
) -> Result<PlatformSnapshot, String> {
    let Some(parent) = validated_parent(path, scope_root, false)? else {
        return Ok(PlatformSnapshot::absent());
    };
    let destination = parent.path.join(
        path.file_name()
            .ok_or_else(|| format!("no file name for {}", path.display()))?,
    );
    let snapshot = snapshot_destination(&destination, path)?;
    drop(parent);
    Ok(snapshot)
}

/// Read through validated, retained no-reparse parent handles with a strict
/// cap. Missing files or parents return `None` without creating directories.
pub fn read_to_string_scoped(path: &Path, scope_root: &Path) -> Result<Option<String>, String> {
    read_snapshot_scoped(path, scope_root)?
        .bytes
        .map(|bytes| {
            String::from_utf8(bytes)
                .map_err(|error| format!("{} is not valid UTF-8: {error}", path.display()))
        })
        .transpose()
}

/// Return whether a destination's complete parent chain currently exists and
/// is safe beneath `scope_root`, without creating anything.
pub fn parent_exists_scoped(path: &Path, scope_root: &Path) -> Result<bool, String> {
    validated_parent(path, scope_root, false).map(|parent| parent.is_some())
}

fn owner_only_descriptor() -> Result<LocalSecurityDescriptor, String> {
    let sid = current_user_sid_string()?;
    let sddl = format!("O:{sid}D:P(A;;FA;;;{sid})");
    let sddl_wide = sddl.encode_utf16().chain(Some(0)).collect::<Vec<_>>();
    let mut descriptor = PSECURITY_DESCRIPTOR::default();
    unsafe {
        ConvertStringSecurityDescriptorToSecurityDescriptorW(
            PCWSTR(sddl_wide.as_ptr()),
            SDDL_REVISION_1,
            &mut descriptor,
            None,
        )
    }
    .map_err(|e| format!("build owner-only security descriptor: {e}"))?;
    Ok(LocalSecurityDescriptor(descriptor))
}

fn transaction_mutex_name(path: &Path, scope_root: &Path) -> Result<Vec<u16>, String> {
    let current = std::env::current_dir().map_err(|error| format!("current_dir: {error}"))?;
    let absolute_path = if path.is_absolute() {
        path.to_path_buf()
    } else {
        current.join(path)
    };
    let absolute_root = if scope_root.is_absolute() {
        scope_root.to_path_buf()
    } else {
        current.join(scope_root)
    };
    let mut hasher = Sha256::new();
    for unit in absolute_root
        .to_string_lossy()
        .to_lowercase()
        .encode_utf16()
    {
        hasher.update(unit.to_le_bytes());
    }
    hasher.update([0]);
    for unit in absolute_path
        .to_string_lossy()
        .to_lowercase()
        .encode_utf16()
    {
        hasher.update(unit.to_le_bytes());
    }
    let mut lock_name = String::from("Local\\TirithSetup-");
    for byte in hasher.finalize() {
        let _ = write!(&mut lock_name, "{byte:02x}");
    }
    Ok(lock_name.encode_utf16().chain(Some(0)).collect())
}

fn open_transaction_mutex(path: &Path, scope_root: &Path) -> Result<OwnedHandle, String> {
    let name = transaction_mutex_name(path, scope_root)?;
    let owner_only = owner_only_descriptor()?;
    let security_attributes = SECURITY_ATTRIBUTES {
        nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
        lpSecurityDescriptor: owner_only.0 .0,
        bInheritHandle: BOOL(0),
    };
    let handle = unsafe { CreateMutexW(Some(&security_attributes), false, PCWSTR(name.as_ptr())) }
        .map_err(|error| format!("open owner-only setup transaction mutex: {error}"))?;
    Ok(OwnedHandle(handle))
}

pub(crate) struct PlatformLock {
    mutex: OwnedHandle,
    owned: bool,
}

impl Drop for PlatformLock {
    fn drop(&mut self) {
        if self.owned {
            unsafe {
                let _ = ReleaseMutex(self.mutex.0);
            }
        }
    }
}

pub(crate) struct PlatformTransaction {
    parent: ValidatedParent,
    destination: PathBuf,
    display_path: PathBuf,
    _lock: PlatformLock,
    published_generation: std::cell::RefCell<Option<FileGeneration>>,
    published_recovery: RefCell<Option<PathBuf>>,
    cleanup_failures: Rc<RefCell<Vec<String>>>,
}

impl PlatformTransaction {
    pub(crate) fn lock(path: &Path, scope_root: &Path) -> Result<PlatformLock, String> {
        let mutex = open_transaction_mutex(path, scope_root)?;
        let wait = unsafe { WaitForSingleObject(mutex.0, INFINITE) };
        if wait != WAIT_OBJECT_0 && wait != WAIT_ABANDONED {
            return Err(format!(
                "wait for setup transaction mutex returned {}",
                wait.0
            ));
        }
        Ok(PlatformLock { mutex, owned: true })
    }

    pub(crate) fn begin(
        path: &Path,
        scope_root: &Path,
        lock: PlatformLock,
    ) -> Result<Self, String> {
        let parent = validated_parent(path, scope_root, true)?
            .ok_or_else(|| format!("cannot create parent for {}", path.display()))?;
        let destination = parent.path.join(
            path.file_name()
                .ok_or_else(|| format!("no file name for {}", path.display()))?,
        );
        Ok(Self {
            parent,
            destination,
            display_path: path.to_path_buf(),
            _lock: lock,
            published_generation: std::cell::RefCell::new(None),
            published_recovery: RefCell::new(None),
            cleanup_failures: Rc::new(RefCell::new(Vec::new())),
        })
    }

    #[cfg(test)]
    fn lock_is_contended(path: &Path, scope_root: &Path) -> Result<bool, String> {
        let mutex = open_transaction_mutex(path, scope_root)?;
        let wait = unsafe { WaitForSingleObject(mutex.0, 0) };
        if wait == windows::Win32::Foundation::WAIT_TIMEOUT {
            Ok(true)
        } else if wait == WAIT_OBJECT_0 || wait == WAIT_ABANDONED {
            unsafe { ReleaseMutex(mutex.0) }
                .map_err(|error| format!("release probed setup mutex: {error}"))?;
            Ok(false)
        } else {
            Err(format!("probe setup transaction mutex returned {}", wait.0))
        }
    }

    pub(crate) fn read_snapshot(&self) -> Result<PlatformSnapshot, String> {
        snapshot_destination(&self.destination, &self.display_path)
    }

    pub(crate) fn take_cleanup_failures(&self) -> Vec<String> {
        std::mem::take(&mut *self.cleanup_failures.borrow_mut())
    }

    pub(crate) fn validate_snapshot(&self, expected: &PlatformSnapshot) -> Result<(), String> {
        let parent_final = final_path(
            self.parent
                .handles
                .last()
                .expect("validated parent has a handle")
                .0,
        )?;
        if !path_rules::final_path_within(&self.parent.root_final, &parent_final) {
            return Err("destination parent moved outside trusted setup root".into());
        }
        let live = self.read_snapshot()?;
        if &live != expected {
            return Err(format!(
                "{} changed while setup was preparing the update; no changes were published",
                self.display_path.display()
            ));
        }
        Ok(())
    }

    pub(crate) fn prepare_temp<'a>(
        &'a self,
        bytes: &[u8],
        _mode: u32,
        _preserve_existing_mode: bool,
        _snapshot: &PlatformSnapshot,
        _keep_backup: Option<&BackupGuard>,
    ) -> Result<TempGuard<'a>, String> {
        let path = self.parent.path.join(format!(
            ".tirith-setup-{}.tmp",
            uuid::Uuid::new_v4().simple()
        ));
        let path_wide = wide(&path);
        let owner_only = owner_only_descriptor()?;
        let security_attributes = SECURITY_ATTRIBUTES {
            nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: owner_only.0 .0,
            bInheritHandle: BOOL(0),
        };
        let handle = unsafe {
            CreateFileW(
                PCWSTR(path_wide.as_ptr()),
                (FILE_GENERIC_READ
                    | FILE_GENERIC_WRITE
                    | READ_CONTROL
                    | FILE_READ_ATTRIBUTES
                    | DELETE)
                    .0,
                FILE_SHARE_READ,
                Some(&security_attributes),
                CREATE_NEW,
                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT,
                None,
            )
        }
        .map_err(|error| format!("create exclusive owner-only temporary file: {error}"))?;
        let mut file = OwnedHandle(handle).into_file();
        if let Err(error) = file.write_all(bytes) {
            let cleanup = mark_held_file_for_deletion(&file)
                .err()
                .map(|cleanup| format!("; cleanup also failed: {cleanup}"))
                .unwrap_or_default();
            return Err(format!("write temporary file: {error}{cleanup}"));
        }
        if let Err(error) = unsafe { FlushFileBuffers(HANDLE(file.as_raw_handle())) } {
            let cleanup = mark_held_file_for_deletion(&file)
                .err()
                .map(|cleanup| format!("; cleanup also failed: {cleanup}"))
                .unwrap_or_default();
            return Err(format!(
                "flush temporary file before publication: {error}{cleanup}"
            ));
        }
        let cleanup = CleanupCapability::from_created(file, &path, bytes)?;
        let generation = cleanup.generation.clone();
        Ok(TempGuard {
            _transaction: self,
            path,
            cleanup: Some(cleanup),
            generation,
            armed: true,
            cleanup_failures: Rc::clone(&self.cleanup_failures),
        })
    }

    pub(crate) fn publish(
        &self,
        mut temp: TempGuard<'_>,
        expected: &PlatformSnapshot,
        #[cfg(test)] test_hook: &mut impl FnMut(super::fs_transaction::TestStage) -> Result<(), String>,
    ) -> Result<PublicationGuard, String> {
        let expected_exists = expected.bytes.is_some();
        // ReplaceFileW documents two failure modes in which it may already
        // have moved one or both names. Keep a private, flushed copy of the
        // locked snapshot until the API has returned so those failures cannot
        // erase both the original and the transaction artifacts.
        let mut recovery = if expected_exists {
            Some(self.create_backup_impl(expected, false)?)
        } else {
            None
        };

        // Creating the recovery copy can take time, so repeat the complete
        // no-follow generation/content/DACL check before publication while the
        // prepared identity remains protected by its no-share-delete handle.
        temp.validate_name()?;
        self.validate_snapshot(expected)?;
        temp.release_for_publication()?;
        #[cfg(test)]
        test_hook(super::fs_transaction::TestStage::PublicationReady)?;

        let temp_wide = wide(&temp.path);
        let destination_wide = wide(&self.destination);
        match path_rules::publication_kind(expected_exists) {
            path_rules::PublicationKind::ReplacePreservingMetadata => {
                let SnapshotGeneration::Present(expected_generation) = &expected.generation else {
                    unreachable!("existing snapshot has a generation")
                };
                let displaced_path = new_displaced_path(&self.destination, expected_generation)?;
                if let Err(error) =
                    replace_file_call(&self.destination, &temp.path, &displaced_path)
                {
                    let names_may_have_changed =
                        is_win32(&error, ERROR_UNABLE_TO_MOVE_REPLACEMENT.0)
                            || is_win32(&error, ERROR_UNABLE_TO_MOVE_REPLACEMENT_2.0);
                    if names_may_have_changed {
                        let destination_generation = generation_at(&self.destination);
                        let replacement_generation = generation_at(&temp.path);
                        let displaced_generation = generation_at(&displaced_path);

                        // With an API backup name, ERROR_UNABLE_TO_MOVE_REPLACEMENT
                        // documents that both original names remain. Prove that
                        // exact identity state before treating it as a clean
                        // failure; otherwise retain every artifact.
                        if is_win32(&error, ERROR_UNABLE_TO_MOVE_REPLACEMENT.0)
                            && destination_generation.as_ref().is_ok_and(|generation| {
                                generation.as_ref() == Some(expected_generation)
                            })
                            && replacement_generation.as_ref().is_ok_and(|generation| {
                                generation.as_ref() == Some(&temp.generation)
                            })
                            && displaced_generation.as_ref().is_ok_and(Option::is_none)
                        {
                            return Err(format!(
                                "replace {} failed before moving either identity: {error}",
                                self.destination.display()
                            ));
                        }

                        let recovery_path = recovery
                            .as_mut()
                            .expect("existing replacement has a recovery snapshot")
                            .retain_for_recovery()
                            .map_err(|validation| {
                                format!(
                                    "replace {} entered a partial Windows failure state ({error}); recovery snapshot validation failed: {validation}",
                                    self.destination.display()
                                )
                            })?;
                        temp.armed = false;
                        return Err(format!(
                            "replace {} entered a partial Windows failure state ({error}); retained the locked original snapshot at {}, destination identity {:?}, replacement identity {:?} at {}, and displaced identity {:?} at {}",
                            self.destination.display(),
                            recovery_path.display(),
                            destination_generation,
                            replacement_generation,
                            temp.path.display(),
                            displaced_generation,
                            displaced_path.display()
                        ));
                    }
                    return Err(format!(
                        "replace {} while preserving its DACL: {error}",
                        self.destination.display()
                    ));
                }

                let mut installed = match generation_at(&self.destination) {
                    Ok(generation) => generation,
                    Err(observation_error) => {
                        let recovery_path = recovery
                            .as_mut()
                            .expect("existing replacement has a recovery snapshot")
                            .retain_for_recovery()
                            .map_err(|validation| {
                                format!("published identity inspection failed and recovery snapshot validation failed: {validation}")
                            })?;
                        temp.armed = false;
                        return Err(format!(
                            "published {} but could not inspect the installed identity ({observation_error}); retained recovery snapshot {}, replacement {}, and displaced path {}",
                            self.destination.display(),
                            recovery_path.display(),
                            temp.path.display(),
                            displaced_path.display()
                        ));
                    }
                };
                // `ReplaceFileW` rewrote the installed file's security metadata
                // (merged DACL, creator owner). Put the preserved descriptor
                // back — but only on the exact identity that was just
                // installed, so a swapped-in competitor never gets its
                // descriptor rewritten. The byte-for-byte comparison below then
                // verifies against the refreshed post-restore observation.
                let mut restore_failure: Option<String> = None;
                if let Some(generation) = installed.as_ref() {
                    if generation.same_identity(&temp.generation)
                        && generation.security_descriptor != expected_generation.security_descriptor
                    {
                        match restore_preserved_security(
                            &self.destination,
                            generation,
                            &expected_generation.security_descriptor,
                        ) {
                            Ok(refreshed) => installed = Some(refreshed),
                            Err(error) => restore_failure = Some(error),
                        }
                    }
                }
                let displaced = match generation_at(&displaced_path) {
                    Ok(generation) => generation,
                    Err(observation_error) => {
                        let recovery_path = recovery
                            .as_mut()
                            .expect("existing replacement has a recovery snapshot")
                            .retain_for_recovery()
                            .map_err(|validation| {
                                format!("displaced identity inspection failed and recovery snapshot validation failed: {validation}")
                            })?;
                        temp.armed = false;
                        return Err(format!(
                            "published {} but could not inspect its displaced identity ({observation_error}); retained recovery snapshot {}, replacement {}, and displaced path {}",
                            self.destination.display(),
                            recovery_path.display(),
                            temp.path.display(),
                            displaced_path.display()
                        ));
                    }
                };
                // Name each component that disagreed. The publication contract
                // spans identity, bytes, attributes, and the preserved security
                // descriptor, and an opaque "changed at publication" gives a
                // caller nothing to act on.
                let mut mismatches = Vec::new();
                match installed.as_ref() {
                    None => mismatches.push("destination absent after replace".to_string()),
                    Some(generation) => {
                        if !generation.same_identity(&temp.generation) {
                            mismatches
                                .push("installed identity is not the replacement".to_string());
                        }
                        if generation.size != temp.generation.size {
                            mismatches.push(format!(
                                "installed size {} != replacement size {}",
                                generation.size, temp.generation.size
                            ));
                        }
                        if generation.digest != temp.generation.digest {
                            mismatches.push("installed digest is not the replacement".to_string());
                        }
                        if generation.reparse_tag != temp.generation.reparse_tag {
                            mismatches.push("installed reparse tag changed".to_string());
                        }
                        if !path_rules::attributes_are_safe(generation.attributes, false) {
                            mismatches.push(format!(
                                "installed attributes {:#x} are unsafe",
                                generation.attributes
                            ));
                        }
                        if generation.security_descriptor != expected_generation.security_descriptor
                        {
                            mismatches.push(format!(
                                "installed security descriptor {} is not the preserved one {}",
                                describe_security_descriptor(&generation.security_descriptor),
                                describe_security_descriptor(
                                    &expected_generation.security_descriptor
                                )
                            ));
                        }
                    }
                }
                match displaced.as_ref() {
                    None => mismatches.push("no displaced backup was produced".to_string()),
                    Some(generation) if generation != expected_generation => {
                        mismatches.push(format!(
                            "displaced identity differs (same_identity={}, sd {} vs {})",
                            generation.same_identity(expected_generation),
                            describe_security_descriptor(&generation.security_descriptor),
                            describe_security_descriptor(&expected_generation.security_descriptor)
                        ));
                    }
                    Some(_) => {}
                }
                if let Some(error) = restore_failure {
                    mismatches.push(format!(
                        "preserved security descriptor could not be restored ({error})"
                    ));
                }
                if !mismatches.is_empty() {
                    // ReplaceFileW's backup captured the exact competing file.
                    // Atomically restore it and keep our attempted replacement
                    // at the original private temp name.
                    let stable = generation_at(&self.destination)
                        .is_ok_and(|live| live == installed)
                        && generation_at(&displaced_path).is_ok_and(|live| live == displaced)
                        && generation_at(&temp.path).is_ok_and(|live| live.is_none());
                    if stable
                        && replace_file_call(&self.destination, &displaced_path, &temp.path).is_ok()
                        && generation_at(&self.destination)
                            .is_ok_and(|live| rollback_landed(live.as_ref(), displaced.as_ref()))
                        && generation_at(&temp.path).is_ok_and(|live| live == installed)
                    {
                        // The rollback replace rewrote the restored competitor's
                        // descriptor exactly the way publication rewrote ours.
                        // Its identity and bytes are proven back above; put the
                        // descriptor that was observed on it back too, so the
                        // competitor is restored in full. Best-effort by
                        // design — the identity proof is what the error claims.
                        if let (Ok(Some(live)), Some(displaced_generation)) =
                            (generation_at(&self.destination), displaced.as_ref())
                        {
                            if live.security_descriptor != displaced_generation.security_descriptor
                            {
                                let _ = restore_preserved_security(
                                    &self.destination,
                                    &live,
                                    &displaced_generation.security_descriptor,
                                );
                            }
                        }
                        // When the file back at the private temp name is OUR
                        // OWN prepared replacement, byte for byte, its metadata
                        // (the restored descriptor) no longer matches the
                        // generation the cleanup guard captured at preparation,
                        // so the scheduled scrub could not reacquire it and the
                        // artifact would strand. Point the guard at the exact
                        // identity verified above. Anything else at that name,
                        // a swapped-in foreign file OR our identity carrying
                        // tampered bytes, keeps the original expectation and is
                        // deliberately retained as evidence.
                        if let Some(generation) = installed.as_ref() {
                            if generation.same_identity(&temp.generation)
                                && generation.digest == temp.generation.digest
                                && generation.size == temp.generation.size
                            {
                                temp.generation = generation.clone();
                            }
                        }
                        return Err(format!(
                            "{} or its prepared replacement changed at publication ({}); restored the competing destination and published nothing",
                            self.destination.display(),
                            mismatches.join("; ")
                        ));
                    }

                    let recovery_path = recovery
                        .as_mut()
                        .expect("existing replacement has a recovery snapshot")
                        .retain_for_recovery()
                        .map_err(|validation| {
                            format!("rollback was uncertain and recovery snapshot validation failed: {validation}")
                        })?;
                    temp.armed = false;
                    return Err(format!(
                        "{} or its prepared replacement changed at publication ({}) and rollback could not be proven; retained recovery snapshot {}, replacement {}, and displaced identity {}",
                        self.destination.display(),
                        mismatches.join("; "),
                        recovery_path.display(),
                        temp.path.display(),
                        displaced_path.display()
                    ));
                }

                let installed = installed.expect("successful replacement has installed state");
                self.published_generation.replace(Some(installed.clone()));
                let held_installed = match HeldIdentity::open_exact(
                    self.destination.clone(),
                    &installed,
                ) {
                    Ok(installed) => installed,
                    Err(hold_error) => {
                        let recovery_path = recovery
                            .as_mut()
                            .expect("existing replacement has a recovery snapshot")
                            .retain_for_recovery()
                            .map_err(|validation| {
                                format!("installed identity hold failed and recovery snapshot validation failed: {validation}")
                            })?;
                        temp.armed = false;
                        return Err(format!(
                            "published {} but could not hold its exact installed identity ({hold_error}); retained recovery snapshot {} and displaced path {}",
                            self.destination.display(),
                            recovery_path.display(),
                            displaced_path.display()
                        ));
                    }
                };
                let displaced = match HeldIdentity::open_exact(
                    displaced_path.clone(),
                    expected_generation,
                ) {
                    Ok(displaced) => displaced,
                    Err(hold_error) => {
                        let recovery_path = recovery
                            .as_mut()
                            .expect("existing replacement has a recovery snapshot")
                            .retain_for_recovery()
                            .map_err(|validation| {
                                format!("displaced identity hold failed and recovery snapshot validation failed: {validation}")
                            })?;
                        temp.armed = false;
                        return Err(format!(
                            "published {} but could not hold its exact displaced identity ({hold_error}); retained recovery snapshot {} and displaced path {}",
                            self.destination.display(),
                            recovery_path.display(),
                            displaced_path.display()
                        ));
                    }
                };
                self.published_recovery
                    .replace(Some(displaced_path.clone()));
                temp.armed = false;
                return Ok(PublicationGuard::replacement(
                    held_installed,
                    displaced,
                    recovery,
                ));
            }
            path_rules::PublicationKind::MoveWithoutReplacement => {
                // Omitting REPLACE_EXISTING gives expected-absent publication
                // an atomic never-overwrite guarantee.
                unsafe {
                    MoveFileExW(
                        PCWSTR(temp_wide.as_ptr()),
                        PCWSTR(destination_wide.as_ptr()),
                        MOVEFILE_WRITE_THROUGH,
                    )
                }
                .map_err(|error| {
                    format!(
                        "publish new destination {} without replacement: {error}",
                        self.destination.display()
                    )
                })?;
                let installed = match generation_at(&self.destination) {
                    Ok(Some(generation)) => generation,
                    Ok(None) => {
                        temp.armed = false;
                        return Err(format!(
                            "published destination {} disappeared; the prepared pathname was retained for recovery",
                            self.destination.display()
                        ));
                    }
                    Err(observation_error) => {
                        temp.armed = false;
                        return Err(format!(
                            "published destination {} but could not verify it ({observation_error}); retained the published pathname for recovery",
                            self.destination.display()
                        ));
                    }
                };
                if installed != temp.generation {
                    temp.armed = false;
                    return Err(format!(
                        "published destination {} no longer identifies the exact prepared replacement; retained its pathname for recovery",
                        self.destination.display()
                    ));
                }
                self.published_generation.replace(Some(installed.clone()));
                let held_installed = match HeldIdentity::open_exact(
                    self.destination.clone(),
                    &installed,
                ) {
                    Ok(installed) => installed,
                    Err(hold_error) => {
                        temp.armed = false;
                        return Err(format!(
                                "published destination {} but could not hold its exact installed identity ({hold_error}); retained the published pathname for recovery",
                                self.destination.display()
                            ));
                    }
                };
                temp.armed = false;
                return Ok(PublicationGuard::clean(held_installed));
            }
        }
    }

    pub(crate) fn sync_parent(&self) -> Result<(), String> {
        // Windows exposes no directory fsync and ReplaceFileW explicitly does
        // not support REPLACEFILE_WRITE_THROUGH. This is therefore an honest
        // exact-file FlushFileBuffers gate, not a claim that the namespace
        // transition itself is durable. Existing-file replacement keeps its
        // displaced original until the caller receives a degraded outcome.
        let destination_wide = wide(&self.destination);
        let handle = unsafe {
            CreateFileW(
                PCWSTR(destination_wide.as_ptr()),
                (FILE_GENERIC_READ | FILE_GENERIC_WRITE | READ_CONTROL | FILE_READ_ATTRIBUTES).0,
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                None,
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT,
                None,
            )
        }
        .map_err(|error| {
            format!(
                "open published destination {} for durability: {error}",
                self.destination.display()
            )
        })?;
        let expected = self.published_generation.borrow().clone().ok_or_else(|| {
            "no published identity available for durability validation".to_string()
        })?;
        let mut file = OwnedHandle(handle).into_file();
        let (_, _, before) = capture_stable_file(
            file.try_clone()
                .map_err(|error| format!("clone published file handle: {error}"))?,
            &self.destination,
        )?;
        if before != expected {
            return Err(format!(
                "published destination {} changed before durability flush",
                self.destination.display()
            ));
        }
        unsafe { FlushFileBuffers(HANDLE(file.as_raw_handle())) }.map_err(|error| {
            format!(
                "flush published destination {} after replacement: {error}",
                self.destination.display()
            )
        })?;
        file.seek(SeekFrom::Start(0))
            .map_err(|error| format!("rewind published destination: {error}"))?;
        let (_, _, after) = capture_stable_file(file, &self.destination)?;
        if after != expected {
            return Err(format!(
                "published destination {} changed during durability flush",
                self.destination.display()
            ));
        }
        Ok(())
    }

    pub(crate) fn create_backup(&self, snapshot: &PlatformSnapshot) -> Result<BackupGuard, String> {
        self.create_backup_impl(snapshot, true)
    }

    fn create_backup_impl(
        &self,
        snapshot: &PlatformSnapshot,
        announce: bool,
    ) -> Result<BackupGuard, String> {
        let bytes = snapshot
            .bytes
            .as_deref()
            .ok_or_else(|| "cannot back up an absent destination".to_string())?;
        let name = backup_name(&self.destination, bytes);
        let path = self.parent.path.join(name);
        let path_wide = wide(&path);
        let owner_only = owner_only_descriptor()?;
        let security_attributes = SECURITY_ATTRIBUTES {
            nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: owner_only.0 .0,
            bInheritHandle: BOOL(0),
        };
        let handle = unsafe {
            CreateFileW(
                PCWSTR(path_wide.as_ptr()),
                (FILE_GENERIC_READ
                    | FILE_GENERIC_WRITE
                    | READ_CONTROL
                    | FILE_READ_ATTRIBUTES
                    | DELETE)
                    .0,
                FILE_SHARE_READ,
                Some(&security_attributes),
                CREATE_NEW,
                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT,
                None,
            )
        }
        .map_err(|error| format!("create exclusive owner-only backup: {error}"))?;
        let mut file = OwnedHandle(handle).into_file();
        if let Err(error) = file.write_all(bytes) {
            let cleanup = mark_held_file_for_deletion(&file)
                .err()
                .map(|cleanup| format!("; cleanup also failed: {cleanup}"))
                .unwrap_or_default();
            return Err(format!(
                "write backup from locked snapshot: {error}{cleanup}"
            ));
        }
        if let Err(error) = unsafe { FlushFileBuffers(HANDLE(file.as_raw_handle())) } {
            let cleanup = mark_held_file_for_deletion(&file)
                .err()
                .map(|cleanup| format!("; cleanup also failed: {cleanup}"))
                .unwrap_or_default();
            return Err(format!("flush backup before update: {error}{cleanup}"));
        }
        let cleanup = CleanupCapability::from_created(file, &path, bytes)?;
        if !backup_name_matches(&path, &self.destination, &cleanup.generation) {
            let cleanup_error = cleanup
                .delete()
                .err()
                .map(|error| format!("; cleanup also failed: {error}"))
                .unwrap_or_default();
            return Err(format!(
                "new backup did not satisfy its provenance or owner-only security binding{cleanup_error}"
            ));
        }
        Ok(BackupGuard {
            path,
            destination: self.destination.clone(),
            cleanup: Some(cleanup),
            armed: true,
            announce_on_commit: announce,
            cleanup_failures: Rc::clone(&self.cleanup_failures),
        })
    }

    pub(crate) fn cleanup_old_backups(&self, keep: Option<&BackupGuard>) -> Result<(), String> {
        let entries = fs::read_dir(&self.parent.path)
            .map_err(|error| format!("enumerate transaction artifact directory: {error}"))?
            .map(|entry| entry.map(|entry| entry.path()))
            .collect::<Result<Vec<_>, _>>()
            .map_err(|error| format!("enumerate transaction artifact entry: {error}"))?;
        let mut failures = Vec::new();

        let keep_backup = keep.map(|guard| guard.path.clone());
        let mut backups = Vec::new();
        for path in entries.iter().filter(|path| {
            path.file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .starts_with(BACKUP_MARKER)
                && keep_backup.as_ref() != Some(*path)
        }) {
            // A filename prefix is never deletion authority. The same
            // no-share-write DELETE handle must validate the complete content
            // binding, safe attributes, and protected owner-only DACL.
            let Ok(cleanup) = CleanupCapability::open(path) else {
                continue;
            };
            if backup_name_matches(path, &self.destination, &cleanup.generation) {
                backups.push((path.clone(), cleanup));
            }
        }
        backups.sort_by(|left, right| left.0.cmp(&right.0));
        let remove_backups = (backups.len() + usize::from(keep_backup.is_some()))
            .saturating_sub(ARTIFACT_RETENTION_LIMIT);
        for (old, cleanup) in backups.into_iter().take(remove_backups) {
            #[cfg(test)]
            OLD_BACKUP_CLEANUP_TEST_HOOK.with(|slot| {
                if let Some(hook) = slot.borrow_mut().as_mut() {
                    hook(&old);
                }
            });
            if let Err(error) = cleanup.delete() {
                failures.push(format!(
                    "delete provenance-bound old backup {}: {error}",
                    old.display()
                ));
            }
        }

        let keep_recovery = self.published_recovery.borrow().clone();
        let mut recoveries = Vec::new();
        for path in entries.iter().filter(|path| {
            path.file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .starts_with(DISPLACED_MARKER)
                && keep_recovery.as_ref() != Some(*path)
        }) {
            let Ok(cleanup) = CleanupCapability::open(path) else {
                continue;
            };
            if displaced_name_matches(path, &self.destination, &cleanup.generation) {
                recoveries.push((path.clone(), cleanup));
            }
        }
        recoveries.sort_by(|left, right| left.0.cmp(&right.0));
        let remove_recoveries = (recoveries.len() + usize::from(keep_recovery.is_some()))
            .saturating_sub(ARTIFACT_RETENTION_LIMIT);
        for (old, cleanup) in recoveries.into_iter().take(remove_recoveries) {
            if let Err(error) = cleanup.delete() {
                failures.push(format!(
                    "delete provenance-bound displaced recovery {}: {error}",
                    old.display()
                ));
            }
        }

        if failures.is_empty() {
            Ok(())
        } else {
            Err(failures.join("; "))
        }
    }
}

pub(crate) struct TempGuard<'a> {
    _transaction: &'a PlatformTransaction,
    path: PathBuf,
    cleanup: Option<CleanupCapability>,
    generation: FileGeneration,
    armed: bool,
    cleanup_failures: Rc<RefCell<Vec<String>>>,
}

impl TempGuard<'_> {
    fn validate_name(&mut self) -> Result<(), String> {
        let capability = self
            .cleanup
            .as_mut()
            .ok_or_else(|| "prepared temporary cleanup capability is unavailable".to_string())?;
        capability.validate(&self.path)?;
        if capability.generation != self.generation {
            return Err(
                "temporary setup file changed before publication; refusing for safety".into(),
            );
        }
        Ok(())
    }

    fn release_for_publication(&mut self) -> Result<(), String> {
        self.validate_name()?;
        self.cleanup.take();
        if generation_at(&self.path)?.as_ref() != Some(&self.generation) {
            return Err("temporary setup file changed while releasing it for publication".into());
        }
        Ok(())
    }
}

impl Drop for TempGuard<'_> {
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        let cleanup = match self.cleanup.take() {
            Some(cleanup) => Some(cleanup),
            None => match CleanupCapability::open_exact(&self.path, &self.generation) {
                Ok(Some(cleanup)) => Some(cleanup),
                Ok(None) => {
                    self.cleanup_failures.borrow_mut().push(format!(
                        "could not reacquire exact temporary identity {} for cleanup",
                        self.path.display()
                    ));
                    None
                }
                Err(error) => {
                    self.cleanup_failures.borrow_mut().push(format!(
                        "could not validate temporary identity {} for cleanup: {error}",
                        self.path.display()
                    ));
                    None
                }
            },
        };
        if let Some(cleanup) = cleanup {
            if let Err(error) = cleanup.delete() {
                self.cleanup_failures.borrow_mut().push(format!(
                    "could not scrub exact temporary identity {}: {error}",
                    self.path.display()
                ));
            }
        }
    }
}

pub(crate) struct BackupGuard {
    path: PathBuf,
    destination: PathBuf,
    cleanup: Option<CleanupCapability>,
    armed: bool,
    announce_on_commit: bool,
    cleanup_failures: Rc<RefCell<Vec<String>>>,
}

impl BackupGuard {
    fn validate(&mut self, purpose: &str) -> Result<(), String> {
        let cleanup = self
            .cleanup
            .as_mut()
            .ok_or_else(|| "backup cleanup capability is unavailable before commit".to_string())?;
        cleanup.validate(&self.path).map_err(|error| {
            format!(
                "backup {} changed before {purpose}: {error}",
                self.path.display(),
            )
        })?;
        if !backup_name_matches(&self.path, &self.destination, &cleanup.generation) {
            return Err(format!(
                "backup {} lost its provenance/security binding before {purpose}",
                self.path.display(),
            ));
        }
        Ok(())
    }

    pub(crate) fn commit(&mut self) -> Result<(), String> {
        self.validate("commit/announcement")?;
        self.armed = false;
        if self.announce_on_commit {
            eprintln!("tirith: backup at {}", self.path.display());
        }
        Ok(())
    }

    pub(crate) fn retain_for_recovery(&mut self) -> Result<PathBuf, String> {
        self.validate("recovery announcement")?;
        self.armed = false;
        Ok(self.path.clone())
    }
}

impl Drop for BackupGuard {
    fn drop(&mut self) {
        if self.armed {
            if let Some(cleanup) = self.cleanup.take() {
                if let Err(error) = cleanup.delete() {
                    self.cleanup_failures.borrow_mut().push(format!(
                        "could not scrub exact backup identity {}: {error}",
                        self.path.display()
                    ));
                }
            }
        }
    }
}

pub(crate) struct PublicationGuard {
    installed: HeldIdentity,
    displaced: Option<HeldIdentity>,
    recovery: Option<BackupGuard>,
}

impl PublicationGuard {
    fn clean(installed: HeldIdentity) -> Self {
        Self {
            installed,
            displaced: None,
            recovery: None,
        }
    }

    fn replacement(
        installed: HeldIdentity,
        displaced: HeldIdentity,
        recovery: Option<BackupGuard>,
    ) -> Self {
        Self {
            installed,
            displaced: Some(displaced),
            recovery,
        }
    }

    pub(crate) fn retain_for_recovery(&mut self) -> String {
        let installed = self
            .installed
            .validate()
            .map(|()| {
                format!(
                    "exact installed identity at {}",
                    self.installed.path.display()
                )
            })
            .unwrap_or_else(|error| format!("installed identity validation failed: {error}"));
        let displaced = self.displaced.as_ref().map(|identity| {
            identity
                .validate()
                .map(|()| format!("exact displaced original at {}", identity.path.display()))
                .unwrap_or_else(|error| format!("displaced original validation failed: {error}"))
        });
        let snapshot = self.recovery.as_mut().map(|backup| {
            backup
                .retain_for_recovery()
                .map(|path| format!("locked recovery snapshot at {}", path.display()))
                .unwrap_or_else(|error| format!("recovery snapshot validation failed: {error}"))
        });
        match (displaced, snapshot) {
            (Some(displaced), Some(snapshot)) => {
                format!("retained {installed}, {displaced}, and {snapshot}")
            }
            (Some(displaced), None) => format!("retained {installed} and {displaced}"),
            (None, Some(snapshot)) => format!("retained {installed} and {snapshot}"),
            (None, None) => format!("retained {installed}; no displaced original existed"),
        }
    }

    pub(crate) fn finish_after_durability(mut self) -> Result<PublicationOutcome, String> {
        if let Err(error) = self.installed.validate() {
            let displaced = self
                .displaced
                .as_ref()
                .map(|identity| {
                    format!(
                        "; retained displaced original at {}",
                        identity.path.display()
                    )
                })
                .unwrap_or_default();
            let recovery = self
                .recovery
                .as_mut()
                .map(BackupGuard::retain_for_recovery)
                .map(|result| match result {
                    Ok(path) => {
                        format!("; retained exact recovery snapshot at {}", path.display())
                    }
                    Err(error) => format!("; recovery snapshot validation failed: {error}"),
                })
                .unwrap_or_default();
            return Err(format!(
                "installed destination identity changed before transaction completion ({error}){displaced}{recovery}"
            ));
        }
        let Some(displaced) = self.displaced.as_ref() else {
            return Ok(PublicationOutcome::Clean);
        };
        if let Err(error) = displaced.validate() {
            let recovery = self
                .recovery
                .as_mut()
                .map(BackupGuard::retain_for_recovery)
                .map(|result| match result {
                    Ok(path) => {
                        format!("; retained exact recovery snapshot at {}", path.display())
                    }
                    Err(error) => format!("; recovery snapshot validation failed: {error}"),
                })
                .unwrap_or_default();
            return Ok(PublicationOutcome::RecoveryRetained(format!(
                "Windows replacement file flush completed, but the displaced identity could not be revalidated ({error}){recovery}"
            )));
        }
        let path = displaced.path.clone();
        // Dropping the private snapshot deletes only its still-held exact
        // identity. The API-provided displaced original remains as recovery.
        self.recovery.take();
        Ok(PublicationOutcome::RecoveryRetained(format!(
            "Windows flushed the installed file but cannot prove ReplaceFileW's directory/name transition durable; retained the exact displaced original at {}",
            path.display()
        )))
    }
}

/// Write a hook script. No executable bit needed on Windows.
pub fn write_hook_script(
    path: &Path,
    scope_root: &Path,
    content: &str,
    force: bool,
    dry_run: bool,
) -> Result<(), String> {
    let outcome = transactional_update(path, scope_root, dry_run, |snapshot| {
        if let Some(existing) = snapshot.text(path)? {
            if existing == content {
                if dry_run {
                    eprintln!(
                        "[dry-run] would skip {} (already up to date)",
                        path.display()
                    );
                } else {
                    eprintln!("tirith: {} already configured, up to date", path.display());
                }
                return Ok(FileUpdate::unchanged());
            }
            if !force {
                if dry_run {
                    eprintln!(
                        "[dry-run] would error: {} exists but content differs — use --force to update",
                        path.display()
                    );
                    return Ok(FileUpdate::unchanged());
                }
                return Err(format!(
                    "{} exists but content differs — use --force to update",
                    path.display()
                ));
            }
        }
        if dry_run {
            eprintln!(
                "[dry-run] would write {} ({} bytes)",
                path.display(),
                content.len()
            );
        }
        Ok(FileUpdate::write_text(content.to_string(), 0o644))
    })?;
    if let Some(annotation) = outcome.completion_annotation() {
        eprintln!("tirith: wrote {}{annotation}", path.display());
    }
    Ok(())
}

/// Validate that `dir` stays within `scope_root` after canonicalization.
pub fn validate_target_dir(dir: &Path, scope_root: Option<&Path>) -> Result<(), String> {
    let root = match scope_root {
        Some(r) => r,
        None => return Ok(()),
    };

    let root_canonical = root
        .canonicalize()
        .map_err(|e| format!("canonicalize {}: {e}", root.display()))?;

    let mut check = dir.to_path_buf();
    loop {
        if check.exists() {
            let canonical = check
                .canonicalize()
                .map_err(|e| format!("canonicalize {}: {e}", check.display()))?;
            if !canonical.starts_with(&root_canonical) {
                return Err(format!(
                    "{} resolves outside project root {} — refusing for safety",
                    dir.display(),
                    root.display()
                ));
            }
            break;
        }
        if !check.pop() {
            return Err(format!(
                "cannot resolve {} — no existing ancestor found",
                dir.display()
            ));
        }
    }

    let mut path_so_far = PathBuf::new();
    for component in dir.components() {
        path_so_far.push(component);
        if path_so_far.exists() {
            if let Ok(meta) = fs::symlink_metadata(&path_so_far) {
                if meta.file_type().is_symlink() && path_so_far.starts_with(&root_canonical) {
                    return Err(format!(
                        "{} is a symlink inside project scope — refusing for safety",
                        path_so_far.display()
                    ));
                }
            }
        }
    }

    Ok(())
}

/// Retire an obsolete content-addressed Codex gateway generation after its
/// registration has been replaced successfully. Windows deletion is bound to
/// the exact validated file handle while retained no-reparse parent handles
/// keep the destination inside the trusted setup root.
pub fn retire_codex_gateway_generation(path: &Path, scope_root: &Path) -> Result<(), String> {
    let lock = PlatformTransaction::lock(path, scope_root)?;
    let transaction = PlatformTransaction::begin(path, scope_root, lock)?;
    let snapshot = transaction.read_snapshot()?;
    let Some(bytes) = snapshot.bytes.as_deref() else {
        return Ok(());
    };
    let digest = Sha256::digest(bytes);
    let expected_name = format!("gateway-sha256-{}.yaml", hex_bytes(&digest));
    if path.file_name() != Some(OsStr::new(&expected_name)) {
        return Err(format!(
            "{} is not named for its exact gateway content; refusing retirement",
            path.display()
        ));
    }
    let SnapshotGeneration::Present(expected_generation) = &snapshot.generation else {
        return Err("gateway retirement snapshot has no stable file generation".into());
    };
    if expected_generation.reparse_tag.is_some()
        || !path_rules::attributes_are_safe(expected_generation.attributes, false)
        || !owner_only_security_descriptor(&expected_generation.security_descriptor)
    {
        return Err(format!(
            "{} is not an owner-only non-reparse file; refusing retirement",
            path.display()
        ));
    }
    transaction.validate_snapshot(&snapshot)?;
    let mut cleanup = CleanupCapability::open(&transaction.destination)?;
    if &cleanup.generation != expected_generation {
        return Err(format!("{} changed before retirement", path.display()));
    }
    cleanup.validate(&transaction.destination)?;
    cleanup.delete()?;
    if transaction.read_snapshot()?.bytes.is_some() {
        return Err(format!(
            "{} still exists after exact-handle retirement",
            path.display()
        ));
    }
    Ok(())
}

/// Run Codex with an explicitly selected project working directory. Codex's
/// global `-C` option preserves its project/user configuration semantics while the
/// supervised child itself keeps a loader-safe working directory on Windows.
pub fn run_codex_cli_in_dir(
    cwd: &Path,
    cmd: &str,
    args: &[&str],
) -> Result<std::process::Output, String> {
    let executable = tirith_core::trusted_child::resolve_ambient(cmd)
        .map_err(|error| format!("{cmd} not found or untrusted: {error}"))?;
    let scoped_args = codex_scoped_args(cwd, args);
    run_cli_bounded(
        &executable,
        &scoped_args,
        tirith_core::trusted_child::ChildLimits::new(
            std::time::Duration::from_secs(30),
            4 * 1024 * 1024,
            4 * 1024 * 1024,
        ),
    )
}

fn codex_scoped_args(cwd: &Path, args: &[&str]) -> Vec<OsString> {
    let mut scoped = Vec::with_capacity(args.len() + 2);
    scoped.push(OsString::from("-C"));
    scoped.push(cwd.as_os_str().to_os_string());
    scoped.extend(args.iter().map(|arg| OsString::from(*arg)));
    scoped
}

fn run_cli_bounded<S: AsRef<OsStr>>(
    executable: &tirith_core::trusted_child::TrustedExecutable,
    args: &[S],
    limits: tirith_core::trusted_child::ChildLimits,
) -> Result<std::process::Output, String> {
    use tirith_core::trusted_child::{ChildOutcome, ChildSpec};

    let mut spec = ChildSpec::new(args.iter().map(AsRef::as_ref), limits).inherit_env(&[
        "HOME",
        "USER",
        "LOGNAME",
        "USERPROFILE",
        "XDG_CONFIG_HOME",
        "XDG_DATA_HOME",
        "XDG_STATE_HOME",
        "APPDATA",
        "LOCALAPPDATA",
        "CODEX_HOME",
        "SystemRoot",
        "WINDIR",
    ]);
    if let Some(path) = tirith_core::trusted_child::sanitized_ambient_path() {
        spec = spec.env("PATH", path);
    }
    match tirith_core::trusted_child::run(executable, &spec) {
        ChildOutcome::Completed {
            status,
            stdout,
            stderr,
        } => Ok(std::process::Output {
            status,
            stdout,
            stderr,
        }),
        ChildOutcome::SpawnError(reason) => Err(format!("failed to start: {reason}")),
        ChildOutcome::WaitError(reason) => Err(format!("wait failed: {reason}")),
        ChildOutcome::CleanupError(reason) => Err(format!("process-tree cleanup failed: {reason}")),
        ChildOutcome::Timeout {
            cleanup_succeeded: true,
        } => Err("timed out after 30s — check installation".into()),
        ChildOutcome::Timeout {
            cleanup_succeeded: false,
        } => Err("timed out and process-tree cleanup failed — check installation".into()),
        ChildOutcome::OutputLimitExceeded {
            cleanup_succeeded: true,
            ..
        } => Err("output limit exceeded — check installation".into()),
        ChildOutcome::OutputLimitExceeded {
            cleanup_succeeded: false,
            ..
        } => Err("output limit exceeded and process-tree cleanup failed".into()),
    }
}

#[cfg(all(test, windows))]
mod tests {
    use super::super::fs_transaction::{
        transactional_update_with_hook, FileUpdate, TestStage, TransactionOutcome,
    };
    use super::*;

    fn symlink_directory_or_explicitly_skip(target: &Path, link: &Path) -> bool {
        match std::os::windows::fs::symlink_dir(target, link) {
            Ok(()) => true,
            Err(error) => {
                eprintln!(
                    "SKIP symlink reparse coverage: Windows denied symlink creation ({error})"
                );
                false
            }
        }
    }

    fn symlink_file_or_explicitly_skip(target: &Path, link: &Path) -> bool {
        match std::os::windows::fs::symlink_file(target, link) {
            Ok(()) => true,
            Err(error) => {
                eprintln!(
                    "SKIP backup reparse coverage: Windows denied symlink creation ({error})"
                );
                false
            }
        }
    }

    fn backup_paths(root: &Path) -> Vec<PathBuf> {
        let mut paths = fs::read_dir(root)
            .unwrap()
            .filter_map(Result::ok)
            .map(|entry| entry.path())
            .filter(|path| {
                path.file_name()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .contains("tirith-backup")
            })
            .collect::<Vec<_>>();
        paths.sort();
        paths
    }

    fn temporary_setup_paths(root: &Path) -> Vec<PathBuf> {
        fs::read_dir(root)
            .unwrap()
            .filter_map(Result::ok)
            .map(|entry| entry.path())
            .filter(|path| {
                let name = path.file_name().unwrap_or_default().to_string_lossy();
                name.starts_with(".tirith-setup-") && name.ends_with(".tmp")
            })
            .collect()
    }

    fn displaced_paths(root: &Path) -> Vec<PathBuf> {
        fs::read_dir(root)
            .unwrap()
            .filter_map(Result::ok)
            .map(|entry| entry.path())
            .filter(|path| {
                path.file_name()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .contains("tirith-displaced")
            })
            .collect()
    }

    struct ReplaceHookReset;

    impl Drop for ReplaceHookReset {
        fn drop(&mut self) {
            REPLACE_FILE_TEST_HOOK.with(|slot| *slot.borrow_mut() = None);
        }
    }

    struct CleanupHookReset;

    impl Drop for CleanupHookReset {
        fn drop(&mut self) {
            OLD_BACKUP_CLEANUP_TEST_HOOK.with(|slot| *slot.borrow_mut() = None);
        }
    }

    struct ArtifactCaptureHookReset;

    impl Drop for ArtifactCaptureHookReset {
        fn drop(&mut self) {
            CREATED_ARTIFACT_CAPTURE_TEST_HOOK.with(|slot| *slot.borrow_mut() = None);
        }
    }

    fn with_replace_hook<T>(
        hook: impl FnMut(&Path, &Path, &Path) -> Result<(), u32> + 'static,
        run: impl FnOnce() -> T,
    ) -> T {
        REPLACE_FILE_TEST_HOOK.with(|slot| {
            assert!(slot.borrow().is_none());
            *slot.borrow_mut() = Some(Box::new(hook));
        });
        let _reset = ReplaceHookReset;
        run()
    }

    fn with_cleanup_hook<T>(hook: impl FnMut(&Path) + 'static, run: impl FnOnce() -> T) -> T {
        OLD_BACKUP_CLEANUP_TEST_HOOK.with(|slot| {
            assert!(slot.borrow().is_none());
            *slot.borrow_mut() = Some(Box::new(hook));
        });
        let _reset = CleanupHookReset;
        run()
    }

    fn with_artifact_capture_hook<T>(
        hook: impl FnMut(&Path) + 'static,
        run: impl FnOnce() -> T,
    ) -> T {
        CREATED_ARTIFACT_CAPTURE_TEST_HOOK.with(|slot| {
            assert!(slot.borrow().is_none());
            *slot.borrow_mut() = Some(Box::new(hook));
        });
        let _reset = ArtifactCaptureHookReset;
        run()
    }

    fn update_with_backup(path: &Path, root: &Path, content: &str) -> Result<(), String> {
        transactional_update(path, root, false, |_| {
            Ok(FileUpdate::write_text(content.to_string(), 0o644).with_backup(true))
        })?;
        Ok(())
    }

    fn descriptor_control(descriptor: &mut [u8]) -> u16 {
        use windows::Win32::Security::GetSecurityDescriptorControl;

        let descriptor = PSECURITY_DESCRIPTOR(descriptor.as_mut_ptr().cast());
        let mut control = 0u16;
        let mut revision = 0u32;
        unsafe { GetSecurityDescriptorControl(descriptor, &mut control, &mut revision) }.unwrap();
        control
    }

    fn create_protected_owner_only_file(path: &Path, content: &[u8]) {
        let path_wide = wide(path);
        let owner_only = owner_only_descriptor().unwrap();
        let security_attributes = SECURITY_ATTRIBUTES {
            nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: owner_only.0 .0,
            bInheritHandle: BOOL(0),
        };
        let handle = unsafe {
            CreateFileW(
                PCWSTR(path_wide.as_ptr()),
                FILE_GENERIC_WRITE.0,
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                Some(&security_attributes),
                CREATE_NEW,
                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT,
                None,
            )
        }
        .unwrap();
        let mut file = OwnedHandle(handle).into_file();
        file.write_all(content).unwrap();
        unsafe { FlushFileBuffers(HANDLE(file.as_raw_handle())) }.unwrap();
    }

    fn overwrite_same_length_and_restore_last_write(path: &Path, content: &[u8]) {
        let mut file = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(path)
            .unwrap();
        let handle = HANDLE(file.as_raw_handle());
        let before = handle_information(handle, path).unwrap();
        let original_size = ((before.nFileSizeHigh as u64) << 32) | before.nFileSizeLow as u64;
        assert_eq!(content.len() as u64, original_size);
        file.seek(SeekFrom::Start(0)).unwrap();
        file.write_all(content).unwrap();
        file.flush().unwrap();
        unsafe {
            windows::Win32::Storage::FileSystem::SetFileTime(
                handle,
                None,
                None,
                Some(&before.ftLastWriteTime),
            )
        }
        .unwrap();
        unsafe { FlushFileBuffers(handle) }.unwrap();
    }

    #[test]
    fn up_to_date_hook_refuses_symlink_reparse_parent() {
        let root = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        fs::write(outside.path().join("hook.cmd"), "expected").unwrap();
        if !symlink_directory_or_explicitly_skip(outside.path(), &root.path().join("hooks")) {
            return;
        }
        let result = write_hook_script(
            &root.path().join("hooks/hook.cmd"),
            root.path(),
            "expected",
            false,
            true,
        );
        assert!(result.is_err());
        assert_eq!(
            fs::read_to_string(outside.path().join("hook.cmd")).unwrap(),
            "expected"
        );
    }

    /// Create an NTFS junction (mount point) natively. `cmd.exe /c mklink /J`
    /// rejects the runner's paths outright, so coverage builds the reparse
    /// point through the same kernel interface Windows itself uses:
    /// `FSCTL_SET_REPARSE_POINT` with a `MountPointReparseBuffer` payload.
    /// Junctions, unlike symlinks, require no privilege.
    fn create_junction(link: &Path, target: &Path) -> Result<(), String> {
        use windows::Win32::System::Ioctl::FSCTL_SET_REPARSE_POINT;
        use windows::Win32::System::IO::DeviceIoControl;

        std::fs::create_dir(link).map_err(|error| format!("create junction dir: {error}"))?;
        let link_wide = wide(link);
        let handle = unsafe {
            CreateFileW(
                PCWSTR(link_wide.as_ptr()),
                FILE_GENERIC_WRITE.0,
                FILE_SHARE_READ,
                None,
                OPEN_EXISTING,
                FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
                None,
            )
        }
        .map_err(|error| format!("open junction dir: {error}"))?;
        let dir = OwnedHandle(handle).into_file();

        let rendered = target.display().to_string();
        let plain = rendered
            .strip_prefix(r"\\?\")
            .unwrap_or(rendered.as_str())
            .to_string();
        let substitute: Vec<u16> = format!(r"\??\{plain}").encode_utf16().collect();
        let print: Vec<u16> = plain.encode_utf16().collect();

        // REPARSE_DATA_BUFFER: tag u32, data-length u16, reserved u16, then the
        // MountPointReparseBuffer (four u16 offsets/lengths + path buffer with
        // NUL-terminated substitute and print names).
        let sub_bytes = substitute.len() * 2;
        let print_bytes = print.len() * 2;
        let reparse_data_length = 8 + sub_bytes + 2 + print_bytes + 2;
        let mut buffer = vec![0u8; 8 + reparse_data_length];
        buffer[0..4].copy_from_slice(&0xA000_0003u32.to_le_bytes()); // IO_REPARSE_TAG_MOUNT_POINT
        buffer[4..6].copy_from_slice(&(reparse_data_length as u16).to_le_bytes());
        buffer[8..10].copy_from_slice(&0u16.to_le_bytes());
        buffer[10..12].copy_from_slice(&(sub_bytes as u16).to_le_bytes());
        buffer[12..14].copy_from_slice(&((sub_bytes + 2) as u16).to_le_bytes());
        buffer[14..16].copy_from_slice(&(print_bytes as u16).to_le_bytes());
        let mut cursor = 16;
        for unit in substitute
            .iter()
            .chain(std::iter::once(&0u16))
            .chain(print.iter())
            .chain(std::iter::once(&0u16))
        {
            buffer[cursor..cursor + 2].copy_from_slice(&unit.to_le_bytes());
            cursor += 2;
        }
        let mut returned = 0u32;
        unsafe {
            DeviceIoControl(
                HANDLE(dir.as_raw_handle()),
                FSCTL_SET_REPARSE_POINT,
                Some(buffer.as_ptr().cast()),
                buffer.len() as u32,
                None,
                0,
                Some(&mut returned),
                None,
            )
        }
        .map_err(|error| format!("set reparse point: {error}"))
    }

    #[test]
    fn junction_parent_swap_is_rejected() {
        let root = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let junction = root.path().join("junction");
        create_junction(&junction, outside.path())
            .unwrap_or_else(|error| panic!("junction coverage setup failed: {error}"));
        let path = junction.join("config.json");
        assert!(update_with_backup(&path, root.path(), "new").is_err());
        assert!(!outside.path().join("config.json").exists());
    }

    #[test]
    fn held_parent_handles_block_concurrent_parent_swap() {
        let root = tempfile::tempdir().unwrap();
        let parent = root.path().join("configs");
        fs::create_dir(&parent).unwrap();
        let path = parent.join("config.json");
        fs::write(&path, "before").unwrap();
        let moved = root.path().join("moved-configs");
        let mut swap_was_blocked = false;
        transactional_update_with_hook(
            &path,
            root.path(),
            |_| Ok(FileUpdate::write_text("after".into(), 0o644)),
            |stage| {
                if stage == TestStage::TempSynced {
                    swap_was_blocked = fs::rename(&parent, &moved).is_err();
                }
                Ok(())
            },
        )
        .unwrap();
        assert!(swap_was_blocked);
        assert_eq!(fs::read_to_string(path).unwrap(), "after");
        assert!(!moved.exists());
    }

    #[test]
    fn same_second_backups_are_unique_and_handle_bound_retention_keeps_five() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "zero").unwrap();
        update_with_backup(&path, root.path(), "one").unwrap();
        update_with_backup(&path, root.path(), "two").unwrap();
        assert_eq!(backup_paths(root.path()).len(), 2);
        for index in 0..6 {
            update_with_backup(&path, root.path(), &format!("value-{index}")).unwrap();
        }
        let retained = backup_paths(root.path());
        assert_eq!(retained.len(), 5);
        assert!(retained
            .iter()
            .any(|backup| fs::read_to_string(backup).unwrap() == "value-4"));
    }

    #[test]
    fn backup_full_generation_is_revalidated_before_commit_announcement() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "before").unwrap();
        let lock = PlatformTransaction::lock(&path, root.path()).unwrap();
        let transaction = PlatformTransaction::begin(&path, root.path(), lock).unwrap();
        let snapshot = transaction.read_snapshot().unwrap();
        let mut backup = transaction.create_backup(&snapshot).unwrap();
        let capability = backup.cleanup.as_mut().unwrap();
        capability.file.seek(SeekFrom::Start(0)).unwrap();
        capability.file.write_all(b"tamper").unwrap();
        unsafe { FlushFileBuffers(HANDLE(capability.file.as_raw_handle())) }.unwrap();

        let error = backup.commit().unwrap_err();
        assert!(error.contains("commit/announcement"));
    }

    #[test]
    fn old_backup_cleanup_handle_blocks_swap_before_deletion() {
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::Arc;

        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "original").unwrap();
        for index in 0..5 {
            update_with_backup(&path, root.path(), &format!("value-{index}")).unwrap();
        }
        let swap_was_blocked = Arc::new(AtomicBool::new(false));
        let observed = swap_was_blocked.clone();
        let moved = root.path().join("attacker-moved-old-backup");
        with_cleanup_hook(
            move |old| {
                if fs::rename(old, &moved).is_err() {
                    observed.store(true, Ordering::SeqCst);
                }
            },
            || update_with_backup(&path, root.path(), "updated").unwrap(),
        );

        assert!(swap_was_blocked.load(Ordering::SeqCst));
        assert!(!root.path().join("attacker-moved-old-backup").exists());
        assert_eq!(backup_paths(root.path()).len(), 5);
    }

    #[test]
    fn creation_handles_close_the_temp_and_backup_reopen_race() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;

        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "before").unwrap();
        let blocked = Arc::new(AtomicUsize::new(0));
        let observed = blocked.clone();
        let moved_root = root.path().to_path_buf();
        with_artifact_capture_hook(
            move |artifact| {
                let moved =
                    moved_root.join(format!("attacker-swap-{}", uuid::Uuid::new_v4().simple()));
                if fs::rename(artifact, moved).is_err() {
                    observed.fetch_add(1, Ordering::SeqCst);
                }
            },
            || update_with_backup(&path, root.path(), "after").unwrap(),
        );

        assert_eq!(blocked.load(Ordering::SeqCst), 3);
        assert_eq!(fs::read_to_string(path).unwrap(), "after");
    }

    #[test]
    fn precreated_regular_and_reparse_backup_names_are_never_overwritten() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "original").unwrap();
        let regular = root
            .path()
            .join("config.json.tirith-backup-99999999-999999-attacker");
        fs::write(&regular, "attacker-regular").unwrap();
        let target = root.path().join("outside-secret");
        fs::write(&target, "attacker-target").unwrap();
        let link = root
            .path()
            .join("config.json.tirith-backup-99999999-999999-reparse");
        if !symlink_file_or_explicitly_skip(&target, &link) {
            return;
        }
        update_with_backup(&path, root.path(), "updated").unwrap();
        assert_eq!(fs::read_to_string(regular).unwrap(), "attacker-regular");
        assert_eq!(fs::read_to_string(target).unwrap(), "attacker-target");
    }

    #[test]
    fn retention_does_not_delete_unproven_backup_prefix_lookalikes() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "zero").unwrap();
        let forged = root.path().join(format!(
            "{BACKUP_MARKER}{}-20260101-000000-000000000_{}_{}",
            destination_tag(&path),
            "0".repeat(64),
            "a".repeat(32)
        ));
        fs::write(&forged, "attacker-lookalike").unwrap();
        for index in 0..8 {
            update_with_backup(&path, root.path(), &format!("value-{index}")).unwrap();
        }
        assert_eq!(fs::read_to_string(forged).unwrap(), "attacker-lookalike");
        assert_eq!(backup_paths(root.path()).len(), 6);
    }

    #[test]
    fn displaced_recovery_retention_is_provenance_bound_and_capped_at_five() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "zero").unwrap();
        let forged = root.path().join(format!(
            "{DISPLACED_MARKER}{}-20260101-000000-000000000_{}_{}",
            destination_tag(&path),
            "0".repeat(64),
            "b".repeat(32)
        ));
        fs::write(&forged, "attacker-recovery-lookalike").unwrap();

        for index in 0..8 {
            let outcome = transactional_update(&path, root.path(), false, |_| {
                Ok(FileUpdate::write_text(format!("value-{index}"), 0o600))
            })
            .unwrap();
            assert_eq!(outcome, TransactionOutcome::WrittenWithRecovery);
        }

        assert_eq!(
            fs::read_to_string(&forged).unwrap(),
            "attacker-recovery-lookalike"
        );
        let recoveries = displaced_paths(root.path());
        assert_eq!(recoveries.len(), 6);
        assert!(recoveries
            .iter()
            .any(|recovery| fs::read_to_string(recovery).unwrap() == "value-6"));
    }

    #[test]
    fn non_cooperating_generation_change_is_rejected_and_temp_is_removed() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "before").unwrap();
        let result = transactional_update_with_hook(
            &path,
            root.path(),
            |_| Ok(FileUpdate::write_text("ours".into(), 0o644)),
            |stage| {
                if stage == TestStage::TempSynced {
                    fs::write(&path, "editor-change").unwrap();
                }
                Ok(())
            },
        );
        assert!(result.unwrap_err().contains("changed while setup"));
        assert_eq!(fs::read_to_string(&path).unwrap(), "editor-change");
        assert!(!fs::read_dir(root.path())
            .unwrap()
            .filter_map(Result::ok)
            .any(|entry| {
                entry
                    .file_name()
                    .to_string_lossy()
                    .starts_with(".tirith-setup-")
                    && entry.path() != path
            }));
    }

    #[test]
    fn prepared_temp_handle_blocks_name_swap_before_publication() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "before").unwrap();
        let mut deletion_was_blocked = false;
        transactional_update_with_hook(
            &path,
            root.path(),
            |_| Ok(FileUpdate::write_text("after".into(), 0o644)),
            |stage| {
                if stage == TestStage::TempSynced {
                    let temp = fs::read_dir(root.path())
                        .unwrap()
                        .filter_map(Result::ok)
                        .find(|entry| {
                            let name = entry.file_name();
                            let name = name.to_string_lossy();
                            name.starts_with(".tirith-setup-") && name.ends_with(".tmp")
                        })
                        .unwrap()
                        .path();
                    deletion_was_blocked = fs::remove_file(temp).is_err();
                }
                Ok(())
            },
        )
        .unwrap();
        assert!(deletion_was_blocked);
        assert_eq!(fs::read_to_string(path).unwrap(), "after");
    }

    #[test]
    fn prepared_backup_handle_blocks_cleanup_name_swap() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "before").unwrap();
        let mut swap_was_blocked = false;
        let error = transactional_update_with_hook(
            &path,
            root.path(),
            |_| Ok(FileUpdate::write_text("after".into(), 0o644).with_backup(true)),
            |stage| {
                if stage == TestStage::TempSynced {
                    let backup = backup_paths(root.path()).pop().unwrap();
                    swap_was_blocked =
                        fs::rename(&backup, root.path().join("swapped-backup")).is_err();
                    return Err("injected failure after backup race".into());
                }
                Ok(())
            },
        )
        .unwrap_err();
        assert!(error.contains("injected failure"));
        assert!(swap_was_blocked);
        assert!(backup_paths(root.path()).is_empty());
        assert_eq!(fs::read_to_string(path).unwrap(), "before");
    }

    #[test]
    fn prepared_backup_never_grants_write_sharing() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "before").unwrap();
        let mut write_was_blocked = false;
        let error = transactional_update_with_hook(
            &path,
            root.path(),
            |_| Ok(FileUpdate::write_text("after".into(), 0o644).with_backup(true)),
            |stage| {
                if stage == TestStage::TempSynced {
                    let backup = backup_paths(root.path()).pop().unwrap();
                    write_was_blocked = fs::OpenOptions::new().write(true).open(backup).is_err();
                    return Err("stop after write-sharing proof".into());
                }
                Ok(())
            },
        )
        .unwrap_err();
        assert!(error.contains("write-sharing proof"));
        assert!(write_was_blocked);
    }

    #[test]
    fn destination_swap_after_validation_is_detected_and_competitor_is_restored() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        let original_hold = root.path().join("original-held-by-writer");
        fs::write(&path, "original").unwrap();
        let original_generation = generation_at(&path).unwrap().unwrap();
        let mut competitor_generation = None;

        let error = transactional_update_with_hook(
            &path,
            root.path(),
            |_| Ok(FileUpdate::write_text("tirith-update".into(), 0o644)),
            |stage| {
                if stage == TestStage::PublicationReady {
                    fs::rename(&path, &original_hold).unwrap();
                    fs::write(&path, "competing-writer").unwrap();
                    competitor_generation = generation_at(&path).unwrap();
                }
                Ok(())
            },
        )
        .unwrap_err();

        assert!(error.contains("restored the competing destination"));
        assert_eq!(fs::read_to_string(&path).unwrap(), "competing-writer");
        assert_eq!(generation_at(&path).unwrap(), competitor_generation);
        assert_eq!(fs::read_to_string(&original_hold).unwrap(), "original");
        assert_eq!(
            generation_at(&original_hold).unwrap(),
            Some(original_generation)
        );
        assert!(temporary_setup_paths(root.path()).is_empty());
        assert!(displaced_paths(root.path()).is_empty());
    }

    #[test]
    fn temp_swap_after_validation_never_publishes_attacker_identity() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        let held_prepared = root.path().join("prepared-held-by-writer");
        fs::write(&path, "original").unwrap();
        let original_generation = generation_at(&path).unwrap().unwrap();
        let mut attacker_path = None;
        let mut attacker_generation = None;
        let mut prepared_generation = None;

        let error = transactional_update_with_hook(
            &path,
            root.path(),
            |_| Ok(FileUpdate::write_text("tirith-update".into(), 0o644)),
            |stage| {
                if stage == TestStage::PublicationReady {
                    let temp = temporary_setup_paths(root.path()).pop().unwrap();
                    prepared_generation = generation_at(&temp).unwrap();
                    fs::rename(&temp, &held_prepared).unwrap();
                    fs::write(&temp, "attacker-temp").unwrap();
                    attacker_generation = generation_at(&temp).unwrap();
                    attacker_path = Some(temp);
                }
                Ok(())
            },
        )
        .unwrap_err();

        assert!(error.contains("restored the competing destination"));
        assert_eq!(fs::read_to_string(&path).unwrap(), "original");
        assert_eq!(generation_at(&path).unwrap(), Some(original_generation));
        let attacker_path = attacker_path.unwrap();
        assert_eq!(fs::read_to_string(&attacker_path).unwrap(), "attacker-temp");
        // The aborted publication briefly installed the attacker's file at the
        // destination, where ReplaceFileW rewrote that file's own security
        // descriptor (the merge behavior the restore path exists to undo for
        // OUR files). Retention promises the attacker's exact identity and
        // bytes were kept out of the destination — not that the attacker's
        // descriptor survived the attempt unchanged.
        let mut retained = generation_at(&attacker_path).unwrap().unwrap();
        let mut expected = attacker_generation.unwrap();
        retained.security_descriptor.clear();
        expected.security_descriptor.clear();
        assert_eq!(retained, expected);
        assert_eq!(fs::read_to_string(&held_prepared).unwrap(), "tirith-update");
        assert_eq!(generation_at(&held_prepared).unwrap(), prepared_generation);
    }

    #[test]
    fn same_length_destination_change_with_restored_timestamp_is_rejected() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "original-state").unwrap();

        let error = transactional_update_with_hook(
            &path,
            root.path(),
            |_| Ok(FileUpdate::write_text("tirith-update!".into(), 0o644)),
            |stage| {
                if stage == TestStage::PublicationReady {
                    overwrite_same_length_and_restore_last_write(&path, b"attacker-state");
                }
                Ok(())
            },
        )
        .unwrap_err();

        assert!(error.contains("restored the competing destination"));
        assert_eq!(fs::read_to_string(path).unwrap(), "attacker-state");
    }

    #[test]
    fn same_length_temp_change_with_restored_timestamp_is_never_accepted() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "original").unwrap();
        let mut mutated_temp = None;

        let error = transactional_update_with_hook(
            &path,
            root.path(),
            |_| Ok(FileUpdate::write_text("tirith-update".into(), 0o644)),
            |stage| {
                if stage == TestStage::PublicationReady {
                    let temp = temporary_setup_paths(root.path()).pop().unwrap();
                    overwrite_same_length_and_restore_last_write(&temp, b"attack-update");
                    mutated_temp = Some(temp);
                }
                Ok(())
            },
        )
        .unwrap_err();

        assert!(error.contains("restored the competing destination"));
        assert_eq!(fs::read_to_string(path).unwrap(), "original");
        assert_eq!(
            fs::read_to_string(mutated_temp.unwrap()).unwrap(),
            "attack-update"
        );
    }

    #[test]
    fn unable_to_move_replacement_is_verified_as_clean_failure() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "original").unwrap();
        let original_generation = generation_at(&path).unwrap().unwrap();

        let error = with_replace_hook(
            |_destination, _replacement, _displaced| Err(ERROR_UNABLE_TO_MOVE_REPLACEMENT.0),
            || {
                transactional_update(&path, root.path(), false, |_| {
                    Ok(FileUpdate::write_text("tirith-update".into(), 0o644))
                })
                .unwrap_err()
            },
        );

        assert!(error.contains("before moving either identity"));
        assert_eq!(fs::read_to_string(&path).unwrap(), "original");
        assert_eq!(generation_at(&path).unwrap(), Some(original_generation));
        assert!(temporary_setup_paths(root.path()).is_empty());
        assert!(displaced_paths(root.path()).is_empty());
        assert!(backup_paths(root.path()).is_empty());
    }

    #[test]
    fn unable_to_move_replacement_2_retains_exact_identity_recovery() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "original").unwrap();
        let original_generation = generation_at(&path).unwrap().unwrap();

        let error = with_replace_hook(
            |destination, _replacement, displaced| {
                fs::rename(destination, displaced).unwrap();
                Err(ERROR_UNABLE_TO_MOVE_REPLACEMENT_2.0)
            },
            || {
                transactional_update(&path, root.path(), false, |_| {
                    Ok(FileUpdate::write_text("tirith-update".into(), 0o644))
                })
                .unwrap_err()
            },
        );

        assert!(error.contains("partial Windows failure state"));
        assert!(!path.exists());
        let displaced = displaced_paths(root.path());
        assert_eq!(displaced.len(), 1);
        assert_eq!(fs::read_to_string(&displaced[0]).unwrap(), "original");
        assert_eq!(
            generation_at(&displaced[0]).unwrap(),
            Some(original_generation)
        );
        let prepared = temporary_setup_paths(root.path());
        assert_eq!(prepared.len(), 1);
        assert_eq!(fs::read_to_string(&prepared[0]).unwrap(), "tirith-update");
        let recovery = backup_paths(root.path());
        assert_eq!(recovery.len(), 1);
        assert_eq!(fs::read_to_string(&recovery[0]).unwrap(), "original");
    }

    #[test]
    fn publication_failure_rolls_back_only_its_backup_and_temp() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "before").unwrap();
        let result = transactional_update_with_hook(
            &path,
            root.path(),
            |_| Ok(FileUpdate::write_text("ours".into(), 0o644).with_backup(true)),
            |stage| {
                if stage == TestStage::SnapshotValidated {
                    fs::remove_file(&path).unwrap();
                    fs::create_dir(&path).unwrap();
                }
                Ok(())
            },
        );
        assert!(result.is_err());
        assert!(backup_paths(root.path()).is_empty());
        assert!(!fs::read_dir(root.path())
            .unwrap()
            .filter_map(Result::ok)
            .any(|entry| {
                entry
                    .file_name()
                    .to_string_lossy()
                    .starts_with(".tirith-setup-")
            }));
    }

    #[test]
    fn exact_handle_cleanup_failure_is_propagated_with_primary_error() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "before").unwrap();
        DELETE_FAILURE_TEST_HOOK.with(|slot| slot.set(true));
        let result = transactional_update_with_hook(
            &path,
            root.path(),
            |_| Ok(FileUpdate::write_text("after".into(), 0o644).with_backup(true)),
            |stage| {
                if stage == TestStage::TempSynced {
                    return Err("injected pre-publication failure".into());
                }
                Ok(())
            },
        );
        DELETE_FAILURE_TEST_HOOK.with(|slot| slot.set(false));

        let error = result.unwrap_err();
        assert!(error.contains("injected pre-publication failure"));
        assert!(error.contains("cleanup also failed"));
        assert_eq!(fs::read_to_string(path).unwrap(), "before");
    }

    #[test]
    fn post_publication_failure_retains_exact_original_recovery() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "before").unwrap();
        let error = transactional_update_with_hook(
            &path,
            root.path(),
            |_| Ok(FileUpdate::write_text("after".into(), 0o644).with_backup(true)),
            |stage| {
                if stage == TestStage::Published {
                    return Err("injected installed-file durability failure".into());
                }
                Ok(())
            },
        )
        .unwrap_err();

        assert!(error.contains("durability"));
        assert!(error.contains("exact displaced original"));
        assert_eq!(fs::read_to_string(&path).unwrap(), "after");
        let displaced = displaced_paths(root.path());
        assert_eq!(displaced.len(), 1);
        assert_eq!(fs::read_to_string(&displaced[0]).unwrap(), "before");
        assert_eq!(backup_paths(root.path()).len(), 2);
    }

    #[test]
    fn held_installed_identity_blocks_name_swap_through_completion() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        let moved = root.path().join("writer-moved-install");
        fs::write(&path, "before").unwrap();
        let mut swap_was_blocked = false;
        transactional_update_with_hook(
            &path,
            root.path(),
            |_| Ok(FileUpdate::write_text("after".into(), 0o644)),
            |stage| {
                if stage == TestStage::Published {
                    swap_was_blocked = fs::rename(&path, &moved).is_err();
                }
                Ok(())
            },
        )
        .unwrap();

        assert!(swap_was_blocked);
        assert_eq!(fs::read_to_string(path).unwrap(), "after");
        assert!(!moved.exists());
    }

    fn wait_for_marker(path: &Path) {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while !path.exists() {
            assert!(
                std::time::Instant::now() < deadline,
                "timed out waiting for subprocess marker {}",
                path.display()
            );
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
    }

    #[test]
    fn subprocess_lock_child() {
        let Some(role) = std::env::var_os("TIRITH_SETUP_LOCK_CHILD_ROLE") else {
            return;
        };
        let root = PathBuf::from(std::env::var_os("TIRITH_SETUP_LOCK_ROOT").unwrap());
        let path = root.join("config.txt");
        match role.to_string_lossy().as_ref() {
            "holder" => {
                let entered = root.join("holder-entered");
                let release = root.join("release-holder");
                transactional_update_with_hook(
                    &path,
                    &root,
                    |snapshot| {
                        let mut content = snapshot.text(&path)?.unwrap().to_string();
                        content.push_str("-holder");
                        Ok(FileUpdate::write_text(content, 0o644))
                    },
                    |stage| {
                        if stage == TestStage::TempSynced {
                            fs::write(&entered, b"locked").unwrap();
                            wait_for_marker(&release);
                        }
                        Ok(())
                    },
                )
                .unwrap();
            }
            "contender" => {
                assert!(PlatformTransaction::lock_is_contended(&path, &root).unwrap());
                fs::write(root.join("contender-observed-lock"), b"contended").unwrap();
                transactional_update(&path, &root, false, |snapshot| {
                    let mut content = snapshot.text(&path)?.unwrap().to_string();
                    content.push_str("-contender");
                    Ok(FileUpdate::write_text(content, 0o644))
                })
                .unwrap();
            }
            other => panic!("unknown setup lock child role {other}"),
        }
    }

    #[test]
    fn cooperative_transactions_overlap_in_distinct_processes_and_recompute() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.txt");
        fs::write(&path, "base").unwrap();
        let test_binary = std::env::current_exe().unwrap();
        let test_name = "cli::setup::fs_helpers::tests::subprocess_lock_child";

        let mut holder = std::process::Command::new(&test_binary)
            .args(["--exact", test_name, "--nocapture"])
            .env("TIRITH_SETUP_LOCK_CHILD_ROLE", "holder")
            .env("TIRITH_SETUP_LOCK_ROOT", root.path())
            .spawn()
            .unwrap();
        wait_for_marker(&root.path().join("holder-entered"));

        let mut contender = std::process::Command::new(&test_binary)
            .args(["--exact", test_name, "--nocapture"])
            .env("TIRITH_SETUP_LOCK_CHILD_ROLE", "contender")
            .env("TIRITH_SETUP_LOCK_ROOT", root.path())
            .spawn()
            .unwrap();
        wait_for_marker(&root.path().join("contender-observed-lock"));
        assert!(holder.try_wait().unwrap().is_none());
        assert!(contender.try_wait().unwrap().is_none());

        fs::write(root.path().join("release-holder"), b"release").unwrap();
        assert!(holder.wait().unwrap().success());
        assert!(contender.wait().unwrap().success());
        let content = fs::read_to_string(path).unwrap();
        assert!(content.contains("-holder") && content.contains("-contender"));
    }

    #[test]
    fn cooperative_transactions_serialize_and_recompute() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.txt");
        fs::write(&path, "base").unwrap();
        let barrier = std::sync::Arc::new(std::sync::Barrier::new(3));
        let mut threads = Vec::new();
        for suffix in ["-one", "-two"] {
            let path = path.clone();
            let root = root.path().to_path_buf();
            let barrier = barrier.clone();
            threads.push(std::thread::spawn(move || {
                barrier.wait();
                transactional_update(&path, &root, false, |snapshot| {
                    let mut content = snapshot.text(&path)?.unwrap().to_string();
                    content.push_str(suffix);
                    Ok(FileUpdate::write_text(content, 0o644))
                })
            }));
        }
        barrier.wait();
        for thread in threads {
            thread.join().unwrap().unwrap();
        }
        let result = fs::read_to_string(path).unwrap();
        assert!(result.contains("-one") && result.contains("-two"));
    }

    #[test]
    fn oversized_snapshot_is_rejected_at_cap_plus_one() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("huge.json");
        fs::write(
            &path,
            vec![b'x'; super::super::fs_transaction::MAX_SETUP_FILE_BYTES + 1],
        )
        .unwrap();
        assert!(read_to_string_scoped(&path, root.path()).is_err());
    }

    #[test]
    fn transformed_payload_cap_is_enforced_before_parent_creation() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("missing").join("too-large.json");
        let payload = "x".repeat(super::super::fs_transaction::MAX_SETUP_FILE_BYTES + 1);
        let error = transactional_update(&path, root.path(), false, |_| {
            Ok(FileUpdate::write_text(payload.clone(), 0o600))
        })
        .unwrap_err();
        assert!(error.contains("setup file limit"));
        assert!(!root.path().join("missing").exists());
    }

    #[test]
    fn drifted_transform_is_recomputed_and_capped_before_artifacts() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "base").unwrap();
        let oversized = "x".repeat(super::super::fs_transaction::MAX_SETUP_FILE_BYTES + 1);
        let error = transactional_update_with_hook(
            &path,
            root.path(),
            |snapshot| {
                if snapshot.text(&path)? == Some("base") {
                    Ok(FileUpdate::write_text("small".into(), 0o600).with_backup(true))
                } else {
                    Ok(FileUpdate::write_text(oversized.clone(), 0o600).with_backup(true))
                }
            },
            |stage| {
                if stage == TestStage::PreflightReady {
                    fs::write(&path, "drift").unwrap();
                }
                Ok(())
            },
        )
        .unwrap_err();

        assert!(error.contains("setup file limit"));
        assert_eq!(fs::read_to_string(path).unwrap(), "drift");
        assert!(backup_paths(root.path()).is_empty());
        assert!(temporary_setup_paths(root.path()).is_empty());
        assert!(displaced_paths(root.path()).is_empty());
    }

    #[test]
    fn transformed_payload_exact_cap_is_accepted() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("exact-cap.json");
        let payload = "x".repeat(super::super::fs_transaction::MAX_SETUP_FILE_BYTES);
        transactional_update(&path, root.path(), false, |_| {
            Ok(FileUpdate::write_text(payload.clone(), 0o600))
        })
        .unwrap();
        assert_eq!(fs::metadata(path).unwrap().len(), payload.len() as u64);
    }

    #[test]
    fn replace_file_preserves_original_dacl_descriptor() {
        use windows::Win32::Security::SE_DACL_PROTECTED;

        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "before").unwrap();
        let before_handle = open_existing(&path).unwrap().unwrap();
        let mut before = security_descriptor(before_handle.0, &path).unwrap();
        assert_eq!(
            descriptor_control(&mut before) & SE_DACL_PROTECTED.0,
            0,
            "fixture must exercise an inheriting DACL"
        );
        drop(before_handle);
        transactional_update(&path, root.path(), false, |_| {
            Ok(FileUpdate::write_text("after".into(), 0o644))
        })
        .unwrap();
        let after_handle = open_existing(&path).unwrap().unwrap();
        let after = security_descriptor(after_handle.0, &path).unwrap();
        assert_eq!(before, after);
    }

    #[test]
    fn replace_file_preserves_protected_dacl_descriptor() {
        use windows::Win32::Security::SE_DACL_PROTECTED;

        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        create_protected_owner_only_file(&path, b"before");
        let before_handle = open_existing(&path).unwrap().unwrap();
        let mut before = security_descriptor(before_handle.0, &path).unwrap();
        assert_ne!(
            descriptor_control(&mut before) & SE_DACL_PROTECTED.0,
            0,
            "fixture must exercise a protected DACL"
        );
        drop(before_handle);
        transactional_update(&path, root.path(), false, |_| {
            Ok(FileUpdate::write_text("after".into(), 0o644))
        })
        .unwrap();
        let after_handle = open_existing(&path).unwrap().unwrap();
        let after = security_descriptor(after_handle.0, &path).unwrap();
        assert_eq!(before, after);
    }

    #[test]
    fn backup_dacl_is_protected_and_owner_only() {
        use windows::Win32::Security::{
            AclSizeInformation, GetAclInformation, GetSecurityDescriptorControl,
            GetSecurityDescriptorDacl, ACL, ACL_SIZE_INFORMATION, SE_DACL_PROTECTED,
        };

        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config.json");
        fs::write(&path, "before").unwrap();
        update_with_backup(&path, root.path(), "after").unwrap();
        let backup = backup_paths(root.path()).pop().unwrap();
        let handle = open_existing(&backup).unwrap().unwrap();
        let mut descriptor = security_descriptor(handle.0, &backup).unwrap();
        let descriptor = PSECURITY_DESCRIPTOR(descriptor.as_mut_ptr().cast());
        let mut control = 0u16;
        let mut revision = 0u32;
        unsafe { GetSecurityDescriptorControl(descriptor, &mut control, &mut revision) }.unwrap();
        assert_ne!(control & SE_DACL_PROTECTED.0, 0);
        let mut present = BOOL(0);
        let mut defaulted = BOOL(0);
        let mut dacl: *mut ACL = std::ptr::null_mut();
        unsafe { GetSecurityDescriptorDacl(descriptor, &mut present, &mut dacl, &mut defaulted) }
            .unwrap();
        assert!(present.as_bool() && !dacl.is_null());
        let mut size = ACL_SIZE_INFORMATION::default();
        unsafe {
            GetAclInformation(
                dacl,
                (&mut size as *mut ACL_SIZE_INFORMATION).cast(),
                std::mem::size_of::<ACL_SIZE_INFORMATION>() as u32,
                AclSizeInformation,
            )
        }
        .unwrap();
        assert_eq!(size.AceCount, 1);
    }

    fn cmd() -> tirith_core::trusted_child::TrustedExecutable {
        let root = std::env::var_os("SystemRoot").expect("SystemRoot");
        tirith_core::trusted_child::TrustedExecutable::from_absolute(
            &PathBuf::from(root).join("System32").join("cmd.exe"),
            &[],
        )
        .expect("trusted system cmd.exe")
    }

    #[test]
    fn windows_setup_runner_preserves_short_legitimate_output() {
        // Room to spare on both streams: this case proves legitimate output
        // survives the supervisor, and any host-dependent extra bytes surface
        // in the assertion below instead of as an opaque limit refusal. The
        // limit path itself is covered by the next test.
        let output = run_cli_bounded(
            &cmd(),
            &["/D", "/S", "/C", "<nul set /p =setup-ok"],
            tirith_core::trusted_child::ChildLimits::new(
                std::time::Duration::from_secs(5),
                4096,
                4096,
            ),
        )
        .unwrap();
        // `set /p` reports errorlevel 1 when its input reaches EOF, which the
        // `<nul` redirect guarantees, so the exit code carries no signal here.
        // What this case proves is that the supervisor hands back the child's
        // exact bytes.
        assert_eq!(
            String::from_utf8_lossy(&output.stdout),
            "setup-ok",
            "status={:?} stderr={}",
            output.status,
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[test]
    fn windows_setup_runner_surfaces_output_limit() {
        let error = run_cli_bounded(
            &cmd(),
            &["/D", "/S", "/C", "<nul set /p =12345"],
            tirith_core::trusted_child::ChildLimits::new(std::time::Duration::from_secs(5), 4, 64),
        )
        .unwrap_err();
        assert!(error.contains("output limit"));
    }

    #[test]
    fn codex_scope_uses_cli_cd_without_mutating_child_cwd() {
        let cwd = Path::new(r"C:\Users\operator\codex-scope");
        let args = codex_scoped_args(cwd, &["mcp", "list", "--json"]);
        assert_eq!(args[0], OsString::from("-C"));
        assert_eq!(args[1], cwd.as_os_str());
        assert_eq!(args[2..], ["mcp", "list", "--json"].map(OsString::from));
    }
}