rch 2.1.25

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

use super::*;
use crate::transfer::WorkerPlatform;

const MAX_OFFLOAD_SSH_OUTPUT_BYTES: usize = 32 * 1024 * 1024;
const MAX_SOURCE_LOCK_READY_BYTES: usize = 4096;
const MAX_SOURCE_LOCK_OUTPUT_BYTES: usize = 64 * 1024;
const REMOTE_SOURCE_AUTHORITY_LOCK_DIR: &str = "/tmp/rch-source-authority-locks";
const SOURCE_AUTHORITY_LOCK_HOLDER: &str = include_str!("source_lock_holder.sh");
const SOURCE_CLAIM_REGISTRY: &str = include_str!("source_claim_registry.sh");
const REMOTE_SOURCE_CLAIM_REGISTRY: &str = "/tmp/rch-source-authority-locks/claims-v1";

/// Keeps the worker-side advisory locks for a mutable Cargo source closure alive.
///
/// The remote holder blocks on this SSH session's stdin after acquiring every
/// lock. EOF/HUP releases kernel locks but retains a durable ownership claim.
/// Only explicit, acknowledged release permits an overlapping future writer.
pub(super) struct RemoteSourceAuthorityLock {
    worker_id: WorkerId,
    child: Option<tokio::process::Child>,
    stdin: Option<tokio::process::ChildStdin>,
    stdout_drain: Option<tokio::task::JoinHandle<std::io::Result<Vec<u8>>>>,
    stderr_drain: Option<tokio::task::JoinHandle<std::io::Result<Vec<u8>>>>,
    release_request: Option<String>,
    pair_root: Option<String>,
}

impl RemoteSourceAuthorityLock {
    pub(super) fn pair_token(&self) -> Option<&str> {
        self.release_request
            .as_deref()?
            .strip_prefix("RCH_SOURCE_PAIR_RELEASE:")
    }

    /// OpenSSH uses 255 for transport errors; a missing local exit status is
    /// represented as -1. Neither proves that remote Cargo has stopped.
    pub(super) fn ensure_execution_finished(&mut self, exit_code: i32) -> anyhow::Result<()> {
        self.ensure_held()?;
        if !(0..255).contains(&exit_code) {
            anyhow::bail!(
                "source pair remains occupied: SSH execution exit {exit_code} does not prove remote completion"
            );
        }
        Ok(())
    }

    /// Fail closed if the lock-holder SSH process disappeared before Cargo starts.
    pub(super) fn ensure_held(&mut self) -> anyhow::Result<()> {
        let child = self
            .child
            .as_mut()
            .ok_or_else(|| anyhow::anyhow!("remote source-authority lock is not active"))?;
        if let Some(status) = child.try_wait()? {
            anyhow::bail!(
                "remote source-authority lock on {} exited before Cargo started: {}",
                self.worker_id,
                status
            );
        }
        Ok(())
    }

    /// Release the locks after Cargo exits and prove the holder stayed healthy.
    pub(super) async fn release(self) -> anyhow::Result<()> {
        self.release_with_timeout(Duration::from_secs(15)).await
    }

    async fn release_with_timeout(mut self, budget: Duration) -> anyhow::Result<()> {
        use tokio::io::AsyncWriteExt as _;

        let deadline = tokio::time::Instant::now() + budget;
        let collect = async {
            if let Some(request) = self.release_request.as_ref() {
                let stdin = self
                    .stdin
                    .as_mut()
                    .ok_or_else(|| anyhow::anyhow!("source ownership release stdin is missing"))?;
                stdin.write_all(format!("{request}\n").as_bytes()).await?;
            }
            drop(self.stdin.take());
            // Keep the child AND both handles in the guard until the whole
            // protocol finishes. Taking a JoinHandle would detach its reader
            // when this future times out or its caller stops waiting.
            let child = self
                .child
                .as_mut()
                .ok_or_else(|| anyhow::anyhow!("remote source-authority lock is not active"))?;
            let wait = async { Ok::<_, anyhow::Error>(child.wait().await?) };
            let (status, stdout, stderr) = tokio::try_join!(
                wait,
                join_lock_drain(self.stdout_drain.as_mut()),
                join_lock_drain(self.stderr_drain.as_mut()),
            )?;
            if !status.success() {
                anyhow::bail!(
                    "remote source-authority lock on {} exited unexpectedly: {}; stdout={}; stderr={}",
                    self.worker_id,
                    status,
                    String::from_utf8_lossy(&stdout).trim(),
                    String::from_utf8_lossy(&stderr).trim()
                );
            }
            if let Some(request) = self.release_request.as_ref()
                && stdout != format!("{request}\n").as_bytes()
            {
                anyhow::bail!(
                    "source ownership release acknowledgment missing on {}",
                    self.worker_id
                );
            }
            Ok(())
        };
        // A successful wait() does not imply EOF: descendants can retain the
        // pipes. The same deadline must cover the write, wait and BOTH drains.
        match tokio::time::timeout_at(deadline, collect).await {
            Ok(result) => result,
            Err(_) => anyhow::bail!(
                "timed out releasing remote source-authority lock on {}",
                self.worker_id
            ),
        }
    }
}

impl Drop for RemoteSourceAuthorityLock {
    fn drop(&mut self) {
        if let Some(child) = self.child.as_mut() {
            let _ = child.start_kill();
        }
        if let Some(task) = self.stdout_drain.take() {
            task.abort();
        }
        if let Some(task) = self.stderr_drain.take() {
            task.abort();
        }
    }
}

async fn join_lock_drain(
    task: Option<&mut tokio::task::JoinHandle<std::io::Result<Vec<u8>>>>,
) -> anyhow::Result<Vec<u8>> {
    match task {
        Some(task) => Ok(task.await??),
        None => Ok(Vec::new()),
    }
}

fn source_authority_lock_path(root: &str) -> String {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"rch.remote_source_authority_lock.v1\0");
    hasher.update(root.as_bytes());
    format!(
        "{REMOTE_SOURCE_AUTHORITY_LOCK_DIR}/{}.lock",
        hasher.finalize().to_hex()
    )
}

fn source_authority_lock_paths(authority_roots: &[String]) -> Vec<String> {
    let mut roots = authority_roots.to_vec();
    roots.sort();
    roots.dedup();
    roots
        .into_iter()
        .map(|root| source_authority_lock_path(&root))
        .collect()
}

/// The canonical spelling `source_authority_lock_plan` demands: a trailing `/`,
/// doubled `/` and `.` components removed (bd-4d1hs).
///
/// A project path given as `/data/tmp/landing/c9-beads/` reached the durable
/// lease verbatim. The lock plan then refused it, the wrapper died before
/// preparing, and `rch jobs recover` refused the same recorded root forever, so
/// the slot reservation was never returned. Anything not merely mis-spelled
/// (relative, `..`, control bytes, non-UTF-8) is returned unchanged so the lock
/// plan still rejects it loudly.
pub(crate) fn canonical_source_authority_root(root: &str) -> String {
    let path = Path::new(root);
    if !path.is_absolute()
        || root.bytes().any(|byte| matches!(byte, b'\n' | b'\r' | 0))
        || path.components().any(|component| {
            matches!(
                component,
                std::path::Component::ParentDir | std::path::Component::Prefix(_)
            )
        })
    {
        return root.to_string();
    }
    path.components()
        .collect::<PathBuf>()
        .to_str()
        .map_or_else(|| root.to_string(), str::to_string)
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct SourceAuthorityLockSpec {
    path: String,
    shared: bool,
}

/// A full-tree writer must exclude writers of any subtree. Shared ancestor
/// locks make that conflict visible without serializing disjoint siblings.
/// Resolve the strongest mode before taking any lock: upgrades can deadlock.
fn source_authority_lock_plan(
    authority_roots: &[String],
    include_ancestors: bool,
) -> anyhow::Result<Vec<SourceAuthorityLockSpec>> {
    let mut roots = std::collections::BTreeMap::new();
    for root in authority_roots {
        let path = Path::new(root);
        let canonical = path.components().collect::<PathBuf>();
        anyhow::ensure!(
            path.is_absolute()
                && path.as_os_str() == canonical.as_os_str()
                && !root.bytes().any(|byte| matches!(byte, b'\n' | b'\r' | 0))
                && !path.components().any(|component| matches!(
                    component,
                    std::path::Component::ParentDir | std::path::Component::Prefix(_)
                )),
            "source authority must be a canonical absolute path: {root:?}"
        );
        roots.insert(root.clone(), false);
        if include_ancestors {
            for ancestor in path.ancestors().skip(1) {
                roots
                    .entry(ancestor.to_string_lossy().into_owned())
                    .or_insert(true);
            }
        }
    }
    // Sort by canonical source paths, never by their lock-file hashes. Every
    // invocation then acquires overlapping sets in the same global order.
    Ok(roots
        .into_iter()
        .map(|(root, shared)| SourceAuthorityLockSpec {
            path: source_authority_lock_path(&root),
            shared,
        })
        .collect())
}

fn build_remote_source_authority_lock_cmd(
    lock_dir: &str,
    locks: &[SourceAuthorityLockSpec],
    ready_marker: &str,
) -> anyhow::Result<String> {
    if locks.is_empty() {
        anyhow::bail!("remote source-authority lock set must not be empty");
    }
    let mut seen = std::collections::HashSet::new();
    for lock in locks {
        let path = &lock.path;
        // The quoted here-document carries literal, one-lock-per-line data.
        // Absolute paths cannot equal its non-path delimiter. Keep the caller's
        // established canonical-root order; re-sorting hashes could deadlock
        // against older holders that acquire the same roots in that order.
        if !path.starts_with('/')
            || path.bytes().any(|byte| matches!(byte, b'\n' | b'\r' | 0))
            || !seen.insert(path)
        {
            anyhow::bail!("invalid or duplicate source-authority lock path: {path:?}");
        }
    }
    if ready_marker.is_empty()
        || ready_marker.len() >= MAX_SOURCE_LOCK_READY_BYTES
        || ready_marker
            .bytes()
            .any(|byte| matches!(byte, b'\n' | b'\r' | 0))
    {
        anyhow::bail!("invalid source-authority ready marker");
    }
    // The closure is data on fd 3, not an argument to SSH, sh, or flock.
    // The fixed holder re-execs with --no-fork and inherits each acquired
    // descriptor, avoiding both E2BIG and one live flock process per root.
    // One descriptor per root is still necessary; exhaustion fails before
    // readiness and process exit releases every partially acquired lock.
    let holder = shell_escape::escape(SOURCE_AUTHORITY_LOCK_HOLDER.into());
    let records = locks
        .iter()
        .map(|lock| format!("{} {}", if lock.shared { "s" } else { "x" }, lock.path))
        .collect::<Vec<_>>()
        .join("\n");
    Ok(format!(
        "set -e\nmkdir -p -- {directory}\nexec 3<<'RCH_SOURCE_LOCK_PATHS'\n{paths}\nRCH_SOURCE_LOCK_PATHS\nexec sh -c {holder} {holder} {count} {ready}",
        directory = shell_escape::escape(lock_dir.into()),
        paths = records,
        count = locks.len(),
        ready = shell_escape::escape(ready_marker.into()),
    ))
}

fn validate_source_identity(identity: &str) -> anyhow::Result<()> {
    anyhow::ensure!(
        !identity.is_empty()
            && identity.len() <= 128
            && identity
                .bytes()
                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte) || byte == b'-'),
        "invalid durable source identity"
    );
    Ok(())
}

fn source_claim_roots(authority_roots: &[String]) -> anyhow::Result<(String, String)> {
    use sha2::{Digest as _, Sha256};
    anyhow::ensure!(!authority_roots.is_empty(), "empty durable source grant");
    source_authority_lock_plan(authority_roots, false)?;
    let mut roots = authority_roots.to_vec();
    roots.sort();
    roots.dedup();
    let roots = format!("{}\n", roots.join("\n"));
    anyhow::ensure!(roots.len() <= 32 * 1024 * 1024, "source grant is too large");
    // sha2 0.11 digests are hybrid-array `Array`s, which implement no
    // `LowerHex`; spell out the lowercase hex that `sha256sum` prints.
    let digest = Sha256::digest(roots.as_bytes())
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect::<String>();
    Ok((roots, digest))
}

/// Reject an unusable intent before its durable journal can strand recovery.
/// Use the same identity and closure checks as remote acquisition; no path
/// normalization or new ownership authority is introduced here.
pub(super) fn validate_source_authority_intent(
    authority_roots: &[String],
    identity: &str,
) -> anyhow::Result<()> {
    validate_source_identity(identity)?;
    source_claim_roots(authority_roots)?;
    Ok(())
}

fn source_registry_setup(registry: &str) -> String {
    let quote = |value: &str| shell_escape::escape(value.into()).into_owned();
    format!(
        "set -eu; umask 077; registry={registry}; \
         [ ! -L \"$registry\" ]; mkdir -p -- \"$registry\"; \
         for directory in \"$registry/released\" \"$registry/cancelled\" \"$registry/quarantine\"; do \
         [ ! -L \"$directory\" ]; mkdir -p -- \"$directory\"; done; \
         [ ! -L \"$registry/metadata.lock\" ]; sync -f \"$registry\";\n",
        registry = quote(registry),
    )
}

fn source_registry_invocation(
    registry: &str,
    identity: &str,
    digest: &str,
    operation: &str,
) -> String {
    let quote = |value: &str| shell_escape::escape(value.into()).into_owned();
    let script = format!(
        "{}\n{}",
        rch_common::stale_target_reap::SOURCE_CLAIM_RECORD_HELPERS,
        SOURCE_CLAIM_REGISTRY,
    );
    format!(
        "flock -x -- {lock} sh -c {script} rch-source-registry {registry} {identity} {digest} {operation}",
        lock = quote(&format!("{registry}/metadata.lock")),
        script = quote(&script),
        registry = quote(registry),
        identity = quote(identity),
        digest = quote(digest),
        operation = quote(operation),
    )
}

fn source_authority_activity_prefix_at(registry: &str, identity: &str) -> anyhow::Result<String> {
    source_authority_activity_prefix_for_mode(registry, identity, false)
}

fn source_authority_activity_prefix_for_mode(
    registry: &str,
    identity: &str,
    cleanup: bool,
) -> anyhow::Result<String> {
    validate_source_identity(identity)?;
    let quote = |value: &str| shell_escape::escape(value.into()).into_owned();
    // The active record is checked AFTER acquiring the activity lock. A queued
    // late rsync/exec therefore cannot cross a release or cancellation boundary.
    let check = "set -eu; registry=$1; token=$2; mode=$3; shift 3; \
         set -- \"$registry/$token.\"*.claim \"$@\"; claim=$1; shift; \
         [ ! -L \"$registry\" ] && [ ! -L \"$claim\" ] && [ -f \"$claim\" ] || \
         { echo 'RCH: source grant is not active' >&2; exit 73; }; \
         case \"${1-}\" in \"$registry/$token.\"*.claim) \
         echo 'RCH: duplicate source grant' >&2; exit 73;; esac; \
         name=${claim##*/}; digest=${name#*.}; digest=${digest%.claim}; \
         case \"$digest\" in *[!a-f0-9]*) exit 73;; esac; [ \"${#digest}\" -eq 64 ]; \
         actual=$(sha256sum -- \"$claim\"); [ \"${actual%% *}\" = \"$digest\" ] || \
         { echo 'RCH: source grant content changed' >&2; exit 73; }; \
         cancelling=\"$registry/$token.$digest.cancelling\"; \
         case \"$mode\" in active) \
         [ ! -e \"$cancelling\" ] && [ ! -L \"$cancelling\" ] || \
         { echo 'RCH: source grant is cancelling' >&2; exit 73; };; \
         cleanup) [ ! -L \"$cancelling\" ] && [ -f \"$cancelling\" ] && \
         cmp -s \"$claim\" \"$cancelling\" || \
         { echo 'RCH: source cleanup authority is absent' >&2; exit 73; };; \
         *) exit 73;; esac; exec \"$@\"";
    Ok(format!(
        "nohup flock -x -- {activity} sh -c {check} rch-source-activity {registry} {identity} {mode}",
        activity = quote(&format!("{registry}/{identity}.activity.lock")),
        check = quote(check),
        registry = quote(registry),
        identity = quote(identity),
        mode = if cleanup { "cleanup" } else { "active" },
    ))
}

/// Prefix an actual remote process, including rsync's server or `sh -s`, while
/// preserving stdin for its command/input protocol. A HUP-resistant flock
/// supervisor retains the lease even when the actual tool closes inherited FDs.
/// Activities within one grant serialize: a surviving writer cannot overlap a
/// later verifier or compiler. Preparation failures still cancel the token;
/// flock ordering is not permission to retry an uncertain mutator in place.
pub(crate) fn source_authority_activity_prefix(identity: &str) -> anyhow::Result<String> {
    source_authority_activity_prefix_at(REMOTE_SOURCE_CLAIM_REGISTRY, identity)
}

/// Cleanup-only authority for an already owned, durably cancelling grant. It
/// cannot start a new normal operation or recover an absent source claim.
pub(crate) fn source_authority_cleanup_prefix(identity: &str) -> anyhow::Result<String> {
    source_authority_activity_prefix_for_mode(REMOTE_SOURCE_CLAIM_REGISTRY, identity, true)
}

pub(crate) fn wrap_remote_source_activity(command: &str, identity: &str) -> anyhow::Result<String> {
    Ok(format!(
        "{} sh -c {}",
        source_authority_activity_prefix(identity)?,
        shell_escape::escape(command.into()),
    ))
}

#[allow(clippy::too_many_arguments)]
fn build_durable_source_authority_lock_cmd(
    lock_dir: &str,
    registry: &str,
    locks: &[SourceAuthorityLockSpec],
    authority_roots: &[String],
    identity: &str,
    operation: &str,
    ready_marker: &str,
) -> anyhow::Result<String> {
    validate_source_identity(identity)?;
    let (roots, digest) = source_claim_roots(authority_roots)?;
    let quote = |value: &str| shell_escape::escape(value.into()).into_owned();
    let release = format!("RCH_SOURCE_AUTHORITY_RELEASE:{identity}");
    let transaction = source_registry_invocation(registry, identity, &digest, operation);
    let retirement = source_registry_invocation(registry, identity, &digest, "release");
    let terminal = format!(
        "set -eu; ready=$1; roots=$(cat <&4); exec 4<&-; \
         printf '%s\\n' \"$roots\" | {transaction}; \
         printf '%s\\n' \"$ready\"; IFS= read -r request; \
         [ \"$request\" = {release} ]; \
         printf '%s\\n' \"$roots\" | flock -x -- {activity} {retirement}; \
         printf '%s\\n' {release}",
        release = quote(&release),
        activity = quote(&format!("{registry}/{identity}.activity.lock")),
    );
    let base = if locks.is_empty() {
        // The only production caller with zero additional kernel locks already
        // owns its complete root through a validated live source-pair guard.
        format!(
            "exec 3</dev/null; exec sh -c {holder} {holder} 0 {ready}",
            holder = quote(SOURCE_AUTHORITY_LOCK_HOLDER),
            ready = quote(ready_marker),
        )
    } else {
        build_remote_source_authority_lock_cmd(lock_dir, locks, ready_marker)?
    };
    Ok(format!(
        "{}exec 4<<'RCH_SOURCE_CLAIM_ROOTS'\n{roots}RCH_SOURCE_CLAIM_ROOTS\n{base} {terminal}",
        source_registry_setup(registry),
        terminal = quote(&terminal),
    ))
}

fn source_intent_command(
    registry: &str,
    roots: &[String],
    identity: &str,
    operation: &str,
) -> anyhow::Result<String> {
    validate_source_identity(identity)?;
    let (roots, digest) = source_claim_roots(roots)?;
    let mut invocation = source_registry_invocation(registry, identity, &digest, operation);
    if matches!(operation, "cancel" | "finish-cancel") {
        invocation = format!(
            "flock -x -- {} {invocation}",
            shell_escape::escape(format!("{registry}/{identity}.activity.lock").into()),
        );
    }
    Ok(format!(
        "{}{invocation} <<'RCH_SOURCE_CLAIM_ROOTS'\n{roots}RCH_SOURCE_CLAIM_ROOTS\n",
        source_registry_setup(registry),
    ))
}

/// Probe whether a started remote execution is gone for good. Every activity
/// under a source grant (the build supervisor and its descendants) inherits
/// the grant's activity-lock descriptor, so while any of it lives the lock is
/// held. Holding that lock ourselves and still finding no completion receipt
/// proves the execution died without one and never will write it. A
/// registry that no longer exists (worker reboot cleared /tmp) proves the
/// same. Prints exactly one of RCH_EXEC_ACTIVE, RCH_EXEC_COMPLETED,
/// RCH_EXEC_LOST.
fn remote_execution_probe_script(
    registry: &str,
    identity: &str,
    receipt: &str,
) -> anyhow::Result<String> {
    validate_source_identity(identity)?;
    let quote = |value: &str| shell_escape::escape(value.into()).into_owned();
    Ok(format!(
        "[ -d {registry} ] || {{ echo RCH_EXEC_LOST; exit 0; }}; \
         flock -n {lock} sh -c 'if [ -e \"$1\" ] || [ -L \"$1\" ]; then echo RCH_EXEC_COMPLETED; \
         else echo RCH_EXEC_LOST; fi' rch-exec-probe {receipt} || echo RCH_EXEC_ACTIVE",
        registry = quote(registry),
        lock = quote(&format!("{registry}/{identity}.activity.lock")),
        receipt = quote(receipt),
    ))
}

/// True only when the probe proves the execution is lost (see
/// [`remote_execution_probe_script`]); any other answer or error keeps the
/// conservative "not complete yet" verdict.
pub(super) async fn remote_execution_lost(
    worker: &WorkerConfig,
    identity: &str,
    receipt: &str,
) -> anyhow::Result<bool> {
    let script = remote_execution_probe_script(REMOTE_SOURCE_CLAIM_REGISTRY, identity, receipt)?;
    let output = run_offload_ssh_command_with_stdin(
        worker,
        "sh -s",
        script.as_bytes(),
        Duration::from_secs(15),
    )
    .await?;
    Ok(output.status.success()
        && String::from_utf8_lossy(&output.stdout)
            .lines()
            .any(|line| line.trim() == "RCH_EXEC_LOST"))
}

/// Reconcile an exact release after completed retrieval. This grants no source
/// read or mutation authority and must never substitute for strict recovery.
pub(super) async fn remote_source_authority_was_released(
    worker: &WorkerConfig,
    roots: &[String],
    identity: &str,
) -> anyhow::Result<bool> {
    let command = source_intent_command(REMOTE_SOURCE_CLAIM_REGISTRY, roots, identity, "released")?;
    let output = run_offload_ssh_command_with_stdin(
        worker,
        "sh -s",
        command.as_bytes(),
        Duration::from_secs(15),
    )
    .await?;
    anyhow::ensure!(
        output.status.success(),
        "cannot reconcile durable source release: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    match output.stdout.as_slice() {
        b"released" => Ok(true),
        b"pending" => Ok(false),
        _ => anyhow::bail!("invalid durable source release response"),
    }
}

/// Begin cancellation of a persisted pre-execution intent, draining normal
/// activity and fencing delayed acquisition. True retains the existing claim
/// for cleanup; false grants no source authority. Execution must never have
/// started. Cleanup must finish before `finish_cancel_remote_source_authority_intent`.
pub(super) async fn cancel_remote_source_authority_intent(
    worker: &WorkerConfig,
    roots: &[String],
    identity: &str,
) -> anyhow::Result<bool> {
    let command = source_intent_command(REMOTE_SOURCE_CLAIM_REGISTRY, roots, identity, "cancel")?;
    let output = run_offload_ssh_command_with_stdin(
        worker,
        "sh -s",
        command.as_bytes(),
        Duration::from_secs(30),
    )
    .await?;
    anyhow::ensure!(
        output.status.success(),
        "cannot cancel durable source intent: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    match output.stdout.as_slice() {
        b"owned" => Ok(true),
        b"unowned" => Ok(false),
        _ => anyhow::bail!("invalid source intent cancellation response"),
    }
}

/// Remove the durable overlap blocker only after cancellation cleanup drains.
pub(super) async fn finish_cancel_remote_source_authority_intent(
    worker: &WorkerConfig,
    roots: &[String],
    identity: &str,
) -> anyhow::Result<()> {
    let command = source_intent_command(
        REMOTE_SOURCE_CLAIM_REGISTRY,
        roots,
        identity,
        "finish-cancel",
    )?;
    let output = run_offload_ssh_command_with_stdin(
        worker,
        "sh -s",
        command.as_bytes(),
        Duration::from_secs(30),
    )
    .await?;
    anyhow::ensure!(
        output.status.success(),
        "cannot finish durable source cancellation: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    Ok(())
}

fn source_authority_lock_transport(
    platform: WorkerPlatform,
    remote_cmd: &str,
) -> (String, Option<String>) {
    let reader = if platform.is_windows() {
        "sh -s".to_owned()
    } else {
        // Preserve POSIX login initialization without putting the closure in
        // its -c argument, and replace the login shell rather than retaining it.
        build_remote_shell_command(platform, "exec sh -s")
    };
    // Parse the entire compound command before executing any stdin consumer.
    // The pipe must remain OPEN afterward: durable source holders and source
    // pairs read their explicit release request from the same pipe.
    // An exec sh -c '<large script>' bootstrap would merely move E2BIG remotely.
    (reader, Some(format!("{{\n{remote_cmd}\n}}\n")))
}

/// Acquire sorted, worker-side locks for every mutable canonical source root.
/// One persistent SSH session owns the whole set, so separate coordinator
/// processes cannot overwrite any member of a Cargo closure while it compiles.
pub(super) async fn acquire_remote_source_authority_lock(
    worker: &WorkerConfig,
    authority_roots: &[String],
    source_pair: Option<&mut RemoteSourceAuthorityLock>,
    identity: &str,
    wait_timeout: Duration,
) -> anyhow::Result<RemoteSourceAuthorityLock> {
    source_authority_lock(
        worker,
        authority_roots,
        source_pair,
        identity,
        "acquire",
        wait_timeout,
    )
    .await
}

/// Reattach a persisted identical source grant; absent or released state never
/// creates ownership, including after a worker restart or an intervening writer.
pub(super) async fn recover_remote_source_authority_lock(
    worker: &WorkerConfig,
    authority_roots: &[String],
    source_pair: Option<&mut RemoteSourceAuthorityLock>,
    identity: &str,
    wait_timeout: Duration,
) -> anyhow::Result<RemoteSourceAuthorityLock> {
    source_authority_lock(
        worker,
        authority_roots,
        source_pair,
        identity,
        "recover",
        wait_timeout,
    )
    .await
}

async fn source_authority_lock(
    worker: &WorkerConfig,
    authority_roots: &[String],
    source_pair: Option<&mut RemoteSourceAuthorityLock>,
    identity: &str,
    operation: &str,
    wait_timeout: Duration,
) -> anyhow::Result<RemoteSourceAuthorityLock> {
    // A validated clean-overlay pair already holds its container exclusively.
    // Its private descendants retain their exact locks; re-locking their parent
    // through another SSH session would deadlock against our own pair holder.
    // Derive this exception from the actual live pair, never a caller flag or
    // an unvalidated recovery-recipe path.
    let (include_ancestors, paired_root) = if let Some(pair) = source_pair {
        pair.ensure_held()?;
        anyhow::ensure!(
            pair.pair_token().is_some(),
            "source pair has no owner token"
        );
        let root = pair
            .pair_root
            .as_deref()
            .ok_or_else(|| anyhow::anyhow!("source pair has no bound root"))?;
        (false, Some(root.to_owned()))
    } else {
        (true, None)
    };
    let lock_roots = authority_roots
        .iter()
        .filter(|root| paired_root.as_ref() != Some(*root))
        .cloned()
        .collect::<Vec<_>>();
    let locks = source_authority_lock_plan(&lock_roots, include_ancestors)?;
    let ready_marker = format!("RCH_SOURCE_AUTHORITY_READY:{}", uuid::Uuid::new_v4());
    let remote_cmd = build_durable_source_authority_lock_cmd(
        REMOTE_SOURCE_AUTHORITY_LOCK_DIR,
        REMOTE_SOURCE_CLAIM_REGISTRY,
        &locks,
        authority_roots,
        identity,
        operation,
        &ready_marker,
    )?;
    let mut guard =
        spawn_source_authority_lock(worker, &remote_cmd, &ready_marker, wait_timeout).await?;
    guard.release_request = Some(format!("RCH_SOURCE_AUTHORITY_RELEASE:{identity}"));
    Ok(guard)
}

/// A reusable source path must remain unavailable after holder loss: the old
/// upload/build can outlive its control SSH connection. Only explicit release
/// after execution, retrieval and source retirement permits the next owner.
pub(super) async fn acquire_clean_overlay_source_pair(
    worker: &WorkerConfig,
    source_root: &str,
    token: &str,
    wait_timeout: Duration,
) -> anyhow::Result<RemoteSourceAuthorityLock> {
    validate_source_identity(token)?;
    let lock_path = source_authority_lock_paths(&[source_root.to_string()])
        .into_iter()
        .next()
        .expect("one source root produces one lock");
    let ready = format!("RCH_SOURCE_PAIR_READY:{token}");
    let release = format!("RCH_SOURCE_PAIR_RELEASE:{token}");
    let command =
        clean_overlay_source_pair_lock_command(&lock_path, source_root, token, &ready, &release);
    let mut guard = spawn_source_authority_lock(worker, &command, &ready, wait_timeout).await?;
    guard.release_request = Some(release);
    guard.pair_root = Some(source_root.to_owned());
    Ok(guard)
}
/// Reattach only the recorded owner; never create or steal a source pair.
pub(super) async fn recover_clean_overlay_source_pair(
    worker: &WorkerConfig,
    source_root: &str,
    token: &str,
    wait_timeout: Duration,
) -> anyhow::Result<RemoteSourceAuthorityLock> {
    validate_source_identity(token)?;
    let lock_path = source_authority_lock_paths(&[source_root.to_owned()])
        .pop()
        .expect("one source root");
    let quote = |value: &str| shell_escape::escape(value.into()).into_owned();
    let ready = format!("RCH_SOURCE_PAIR_READY:{token}");
    let release = format!("RCH_SOURCE_PAIR_RELEASE:{token}");
    let owner = format!("{lock_path}.owner");
    let receipt = format!(
        "{lock_path}.released-{}",
        blake3::hash(token.as_bytes()).to_hex()
    );
    let script = format!(
        "set -eu; owner={owner}; root={root}; token={token}; \
         [ ! -L \"$owner\" ] && [ \"$(cat \"$owner\")\" = \"$token\" ]; \
         printf '%s\\n' {ready}; IFS= read -r request; \
         [ \"$request\" = {release} ]; [ \"$(cat \"$owner\")\" = \"$token\" ]; \
         [ ! -e \"$root\" ] && [ ! -L \"$root\" ]; \
         printf '%s\\n' {token} > {receipt}; sync -f {receipt}; \
         printf 'released\\n' > \"$owner\"; sync -f \"$owner\"; printf '%s\\n' {release}",
        owner = quote(&owner),
        root = quote(source_root),
        token = quote(token),
        ready = quote(&ready),
        release = quote(&release),
        receipt = quote(&receipt),
    );
    let command = format!(
        "exec flock -x {} sh -c {}",
        quote(&lock_path),
        quote(&script)
    );
    let mut guard = spawn_source_authority_lock(worker, &command, &ready, wait_timeout).await?;
    guard.release_request = Some(release);
    guard.pair_root = Some(source_root.to_owned());
    Ok(guard)
}

/// Once the source intent has been cancelled, acquire the old pair only when
/// it is still owned by that exact token. A missing/different owner yields no
/// source authority; the cancellation tombstone fences a delayed acquisition.
pub(super) async fn cancel_clean_overlay_source_pair_intent(
    worker: &WorkerConfig,
    source_root: &str,
    token: &str,
    wait_timeout: Duration,
) -> anyhow::Result<Option<RemoteSourceAuthorityLock>> {
    validate_source_identity(token)?;
    let quote = |value: &str| shell_escape::escape(value.into()).into_owned();
    let lock = source_authority_lock_path(source_root);
    let script = format!(
        "set -eu; registry={registry}; token={token}; \
         set -- \"$registry/$token.\"*.claim; active=$1; owned=0; \
         if [ \"$#\" -eq 1 ] && [ ! -L \"$active\" ] && [ -f \"$active\" ]; then \
         cancelling=${{active%.claim}}.cancelling; \
         [ ! -L \"$cancelling\" ] && [ -f \"$cancelling\" ]; \
         cmp -s \"$active\" \"$cancelling\"; owned=1; else \
         [ ! -e \"$active\" ] && [ ! -L \"$active\" ]; \
         set -- \"$registry/cancelled/$token.\"*.claim; \
         [ \"$#\" -eq 1 ] && [ ! -L \"$1\" ] && [ -f \"$1\" ]; fi; \
         owner={owner}; [ ! -L \"$owner\" ]; \
         if [ -f \"$owner\" ] && [ \"$(cat \"$owner\")\" = \"$token\" ]; \
         then if [ \"$owned\" -eq 1 ]; then printf owned; else \
         printf '%s\\n' \"$token\" > {receipt}; sync -f {receipt}; \
         printf 'released\\n' > \"$owner\"; sync -f \"$owner\"; printf unowned; fi; \
         else printf unowned; fi",
        registry = quote(REMOTE_SOURCE_CLAIM_REGISTRY),
        token = quote(token),
        owner = quote(&format!("{lock}.owner")),
        receipt = quote(&format!(
            "{lock}.released-{}",
            blake3::hash(token.as_bytes()).to_hex()
        )),
    );
    let command = format!("flock -x -- {} sh -c {}", quote(&lock), quote(&script));
    let output =
        run_offload_ssh_command_with_stdin(worker, "sh -s", command.as_bytes(), wait_timeout)
            .await?;
    anyhow::ensure!(
        output.status.success(),
        "cannot reconcile cancelled source pair"
    );
    match output.stdout.as_slice() {
        b"owned" => Ok(Some(
            recover_clean_overlay_source_pair(worker, source_root, token, wait_timeout).await?,
        )),
        b"unowned" => Ok(None),
        _ => anyhow::bail!("invalid cancelled source-pair response"),
    }
}

/// Reconcile only an exact-token release receipt while holding the pair lock.
/// Consumed by retirement retry after a lost release acknowledgement.
pub(super) async fn clean_overlay_source_pair_was_released(
    worker: &WorkerConfig,
    source_root: &str,
    token: &str,
) -> anyhow::Result<bool> {
    let lock_path = source_authority_lock_paths(&[source_root.to_owned()])
        .pop()
        .expect("one source root");
    let quote = |value: &str| shell_escape::escape(value.into()).into_owned();
    let owner = format!("{lock_path}.owner");
    let receipt = format!(
        "{lock_path}.released-{}",
        blake3::hash(token.as_bytes()).to_hex()
    );
    let script = format!(
        "set -eu; [ ! -L {receipt} ]; \
         if [ ! -f {receipt} ]; then printf pending; exit 0; fi; \
         [ \"$(cat {receipt})\" = {token} ]; [ ! -L {owner} ]; \
         if [ \"$(cat {owner})\" = {token} ]; then \
         [ ! -e {root} ] && [ ! -L {root} ]; \
         printf 'released\\n' > {owner}; sync -f {owner}; fi; printf released",
        receipt = quote(&receipt),
        token = quote(token),
        owner = quote(&owner),
        root = quote(source_root),
    );
    let command = format!("flock -x {} sh -c {}", quote(&lock_path), quote(&script));
    let output = run_offload_ssh_command_with_stdin(
        worker,
        "sh -s",
        command.as_bytes(),
        Duration::from_secs(15),
    )
    .await?;
    anyhow::ensure!(
        output.status.success(),
        "cannot verify source-pair release receipt"
    );
    match output.stdout.as_slice() {
        b"released" => Ok(true),
        b"pending" => Ok(false),
        _ => anyhow::bail!("invalid source-pair release response"),
    }
}

fn clean_overlay_source_pair_lock_command(
    lock_path: &str,
    source_root: &str,
    token: &str,
    ready: &str,
    release: &str,
) -> String {
    let quote = |value: &str| shell_escape::escape(value.into()).into_owned();
    let owner = format!("{lock_path}.owner");
    let receipt = format!(
        "{lock_path}.released-{}",
        blake3::hash(token.as_bytes()).to_hex()
    );
    let creation = format!(
        "set -eu; owner={owner}; root={root}; token={token}; \
         registry={registry}; \
         for cancelled in \"$registry/cancelled/$token.\"*.claim \"$registry/$token.\"*.cancelling; do \
         if [ -e \"$cancelled\" ] || [ -L \"$cancelled\" ]; then \
         echo 'RCH: source pair intent was cancelled' >&2; exit 1; fi; done; \
         if [ -L \"$owner\" ] || {{ [ -e \"$owner\" ] && [ \"$(cat \"$owner\")\" != released ]; }}; then \
         echo 'RCH: source pair has an unfinished owner; inspect the prior job or use RCH_DISABLE_TARGET_REUSE=1' >&2; exit 1; fi; \
         if [ -e \"$root\" ] || [ -L \"$root\" ]; then \
         echo 'RCH: source pair has unretired source; refusing reuse' >&2; exit 1; fi; \
         printf '%s\\n' \"$token\" > \"$owner\"; sync -f \"$owner\"; \
         sync -f \"$(dirname \"$owner\")\"",
        owner = quote(&owner),
        root = quote(source_root),
        token = quote(token),
        registry = quote(REMOTE_SOURCE_CLAIM_REGISTRY),
    );
    let script = format!(
        "{setup}flock -x -- {metadata_lock} sh -c {creation}; \
         owner={owner}; root={root}; token={token}; \
         printf '%s\\n' {ready}; IFS= read -r request; \
         [ \"$request\" = {release} ]; [ \"$(cat \"$owner\")\" = \"$token\" ]; \
         [ ! -e \"$root\" ] && [ ! -L \"$root\" ]; \
         printf '%s\\n' {token} > {receipt}; sync -f {receipt}; \
         printf 'released\\n' > \"$owner\"; sync -f \"$owner\"; printf '%s\\n' {release}",
        owner = quote(&owner),
        root = quote(source_root),
        token = quote(token),
        ready = quote(ready),
        release = quote(release),
        receipt = quote(&receipt),
        setup = source_registry_setup(REMOTE_SOURCE_CLAIM_REGISTRY),
        metadata_lock = quote(&format!("{REMOTE_SOURCE_CLAIM_REGISTRY}/metadata.lock")),
        creation = quote(&creation),
    );
    format!(
        "mkdir -p {} && exec flock -x {} sh -c {}",
        quote(REMOTE_SOURCE_AUTHORITY_LOCK_DIR),
        quote(lock_path),
        quote(&script),
    )
}

async fn spawn_source_authority_lock(
    worker: &WorkerConfig,
    remote_cmd: &str,
    ready_marker: &str,
    wait_timeout: Duration,
) -> anyhow::Result<RemoteSourceAuthorityLock> {
    use anyhow::Context as _;
    let identity_file = shellexpand::tilde(&worker.identity_file);
    let destination = format!("{}@{}", worker.user, worker.host);
    let mut cmd = Command::new("ssh");
    cmd.arg("-o").arg("BatchMode=yes");
    cmd.arg("-o").arg("StrictHostKeyChecking=accept-new");
    cmd.arg("-o").arg("ConnectTimeout=10");
    cmd.arg("-i").arg(identity_file.as_ref());
    if let Some(opts) = rch_common::ssh_utils::identities_only_args(identity_file.as_ref()) {
        cmd.args(opts);
    }
    cmd.arg(&destination);
    let (remote_arg, stdin_bootstrap) =
        source_authority_lock_transport(WorkerPlatform::from_worker(worker), remote_cmd);
    cmd.arg(remote_arg);
    cmd.stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);

    let child = cmd
        .spawn()
        .with_context(|| format!("failed to start source-authority lock on {destination}"))?;
    finish_source_authority_lock_acquisition(
        child,
        worker.id.clone(),
        ready_marker,
        stdin_bootstrap.as_deref(),
        wait_timeout,
    )
    .await
}

async fn finish_source_authority_lock_acquisition(
    mut child: tokio::process::Child,
    worker_id: WorkerId,
    ready_marker: &str,
    stdin_bootstrap: Option<&str>,
    wait_timeout: Duration,
) -> anyhow::Result<RemoteSourceAuthorityLock> {
    use tokio::io::{AsyncBufReadExt as _, AsyncReadExt as _, AsyncWriteExt as _};

    let mut stdin = child
        .stdin
        .take()
        .ok_or_else(|| anyhow::anyhow!("source-authority lock stdin was not piped"))?;
    let stdout = child
        .stdout
        .take()
        .ok_or_else(|| anyhow::anyhow!("source-authority lock stdout was not piped"))?;
    let mut stdout = tokio::io::BufReader::new(stdout);
    let stderr = child
        .stderr
        .take()
        .ok_or_else(|| anyhow::anyhow!("source-authority lock stderr was not piped"))?;
    let stderr_drain = tokio::spawn(crate::transfer::read_bounded_output_stream(
        stderr,
        MAX_SOURCE_LOCK_OUTPUT_BYTES,
    ));
    // Own cleanup before any fallible write/read: timeout, cancellation and
    // invalid readiness must not detach the drain or leave a lock holder.
    let mut guard = RemoteSourceAuthorityLock {
        worker_id,
        child: Some(child),
        stdin: None,
        stdout_drain: None,
        stderr_drain: Some(stderr_drain),
        release_request: None,
        pair_root: None,
    };

    let mut observed = String::new();
    let acquisition = async {
        let write_bootstrap = async {
            if let Some(bootstrap) = stdin_bootstrap {
                stdin.write_all(bootstrap.as_bytes()).await?;
                stdin.flush().await?;
            }
            Ok::<(), std::io::Error>(())
        };
        let read_ready = async {
            // Bound the read itself, not just the buffer after read_line has
            // waited for an arbitrarily large or never-terminated frame.
            let read = (&mut stdout)
                .take((MAX_SOURCE_LOCK_READY_BYTES + 1) as u64)
                .read_line(&mut observed)
                .await?;
            if read > MAX_SOURCE_LOCK_READY_BYTES {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "source-authority ready frame exceeded its byte limit",
                ));
            }
            Ok(read)
        };
        tokio::try_join!(write_bootstrap, read_ready)
    };
    let failure = match timeout(wait_timeout, acquisition).await {
        Ok(Ok(((), 0))) => Some(format!(
            "source-authority lock on {} exited before acquisition",
            guard.worker_id
        )),
        Ok(Ok(((), _)))
            if observed
                .strip_suffix('\n')
                .map(|line| line.strip_suffix('\r').unwrap_or(line))
                == Some(ready_marker) =>
        {
            None
        }
        Ok(Ok(((), _))) => Some(format!(
            "source-authority lock on {} emitted an invalid ready marker: {:?}",
            guard.worker_id,
            observed.trim_end()
        )),
        Ok(Err(err)) => Some(format!(
            "failed writing source-authority lock bootstrap or reading readiness on {}: {err}",
            guard.worker_id
        )),
        Err(_) => Some(format!(
            "timed out waiting {:?} for source-authority locks on {}",
            wait_timeout, guard.worker_id
        )),
    };
    if let Some(failure) = failure {
        drop(stdin);
        if let Some(child) = guard.child.as_mut() {
            let _ = child.start_kill();
            let _ = timeout(Duration::from_secs(1), child.wait()).await;
        }
        let stderr = if let Some(task) = guard.stderr_drain.as_mut() {
            match timeout(Duration::from_secs(1), task).await {
                Ok(Ok(Ok(bytes))) => String::from_utf8_lossy(&bytes).trim().to_string(),
                Ok(Ok(Err(err))) => format!("stderr read failed: {err}"),
                Ok(Err(err)) => format!("stderr task failed: {err}"),
                Err(_) => "stderr drain did not finish before cleanup deadline".into(),
            }
        } else {
            String::new()
        };
        anyhow::bail!("{failure}; stderr={stderr}");
    }

    guard.stdin = Some(stdin);
    guard.stdout_drain = Some(tokio::spawn(crate::transfer::read_bounded_output_stream(
        stdout,
        MAX_SOURCE_LOCK_OUTPUT_BYTES,
    )));
    Ok(guard)
}

pub(super) fn should_skip_remote_preflight(worker: &WorkerConfig) -> bool {
    mock::is_mock_enabled() || mock::is_mock_worker(worker)
}

pub(super) async fn run_offload_ssh_command(
    worker: &WorkerConfig,
    remote_cmd: &str,
    timeout_duration: Duration,
) -> anyhow::Result<Output> {
    let (remote_arg, stdin_payload) = offload_remote_command_transport(worker, remote_cmd);
    run_offload_ssh_command_with_optional_stdin(worker, remote_arg, stdin_payload, timeout_duration)
        .await
}

/// Windows OpenSSH passes its remote command through an additional shell
/// boundary, where the nested single quotes produced by `sh -lc` can be
/// reparsed and truncated. Feed control-plane scripts to `sh -s` instead;
/// POSIX workers retain the historical argv transport.
pub(super) fn offload_remote_command_transport<'a>(
    worker: &WorkerConfig,
    remote_cmd: &'a str,
) -> (&'a str, Option<&'a [u8]>) {
    if crate::transfer::WorkerPlatform::from_worker(worker).is_windows() {
        ("sh -s", Some(remote_cmd.as_bytes()))
    } else {
        (remote_cmd, None)
    }
}

/// Execute a hardened control-plane SSH command while streaming a bounded
/// caller-supplied payload to its stdin. Source-content verification uses this
/// instead of placing thousands of file identities in argv, where shell/OS
/// limits would make the proof denominator depend on repository size.
pub(super) async fn run_offload_ssh_command_with_stdin(
    worker: &WorkerConfig,
    remote_cmd: &str,
    stdin_payload: &[u8],
    timeout_duration: Duration,
) -> anyhow::Result<Output> {
    run_offload_ssh_command_with_optional_stdin(
        worker,
        remote_cmd,
        Some(stdin_payload),
        timeout_duration,
    )
    .await
}

async fn run_offload_ssh_command_with_optional_stdin(
    worker: &WorkerConfig,
    remote_cmd: &str,
    stdin_payload: Option<&[u8]>,
    timeout_duration: Duration,
) -> anyhow::Result<Output> {
    let identity_file = shellexpand::tilde(&worker.identity_file);
    let destination = format!("{}@{}", worker.user, worker.host);

    let mut cmd = Command::new("ssh");
    cmd.arg("-o").arg("BatchMode=yes");
    cmd.arg("-o").arg("StrictHostKeyChecking=accept-new");
    // The per-file verifier after the rsync barrier also requires clean stderr.
    // Change only client INFO logging; preserve remote stderr and auth failures.
    crate::transfer::source_content_barrier::configure_ssh_command(cmd.as_std_mut());
    cmd.arg("-o").arg(format!(
        "ConnectTimeout={}",
        timeout_duration.as_secs().max(1)
    ));
    cmd.arg("-i").arg(identity_file.as_ref());
    if let Some(opts) = rch_common::ssh_utils::identities_only_args(identity_file.as_ref()) {
        cmd.args(opts);
    }
    cmd.arg(&destination);
    cmd.arg(build_remote_shell_command(
        WorkerPlatform::from_worker(worker),
        remote_cmd,
    ));
    if stdin_payload.is_some() {
        cmd.stdin(Stdio::piped());
    } else {
        cmd.stdin(Stdio::null());
    }
    cmd.stdout(Stdio::piped()).stderr(Stdio::piped());

    // Spawn manually instead of `cmd.output()` so the local SSH process is
    // killed if our outer timeout fires. `tokio::time::timeout` only drops
    // the future; without `kill_on_drop`, the spawned ssh process keeps
    // running, holding the network socket open until SSH's own keepalive
    // gives up. For a busy hook this leaks fds and ssh processes — exactly
    // the kind of slow accumulation that turns into a daemon-restart bug
    // weeks later.
    cmd.kill_on_drop(true);

    use anyhow::Context as _;
    use tokio::io::AsyncWriteExt as _;

    let mut child = cmd
        .spawn()
        .with_context(|| format!("Failed to spawn ssh to {}", destination))?;

    // Drain stdout/stderr concurrently with the wait so that even verbose
    // remote output never deadlocks the child on a full pipe buffer.
    let mut stdin_pipe = child.stdin.take();
    let mut stdout_pipe = child.stdout.take();
    let mut stderr_pipe = child.stderr.take();
    let stdin_payload = stdin_payload.map(<[u8]>::to_vec);
    let collect = async {
        let stdin_fut = async {
            if let (Some(mut pipe), Some(payload)) = (stdin_pipe.take(), stdin_payload.as_deref()) {
                pipe.write_all(payload).await?;
                pipe.shutdown().await?;
                drop(pipe);
            }
            Ok::<_, std::io::Error>(())
        };
        let stdout_fut = async {
            match stdout_pipe.take() {
                Some(pipe) => {
                    crate::transfer::read_bounded_output_stream(pipe, MAX_OFFLOAD_SSH_OUTPUT_BYTES)
                        .await
                }
                None => Ok(Vec::new()),
            }
        };
        let stderr_fut = async {
            match stderr_pipe.take() {
                Some(pipe) => {
                    crate::transfer::read_bounded_output_stream(pipe, MAX_OFFLOAD_SSH_OUTPUT_BYTES)
                        .await
                }
                None => Ok(Vec::new()),
            }
        };
        let ((), stdout_bytes, stderr_bytes) = tokio::try_join!(stdin_fut, stdout_fut, stderr_fut)?;
        let status = child.wait().await?;
        Ok::<_, std::io::Error>(Output {
            status,
            stdout: stdout_bytes,
            stderr: stderr_bytes,
        })
    };

    match timeout(timeout_duration, collect).await {
        Ok(result) => result.context("Failed to collect ssh output"),
        Err(_) => {
            // collect future is dropped here; with kill_on_drop=true the
            // local ssh process is SIGKILLed when `child` (still owned by
            // the dropped future) is dropped.
            anyhow::bail!("SSH command timed out after {:?}", timeout_duration);
        }
    }
}

fn build_remote_shell_command(platform: WorkerPlatform, remote_cmd: &str) -> String {
    // The Windows control-plane script is carried on stdin. Its fixed reader
    // needs no quoting or login initialization; that extra startup can exhaust
    // the dependency probe budget before the file checks run.
    if platform.is_windows() && remote_cmd == "sh -s" {
        return remote_cmd.to_string();
    }
    format!("sh -lc {}", shell_escape::escape(remote_cmd.into()))
}

/// Isolated Git overlays and source-content receipt trees live beneath the
/// configured worker staging base. Keep the controller policy for ordinary
/// mirrors and validate every isolated destination before any remote topology
/// command can create or repair a path.
pub(super) fn remote_preflight_topology_policy(
    controller_policy: &PathTopologyPolicy,
    clean_overlay: bool,
    source_content_receipt: bool,
    remote_base: &str,
    dispatch_closure_roots: &[PathBuf],
) -> anyhow::Result<PathTopologyPolicy> {
    if !clean_overlay && !source_content_receipt {
        return Ok(controller_policy.clone());
    }

    let remote_base = rch_common::types::validate_remote_base(remote_base)
        .map_err(|error| anyhow::anyhow!("invalid isolated staging base: {error}"))?;
    if remote_base.chars().any(char::is_control) || remote_base.contains('\\') {
        anyhow::bail!("isolated staging base contains an invalid path character");
    }
    let staging_root = PathBuf::from(remote_base);
    if dispatch_closure_roots.is_empty() {
        anyhow::bail!("isolated staging preflight requires a planned source root");
    }
    for root in dispatch_closure_roots {
        let literal = root
            .to_str()
            .ok_or_else(|| anyhow::anyhow!("isolated source destination is not a UTF-8 path"))?;
        if literal.chars().any(char::is_control)
            || literal.contains('\\')
            || literal.split('/').any(|part| part == "." || part == "..")
        {
            anyhow::bail!("invalid isolated source destination: {}", root.display());
        }
        let relative = root.strip_prefix(&staging_root).ok().filter(|relative| {
            !relative.as_os_str().is_empty()
                && relative
                    .components()
                    .all(|part| matches!(part, std::path::Component::Normal(_)))
        });
        if relative.is_none() {
            anyhow::bail!(
                "isolated source destination {} is not a strict descendant of staging base {}",
                root.display(),
                staging_root.display()
            );
        }
    }
    // No worker-global alias is required for an invocation-owned source tree.
    Ok(PathTopologyPolicy::new(staging_root.clone(), staging_root))
}

fn build_worker_projects_topology_probe_cmd(topology_policy: &PathTopologyPolicy) -> String {
    format!(
        "set -eu; \
         if {{ [ ! -e {canonical} ] && [ ! -L {canonical} ]; }} \
         || {{ [ ! -e {alias} ] && [ ! -L {alias} ]; }}; then \
           printf 'RCH_TOPOLOGY_INITIALIZATION_REQUIRED\\n'; \
         else printf 'RCH_TOPOLOGY_PATHS_PRESENT\\n'; fi",
        canonical = shell_escape::escape(topology_policy.canonical_root().to_string_lossy()),
        alias = shell_escape::escape(topology_policy.alias_root().to_string_lossy()),
    )
}

/// Probe without changing paths so initialization can be included in the exact
/// durable grant before any topology or source mutation. The later preflight
/// refuses creation if this observation becomes stale in the other direction.
pub(super) async fn worker_projects_topology_requires_initialization(
    worker: &WorkerConfig,
    topology_policy: &PathTopologyPolicy,
) -> anyhow::Result<bool> {
    let command = build_worker_projects_topology_probe_cmd(topology_policy);
    let output = run_offload_ssh_command_with_stdin(
        worker,
        "sh -s",
        command.as_bytes(),
        Duration::from_secs(20),
    )
    .await?;
    anyhow::ensure!(
        output.status.success(),
        "remote topology initialization probe failed on {} (status {:?}): {}",
        worker.id,
        output.status.code(),
        String::from_utf8_lossy(&output.stderr).trim(),
    );
    match output.stdout.as_slice() {
        b"RCH_TOPOLOGY_INITIALIZATION_REQUIRED\n" => Ok(true),
        b"RCH_TOPOLOGY_PATHS_PRESENT\n" => Ok(false),
        other => anyhow::bail!(
            "unrecognized topology initialization probe response from {}: {:?}",
            worker.id,
            String::from_utf8_lossy(other),
        ),
    }
}

fn build_worker_projects_topology_cmd(
    topology_policy: &PathTopologyPolicy,
    allow_initialization: bool,
) -> String {
    let canonical_display = topology_policy.canonical_root().display().to_string();
    let alias_display = topology_policy.alias_root().display().to_string();
    let canonical_slash_display = format!("{}/", canonical_display.trim_end_matches('/'));

    format!(
        "set -e; \
         if [ ! -e {canonical} ] && [ ! -L {canonical} ]; then \
           if [ {allow_initialization} != true ]; then printf 'RCH_TOPOLOGY_ERR_INITIALIZATION_REQUIRED:path=%s\\n' {canonical} >&2; exit 48; fi; \
           mkdir_stderr=$(mkdir -p -- {canonical} 2>&1) || {{ printf 'RCH_TOPOLOGY_ERR_CANONICAL_CREATE_FAILED:path=%s:%s\\n' {canonical} \"$mkdir_stderr\" >&2; exit 45; }}; fi; \
         if [ ! -d {canonical} ]; then printf 'RCH_TOPOLOGY_ERR_CANONICAL_NOT_DIRECTORY:path=%s\\n' {canonical} >&2; exit 41; fi; \
         canonical_real=$(readlink -f -- {canonical} 2>/dev/null || printf '%s' {canonical}); \
         ensure_alias_symlink() {{ \
         if [ -L {alias} ]; then \
           target=$(readlink -- {alias} 2>/dev/null || true); \
           target_real=$(readlink -f -- {alias} 2>/dev/null || true); \
           if [ \"$target\" != {canonical} ] && [ \"$target\" != {canonical_slash} ] && [ \"$target_real\" != \"$canonical_real\" ]; then \
             printf 'RCH_TOPOLOGY_ERR_ALIAS_TARGET_CONFLICT:path=%s:target=%s:expected=%s\\n' {alias} \"$target\" {canonical} >&2; return 43; \
           fi; \
         elif [ -e {alias} ]; then \
           alias_real=$(readlink -f -- {alias} 2>/dev/null || true); \
           if [ -n \"$alias_real\" ] && [ \"$alias_real\" = \"$canonical_real\" ]; then return 0; fi; \
           printf 'RCH_TOPOLOGY_ERR_ALIAS_NOT_SYMLINK:path=%s\\n' {alias} >&2; return 42; \
         else \
           if [ {allow_initialization} != true ]; then printf 'RCH_TOPOLOGY_ERR_INITIALIZATION_REQUIRED:path=%s\\n' {alias} >&2; return 48; fi; \
           create_stderr=$(ln -s -- {canonical} {alias} 2>&1) && return 0; \
           if [ -L {alias} ]; then ensure_alias_symlink; return $?; fi; \
           if [ -e {alias} ]; then \
             alias_real=$(readlink -f -- {alias} 2>/dev/null || true); \
             if [ -n \"$alias_real\" ] && [ \"$alias_real\" = \"$canonical_real\" ]; then return 0; fi; \
             printf 'RCH_TOPOLOGY_ERR_ALIAS_NOT_SYMLINK:path=%s\\n' {alias} >&2; return 42; fi; \
           printf 'RCH_TOPOLOGY_ERR_ALIAS_CREATE_FAILED:path=%s:target=%s:%s\\n' {alias} {canonical} \"$create_stderr\" >&2; return 44; \
         fi; \
         }}; \
         ensure_alias_symlink; \
         echo RCH_TOPOLOGY_OK",
        canonical = shell_escape::escape(canonical_display.into()),
        canonical_slash = shell_escape::escape(canonical_slash_display.into()),
        alias = shell_escape::escape(alias_display.into()),
        allow_initialization = allow_initialization,
    )
}

/// bd-8iwkm: build the bounded ownership-drift detect+repair command for the
/// canonical mirror tree. Counts root-owned entries (the rsync exit-23 class),
/// chowns them to the SSH user via passwordless sudo, and re-counts to prove
/// the repair. Never deletes; touches only root-owned entries; the alias root
/// is intentionally not scanned separately because it resolves into (or is
/// policy-conflicting with) the canonical root, which this sweep already
/// covers. Exit codes: 0 = ok/repaired/check-unavailable (fail-open), 46 =
/// repair unavailable (sudo missing/refused), 47 = partial repair.
fn build_worker_ownership_repair_cmd(roots: &[PathBuf], ssh_user: &str) -> String {
    let quoted_user = shell_escape::escape(ssh_user.into());
    let quoted_roots = roots
        .iter()
        .map(|root| shell_escape::escape(root.to_string_lossy()))
        .collect::<Vec<_>>()
        .join(" ");
    format!(
        "set -e; u={user}; \
         detect_root() {{ \
           if ! b=$(sudo -n find \"$1\" -xdev -user root -print 2>/dev/null | wc -l); then \
             printf 'RCH_OWNERSHIP_CHECK_UNAVAILABLE\\n' >&2; exit 0; \
           fi; \
           echo $((b + 0)); \
         }}; \
         total=0; \
         for r in {roots}; do \
           [ -d \"$r\" ] || continue; \
           total=$((total + $(detect_root \"$r\"))); \
         done; \
         if [ \"$total\" -eq 0 ]; then echo RCH_OWNERSHIP_OK; exit 0; fi; \
         repair_ok=1; \
         for r in {roots}; do \
           [ -d \"$r\" ] || continue; \
           if ! sudo -n find \"$r\" -xdev -user root -exec chown -h \"$u\" {{}} + 2>/dev/null; then \
             repair_ok=0; \
           fi; \
         done; \
         if [ \"$repair_ok\" -eq 0 ]; then \
           printf 'RCH_OWNERSHIP_REPAIR_UNAVAILABLE:detected=%s\\n' \"$total\" >&2; exit 46; \
         fi; \
         remaining=0; \
         for r in {roots}; do \
           [ -d \"$r\" ] || continue; \
           remaining=$((remaining + $(detect_root \"$r\"))); \
         done; \
         if [ \"$remaining\" -eq 0 ]; then printf 'RCH_OWNERSHIP_REPAIRED:count=%s\\n' \"$total\"; exit 0; fi; \
         printf 'RCH_OWNERSHIP_PARTIAL:remaining=%s\\n' \"$remaining\" >&2; exit 47",
        user = quoted_user,
        roots = quoted_roots,
    )
}

/// bd-kugfc: detection-only ownership probe command for the canonical
/// mirror tree. Counts root-owned entries and mutates nothing — the
/// doctor must stay read-only. Contract mirrors the repair command's
/// sentinels where meaningful: stdout `RCH_OWNERSHIP_OK` or
/// `RCH_OWNERSHIP_DRIFT:count=N` (exit 0), stderr
/// `RCH_OWNERSHIP_CHECK_UNAVAILABLE` when passwordless sudo is
/// unavailable (also exit 0 — same fail-open posture as dispatch).
fn build_worker_ownership_detect_cmd(canonical_root: &Path) -> String {
    let root = shell_escape::escape(canonical_root.display().to_string().into());
    format!(
        "set -e; r={root}; \
         if ! b=$(sudo -n find \"$r\" -xdev -user root -print 2>/dev/null | wc -l); then \
           printf 'RCH_OWNERSHIP_CHECK_UNAVAILABLE\\n' >&2; exit 0; \
         fi; \
         b=$((b + 0)); \
         if [ \"$b\" -eq 0 ]; then echo RCH_OWNERSHIP_OK; \
         else printf 'RCH_OWNERSHIP_DRIFT:count=%s\\n' \"$b\"; fi",
        root = root,
    )
}

/// bd-kugfc: outcome of one worker's detection-only mirror-ownership
/// probe.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum MirrorOwnershipProbe {
    /// Probe intentionally not run (mock mode or Windows worker —
    /// neither has the Unix canonical/alias mirror-tree semantics).
    Skipped,
    /// No root-owned entries under the canonical mirror tree.
    Healthy,
    /// Drift detected: N root-owned entries will make rsync-as-ssh-user
    /// fail exit 23 until repaired.
    Drift { count: u64 },
    /// The worker cannot run the count (passwordless sudo unavailable);
    /// dispatch-time repair fails open silently in this state too.
    CheckUnavailable,
    /// SSH transport failure, timeout, or unrecognized output; drift
    /// state on this worker is unknown.
    Unprobeable(String),
}

/// Pure classifier for the detect-command output so the parsing
/// contract stays unit-testable without an SSH fleet.
fn parse_ownership_detect_output(
    status_success: bool,
    stdout: &str,
    stderr: &str,
) -> MirrorOwnershipProbe {
    if !status_success {
        // `set -e` makes any non-zero exit an unexpected shell failure
        // (the sentinel paths all exit 0 by construction).
        return MirrorOwnershipProbe::Unprobeable(format!(
            "probe exited non-zero: stderr='{}'",
            stderr.trim()
        ));
    }
    if stderr.contains("RCH_OWNERSHIP_CHECK_UNAVAILABLE") {
        return MirrorOwnershipProbe::CheckUnavailable;
    }
    if let Some(count) = stdout
        .trim()
        .strip_prefix("RCH_OWNERSHIP_DRIFT:count=")
        .and_then(|value| value.parse::<u64>().ok())
    {
        return MirrorOwnershipProbe::Drift { count };
    }
    if stdout.contains("RCH_OWNERSHIP_OK") {
        return MirrorOwnershipProbe::Healthy;
    }
    MirrorOwnershipProbe::Unprobeable(format!(
        "unrecognized probe output: stdout='{}' stderr='{}'",
        stdout.trim(),
        stderr.trim()
    ))
}

/// bd-kugfc: run the detection-only ownership probe against one worker.
/// Read-only by contract — it never chowns, deletes, or otherwise
/// mutates the worker. Bounded to 8s so the reliability doctor's outer
/// per-probe ceiling (10s) stays authoritative across the fan-out.
pub(crate) async fn probe_worker_mirror_ownership(
    worker: &WorkerConfig,
    canonical_root: &Path,
) -> MirrorOwnershipProbe {
    if should_skip_remote_preflight(worker)
        || crate::transfer::WorkerPlatform::from_worker(worker).is_windows()
    {
        return MirrorOwnershipProbe::Skipped;
    }
    let cmd = build_worker_ownership_detect_cmd(canonical_root);
    match run_offload_ssh_command(worker, &cmd, Duration::from_secs(8)).await {
        Ok(output) => parse_ownership_detect_output(
            output.status.success(),
            &String::from_utf8_lossy(&output.stdout),
            &String::from_utf8_lossy(&output.stderr),
        ),
        Err(err) => MirrorOwnershipProbe::Unprobeable(err.to_string()),
    }
}

pub(super) async fn ensure_worker_projects_topology(
    worker: &WorkerConfig,
    reporter: &HookReporter,
    topology_policy: &PathTopologyPolicy,
    dispatch_closure_roots: &[PathBuf],
    source_identity: Option<&str>,
    allow_initialization: bool,
) -> anyhow::Result<()> {
    if should_skip_remote_preflight(worker) {
        reporter.verbose("[RCH] topology preflight skipped in mock mode");
        return Ok(());
    }

    if crate::transfer::WorkerPlatform::from_worker(worker).is_windows() {
        // Windows workers have no Unix canonical/alias projects topology — they
        // build under `C:/rch` via tar-over-ssh — so the `/dp`→canonical symlink
        // enforcement does not apply and would fail (no POSIX symlink there).
        reporter.verbose("[RCH] topology preflight skipped for Windows worker");
        return Ok(());
    }

    let canonical_display = topology_policy.canonical_root().display().to_string();
    let alias_display = topology_policy.alias_root().display().to_string();
    let topology_cmd = build_worker_projects_topology_cmd(topology_policy, allow_initialization);
    let remote_reader = match source_identity {
        Some(identity) => format!("{} sh -s", source_authority_activity_prefix(identity)?),
        None => "sh -s".to_owned(),
    };
    let output = run_offload_ssh_command_with_stdin(
        worker,
        &remote_reader,
        topology_cmd.as_bytes(),
        Duration::from_secs(20),
    )
    .await?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
        let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
        // A non-symlink alias that does NOT resolve to the canonical root is a
        // path_topology *policy* problem, not a worker fault — every worker will
        // refuse it identically. Name the config sources so operators fix the
        // policy instead of triaging (or "repairing") a healthy worker (rch#32).
        let policy_hint = if stderr.contains("RCH_TOPOLOGY_ERR_ALIAS_TARGET_CONFLICT") {
            "; the alias already names a different source tree; worker topology must be reconciled after existing source owners are retired"
        } else if stderr.contains("RCH_TOPOLOGY_ERR_INITIALIZATION_REQUIRED") {
            "; worker topology changed after the read-only probe; retry after this source intent is cancelled so initialization can acquire its complete grant"
        } else if stderr.contains("RCH_TOPOLOGY_ERR_ALIAS_NOT_SYMLINK") {
            "; the alias root is a plain directory that does not resolve to the canonical root — \
             this is a [path_topology] policy conflict (RCH_ALIAS_PROJECT_ROOT / \
             RCH_CANONICAL_PROJECT_ROOT), not a worker fault; every worker refuses it identically"
        } else {
            ""
        };
        anyhow::bail!(
            "remote topology preflight failed on {} (status {:?}): stdout='{}' stderr='{}'{}",
            worker.id,
            output.status.code(),
            stdout,
            stderr,
            policy_hint
        );
    }
    reporter.verbose(&format!(
        "[RCH] topology preflight ok on {} ({} -> {} enforced)",
        worker.id, alias_display, canonical_display
    ));
    // bd-8iwkm: root-owned entries inside the canonical mirror tree make
    // rsync-as-ssh-user fail exit 23 on replace/unlink even when topology is
    // healthy. Repair them before sync so the failure window closes here
    // instead of mid-transfer.
    // bd-gc0ze follow-up: scope the ownership sweep to THIS dispatch's closure
    // roots instead of the whole canonical mirror. A global scan walks every
    // mirrored repo (13GB+ franken_engine mirrors included) on every dispatch,
    // which blew the fixed SSH budget and failed closed on E104 before any
    // rsync started. The drift that breaks THIS transfer can only live under
    // the remote roots THIS transfer writes into.
    let ownership_scan_roots: Vec<PathBuf> = if dispatch_closure_roots.is_empty() {
        vec![topology_policy.canonical_root().to_path_buf()]
    } else {
        dispatch_closure_roots.to_vec()
    };
    let repaired =
        repair_worker_mirror_ownership(worker, reporter, &ownership_scan_roots, source_identity)
            .await?;
    if repaired > 0 {
        reporter.summary(&format!(
            "[RCH] repaired ownership drift on {}: {repaired} root-owned entries chowned to {}",
            worker.id, worker.user
        ));
    }
    Ok(())
}

/// bd-8iwkm: detect and repair root-owned entries under the dispatch's closure
/// roots on the worker's canonical mirror. Returns the number of repaired
/// entries; zero means either no drift or a fail-open check-unavailable (never
/// blocks dispatch). Scoped to the closure roots (see caller) so cost tracks
/// the trees about to be rsynced rather than the entire mirror.
async fn repair_worker_mirror_ownership(
    worker: &WorkerConfig,
    reporter: &HookReporter,
    roots: &[PathBuf],
    source_identity: Option<&str>,
) -> anyhow::Result<u64> {
    if should_skip_remote_preflight(worker) {
        reporter.verbose("[RCH] ownership preflight skipped in mock mode");
        return Ok(0);
    }
    if crate::transfer::WorkerPlatform::from_worker(worker).is_windows() {
        reporter.verbose("[RCH] ownership preflight skipped for Windows worker");
        return Ok(0);
    }
    // bd-8iwkm/bd-gc0ze: when the SSH user IS root, rsync already runs as
    // root and root-owned entries cannot block replace/unlink. Counting them
    // would flag the entire mirror as drift while the repair chown is a
    // no-op, so the sweep would report RCH_OWNERSHIP_PARTIAL forever and
    // fail-closed every dispatch on root-login workers.
    if worker.user == "root" {
        reporter.verbose("[RCH] ownership preflight skipped for root-login worker");
        return Ok(0);
    }
    let cmd = build_worker_ownership_repair_cmd(roots, &worker.user);
    let remote_reader = match source_identity {
        Some(identity) => format!("{} sh -s", source_authority_activity_prefix(identity)?),
        None => "sh -s".to_owned(),
    };
    // bd-gc0ze: closure-scoped sweeps normally finish in seconds; 600s bounds
    // pathological trees without failing every dispatch the way the old fixed
    // 60s budget did once mirrors grew past multi-GB.
    // rch#71: keep the closure-sized script off argv. The existing stdin
    // executor retains the timeout, concurrent output drains and kill-on-drop.
    let output = run_offload_ssh_command_with_stdin(
        worker,
        &remote_reader,
        cmd.as_bytes(),
        Duration::from_secs(600),
    )
    .await?;
    let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
        anyhow::bail!(
            "worker mirror ownership repair failed on {} (status {:?}): stdout='{}' stderr='{}' — \
             root-owned entries under the dispatch closure block rsync-as-{} (bd-8iwkm)",
            worker.id,
            output.status.code(),
            stdout,
            stderr,
            worker.user
        );
    }
    if let Some(count) = stdout
        .strip_prefix("RCH_OWNERSHIP_REPAIRED:count=")
        .and_then(|value| value.parse::<u64>().ok())
    {
        reporter.verbose(&format!(
            "[RCH] ownership drift repaired on {}: {count} entries chowned to {}",
            worker.id, worker.user
        ));
        return Ok(count);
    }
    Ok(0)
}

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

    #[cfg(unix)]
    #[tokio::test]
    async fn test_worker_ownership_repair_streams_large_closure() {
        let _guard = test_guard!();
        const DIR_ENV: &str = "RCH_OWNERSHIP_TEST_DIR";
        const ROOT_ENV: &str = "RCH_OWNERSHIP_TEST_ROOT";

        // Re-enter this test in a child with its own PATH. Do not mutate the
        // process-wide environment while the rest of the test suite runs.
        if let Some(dir) = std::env::var_os(DIR_ENV) {
            let dir = PathBuf::from(dir);
            let worker = WorkerConfig {
                id: WorkerId::new("ownership-stdin-test"),
                host: "ownership-test.invalid".into(),
                user: "ubuntu".into(),
                ..WorkerConfig::default()
            };
            assert!(!should_skip_remote_preflight(&worker));
            let reporter = HookReporter::new(OutputVisibility::Summary);
            let mut roots: Vec<PathBuf> = (0..4096)
                .map(|i| {
                    dir.join("missing")
                        .join(format!("dep-{i:04}-{}", "x".repeat(160)))
                })
                .collect();
            // An existing, shell-sensitive root at the end also proves that
            // the large payload was not truncated or its roots reinterpreted.
            roots.push(PathBuf::from(std::env::var_os(ROOT_ENV).unwrap()));
            let script = build_worker_ownership_repair_cmd(&roots, &worker.user);
            assert!(script.len() > 128 * 1024);

            for (mode, count, error, calls) in [
                ("healthy", 0, None, "detect\n"),
                ("repair", 1, None, "detect\nrepair\ndetect\n"),
                ("check-unavailable", 0, None, "detect\n"),
                (
                    "unavailable",
                    0,
                    Some((46, "RCH_OWNERSHIP_REPAIR_UNAVAILABLE:detected=1")),
                    "detect\nrepair\n",
                ),
                (
                    "partial",
                    0,
                    Some((47, "RCH_OWNERSHIP_PARTIAL:remaining=1")),
                    "detect\nrepair\ndetect\n",
                ),
            ] {
                std::fs::write(dir.join("mode"), mode).unwrap();
                std::fs::write(dir.join("state"), "pending").unwrap();
                std::fs::write(dir.join("calls"), "").unwrap();
                let result = timeout(
                    Duration::from_secs(20),
                    repair_worker_mirror_ownership(&worker, &reporter, &roots, None),
                )
                .await
                .expect("ownership repair must not hang on stdin/EOF");
                if let Some((code, marker)) = error {
                    let error = result.expect_err(mode).to_string();
                    assert!(error.contains(&format!("status Some({code})")), "{error}");
                    assert!(error.contains(marker), "{error}");
                } else {
                    assert_eq!(result.expect(mode), count, "{mode}");
                }
                assert_eq!(
                    std::fs::read(dir.join("payload")).unwrap(),
                    script.as_bytes()
                );
                assert_eq!(std::fs::read_to_string(dir.join("calls")).unwrap(), calls);
            }
            std::fs::write(dir.join("finished"), "ok").unwrap();
            return;
        }

        use std::os::unix::fs::PermissionsExt as _;
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("bin");
        std::fs::create_dir(&bin).unwrap();
        let root = dir.path().join("root with ' quotes; $cash `echo nope`");
        std::fs::create_dir(&root).unwrap();
        let ssh = bin.join("ssh");
        std::fs::write(
            &ssh,
            r#"#!/bin/sh
set -eu
LC_ALL=C
export LC_ALL
remote=''
for arg; do
    [ "${#arg}" -lt 131072 ] || exit 90
    remote=$arg
done
[ "$remote" = "sh -lc 'sh -s'" ] || exit 91
cat > "$RCH_OWNERSHIP_TEST_DIR/payload"
# Execute the real remote wrapper and script, replacing only privileged work.
{
cat <<'RCH_TEST_SUDO'
sudo() {
    [ "$1" = -n ] && [ "$2" = find ] || return 92
    shift 2
    [ "$1" = "$RCH_OWNERSHIP_TEST_ROOT" ] || return 93
    shift
    [ "$1" = -xdev ] && [ "$2" = -user ] && [ "$3" = root ] || return 94
    shift 3
    mode=$(cat "$RCH_OWNERSHIP_TEST_DIR/mode")
    case "$1" in
        -print)
            [ "$#" -eq 1 ] || return 95
            echo detect >> "$RCH_OWNERSHIP_TEST_DIR/calls"
            [ "$mode" != check-unavailable ] || return 1
            if [ "$mode" != healthy ] && [ "$(cat "$RCH_OWNERSHIP_TEST_DIR/state")" != repaired ]; then
                printf 'root-owned-entry\n'
            fi
            ;;
        -exec)
            [ "$#" -eq 6 ] && [ "$2" = chown ] && [ "$3" = -h ] &&
                [ "$4" = ubuntu ] && [ "$5" = '{}' ] && [ "$6" = + ] || return 96
            echo repair >> "$RCH_OWNERSHIP_TEST_DIR/calls"
            [ "$mode" != unavailable ] || return 1
            if [ "$mode" = repair ]; then
                echo repaired > "$RCH_OWNERSHIP_TEST_DIR/state"
            fi
            ;;
        *) return 97 ;;
    esac
}
RCH_TEST_SUDO
cat "$RCH_OWNERSHIP_TEST_DIR/payload"
} | /bin/sh -c "$remote"
"#,
        )
        .unwrap();
        std::fs::set_permissions(&ssh, std::fs::Permissions::from_mode(0o755)).unwrap();
        let old_path = std::env::var_os("PATH").unwrap_or_default();
        let paths = std::iter::once(bin).chain(std::env::split_paths(&old_path));
        let path = std::env::join_paths(paths).unwrap();
        let test_name = concat!(
            module_path!(),
            "::test_worker_ownership_repair_streams_large_closure"
        );
        let test_name = test_name.split_once("::").unwrap().1;
        let output = timeout(
            Duration::from_secs(60),
            Command::new(std::env::current_exe().unwrap())
                .args(["--exact", test_name, "--nocapture"])
                .env(DIR_ENV, dir.path())
                .env(ROOT_ENV, &root)
                .env("PATH", path)
                .env("RCH_MOCK_SSH", "0")
                .kill_on_drop(true)
                .output(),
        )
        .await
        .expect("isolated ownership regression timed out")
        .expect("start isolated ownership regression");
        assert!(
            output.status.success(),
            "stdout={} stderr={}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(
            dir.path().join("finished").is_file(),
            "child test did not run"
        );
    }

    #[test]
    fn source_authority_lock_keys_are_sorted_deduplicated_and_root_stable() {
        let _guard = test_guard!();
        let forward = source_authority_lock_paths(&[
            "/data/projects/franken_whisper".to_string(),
            "/data/projects/frankensqlite".to_string(),
            "/data/projects/frankensqlite".to_string(),
        ]);
        let reverse = source_authority_lock_paths(&[
            "/data/projects/frankensqlite".to_string(),
            "/data/projects/franken_whisper".to_string(),
        ]);

        assert_eq!(forward, reverse, "input order must not change lock order");
        assert_eq!(forward.len(), 2, "duplicate roots need one authority lock");
        assert_eq!(
            source_authority_lock_paths(&["/data/projects/frankensqlite".to_string()]),
            source_authority_lock_paths(&["/data/projects/frankensqlite".to_string()]),
            "the same canonical root must serialize source-only revisions even when their project hashes differ"
        );
    }

    fn exclusive_source_locks(paths: &[String]) -> Vec<SourceAuthorityLockSpec> {
        paths
            .iter()
            .map(|path| SourceAuthorityLockSpec {
                path: path.clone(),
                shared: false,
            })
            .collect()
    }

    #[test]
    fn canonical_source_authority_root_repairs_only_benign_spellings() {
        // bd-4d1hs: the exact root a dead fleet lease recorded.
        let recorded = "/data/tmp/landing/c9-beads/";
        assert!(source_authority_lock_plan(&[recorded.into()], false).is_err());
        let canonical = canonical_source_authority_root(recorded);
        assert_eq!(canonical, "/data/tmp/landing/c9-beads");
        assert!(source_authority_lock_plan(&[canonical], false).is_ok());

        assert_eq!(canonical_source_authority_root("/a//b/./c/"), "/a/b/c");
        assert_eq!(canonical_source_authority_root("/"), "/");
        assert_eq!(canonical_source_authority_root("/a/b"), "/a/b");
        // Not merely mis-spelled: left as-is so the lock plan still refuses it.
        for unsafe_root in ["relative/dir/", "/a/../b/", "/a/b\n"] {
            assert_eq!(canonical_source_authority_root(unsafe_root), unsafe_root);
            assert!(source_authority_lock_plan(&[unsafe_root.into()], false).is_err());
        }
    }

    #[test]
    fn source_authority_hierarchy_uses_one_order_and_strongest_mode() {
        let forward =
            source_authority_lock_plan(&["/a/child".into(), "/b/child".into(), "/a".into()], true)
                .unwrap();
        let reverse = source_authority_lock_plan(
            &[
                "/a".into(),
                "/b/child".into(),
                "/a/child".into(),
                "/a".into(),
            ],
            true,
        )
        .unwrap();
        assert_eq!(forward, reverse);
        let expected = [
            ("/", true),
            ("/a", false),
            ("/a/child", false),
            ("/b", true),
            ("/b/child", false),
        ]
        .into_iter()
        .map(|(root, shared)| SourceAuthorityLockSpec {
            path: source_authority_lock_path(root),
            shared,
        })
        .collect::<Vec<_>>();
        assert_eq!(forward, expected);
        for root in ["relative", "/a/../b", "/a/./b", "/a//b", "/a/"] {
            assert!(source_authority_lock_plan(&[root.into()], true).is_err());
        }
        let paired = source_authority_lock_plan(&["/private/child".into()], false).unwrap();
        assert_eq!(
            paired,
            exclusive_source_locks(&[source_authority_lock_path("/private/child")])
        );
    }

    /// A started execution is "lost" only when its activity lock is free and
    /// no receipt exists (or the whole registry is gone); a held lock means it
    /// is still running and a receipt means it completed.
    #[cfg(target_os = "linux")]
    #[test]
    fn remote_execution_probe_distinguishes_active_completed_and_lost() {
        use std::process::{Command, Stdio};
        let tmp = tempfile::tempdir().unwrap();
        let registry = tmp.path().join("claims");
        std::fs::create_dir(&registry).unwrap();
        let identity = "0123456789abcdef0123456789abcdef";
        let receipt = tmp.path().join("recovery-1-id");
        let probe = |registry: &Path| {
            let script = remote_execution_probe_script(
                registry.to_str().unwrap(),
                identity,
                receipt.to_str().unwrap(),
            )
            .unwrap();
            let output = Command::new("sh").arg("-c").arg(script).output().unwrap();
            assert!(output.status.success());
            String::from_utf8(output.stdout).unwrap().trim().to_owned()
        };

        assert_eq!(probe(&registry), "RCH_EXEC_LOST", "free lock, no receipt");
        assert_eq!(
            probe(&tmp.path().join("absent")),
            "RCH_EXEC_LOST",
            "registry gone"
        );

        let lock = registry.join(format!("{identity}.activity.lock"));
        // One process holds the lock (the shell execs into sleep, keeping fd
        // 9), so killing it frees the lock. `flock <file> sleep` would leave
        // the lock with the surviving sleep child: the very inheritance the
        // probe relies on to see a live execution.
        let mut holder = Command::new("sh")
            .arg("-c")
            .arg("exec 9>\"$1\" && flock -x 9 && exec sleep 30")
            .arg("lock-holder")
            .arg(&lock)
            .stdout(Stdio::null())
            .spawn()
            .unwrap();
        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        while Command::new("flock")
            .args(["-n"])
            .arg(&lock)
            .arg("true")
            .status()
            .unwrap()
            .success()
        {
            assert!(std::time::Instant::now() < deadline, "holder never locked");
            std::thread::sleep(Duration::from_millis(20));
        }
        assert_eq!(probe(&registry), "RCH_EXEC_ACTIVE", "lock held");
        holder.kill().unwrap();
        holder.wait().unwrap();

        std::fs::write(&receipt, "id 0\n").unwrap();
        assert_eq!(probe(&registry), "RCH_EXEC_COMPLETED", "receipt present");
    }

    #[cfg(target_os = "linux")]
    fn source_lock_test_dir() -> PathBuf {
        // RCH places TMPDIR inside its exclusively held source snapshot.
        // These tests acquire real hierarchical source locks, so their
        // independent repositories must be outside that enclosing grant.
        tempfile::Builder::new()
            .prefix("rch-source-lock-test-")
            .tempdir_in("/tmp")
            .unwrap()
            .keep()
    }

    #[cfg(target_os = "linux")]
    async fn claim_test_source_closure(roots: &[String]) -> RemoteSourceAuthorityLock {
        let locks = source_authority_lock_plan(roots, true).unwrap();
        let script = build_remote_source_authority_lock_cmd(
            REMOTE_SOURCE_AUTHORITY_LOCK_DIR,
            &locks,
            "CLOSURE_READY",
        )
        .unwrap();
        let (child, bootstrap) = local_source_lock_transport(WorkerPlatform::Posix, &script);
        finish_source_authority_lock_acquisition(
            child,
            WorkerId::new("local-closure-regression"),
            "CLOSURE_READY",
            bootstrap.as_deref(),
            Duration::from_secs(10),
        )
        .await
        .unwrap()
    }

    #[cfg(target_os = "linux")]
    async fn claim_test_durable_source_closure(
        registry: &Path,
        roots: &[String],
        identity: &str,
        operation: &str,
    ) -> anyhow::Result<RemoteSourceAuthorityLock> {
        let locks = source_authority_lock_plan(roots, true)?;
        let script = build_durable_source_authority_lock_cmd(
            REMOTE_SOURCE_AUTHORITY_LOCK_DIR,
            registry.to_str().unwrap(),
            &locks,
            roots,
            identity,
            operation,
            "DURABLE_READY",
        )?;
        let (child, bootstrap) = local_source_lock_transport(WorkerPlatform::Posix, &script);
        let mut guard = finish_source_authority_lock_acquisition(
            child,
            WorkerId::new("durable-source-regression"),
            "DURABLE_READY",
            bootstrap.as_deref(),
            Duration::from_secs(10),
        )
        .await?;
        guard.release_request = Some(format!("RCH_SOURCE_AUTHORITY_RELEASE:{identity}"));
        Ok(guard)
    }

    #[cfg(target_os = "linux")]
    async fn test_source_intent(
        registry: &Path,
        roots: &[String],
        identity: &str,
        operation: &str,
    ) -> Output {
        Command::new("sh")
            .args([
                "-c",
                &source_intent_command(registry.to_str().unwrap(), roots, identity, operation)
                    .unwrap(),
            ])
            .kill_on_drop(true)
            .output()
            .await
            .unwrap()
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn durable_source_registry_quarantines_incomplete_pending_without_resurrection() {
        use std::os::unix::fs::MetadataExt;
        async fn legacy_preflight(registry: &Path, token: &str, marker: &Path) {
            // Preserve the old script's identity preflight, before any
            // acquire/recover/cancel branch. The full old script is also
            // exercised during review; this small compatibility contract
            // keeps its size/hash refusal guards committed without a copy
            // of the whole superseded implementation.
            let old_preflight = r#"
set -eu; registry=$1; token=$2; marker=$3
for previous in "$registry/$token."*.claim "$registry/$token."*.pending \
    "$registry/$token."*.cancelling "$registry/released/$token."*.claim \
    "$registry/cancelled/$token."*.claim; do
    [ -e "$previous" ] || [ -L "$previous" ] || continue
    [ ! -L "$previous" ] && [ -f "$previous" ] || exit 73
    size=$(wc -c < "$previous")
    [ "$size" -gt 0 ] && [ "$size" -le 33554432 ] || exit 73
    name=${previous##*/}; record_digest=${name#*.}; record_digest=${record_digest%%.*}
    actual=$(sha256sum -- "$previous")
    [ "${actual%% *}" = "$record_digest" ] || exit 73
done
printf 'legacy identity escaped its fence\n' > "$marker"
"#;
            let output = Command::new("flock")
                .arg("-x")
                .arg(registry.join("metadata.lock"))
                .args(["sh", "-c", old_preflight, "legacy-registry-preflight"])
                .arg(registry)
                .arg(token)
                .arg(marker)
                .kill_on_drop(true)
                .output()
                .await
                .unwrap();
            assert_eq!(output.status.code(), Some(73));
            assert!(
                !marker.exists(),
                "delayed legacy admission crossed its identity fence"
            );
        }
        let directory = tempfile::tempdir().unwrap();
        let registry = directory.path().join("registry");
        std::fs::create_dir(&registry).unwrap();
        let roots = vec![directory.path().join("source").display().to_string()];
        let (contents, digest) = source_claim_roots(&roots).unwrap();
        let damaged = [
            ("aa01", b"".as_slice()),
            ("aa02", b"/truncated".as_slice()),
            ("aa06", b"/interrupted".as_slice()),
        ];
        for (token, bytes) in damaged {
            let pending = registry.join(format!("{token}.{digest}.pending"));
            std::fs::write(&pending, bytes).unwrap();
            if token == "aa06" {
                // Restart after the durable fence but before quarantine's
                // rename. Only this exact hard link may resume that frontier.
                std::fs::hard_link(
                    &pending,
                    registry.join(format!("{token}.{digest}.cancelling")),
                )
                .unwrap();
            }
        }
        // Both admissions reach the real metadata flock concurrently. Exactly
        // one receives this source closure after the failed writes are fenced.
        let (first, second) = tokio::join!(
            test_source_intent(&registry, &roots, "aa03", "acquire"),
            test_source_intent(&registry, &roots, "aa04", "acquire"),
        );
        assert_ne!(first.status.success(), second.status.success());
        let (winner, success, failure) = if first.status.success() {
            ("aa03", first, second)
        } else {
            ("aa04", second, first)
        };
        assert!(String::from_utf8_lossy(&success.stderr).contains("RCH_SOURCE_CLAIM_QUARANTINED"));
        assert!(String::from_utf8_lossy(&failure.stderr).contains("overlapping"));
        for (token, bytes) in damaged {
            let name = format!("{token}.{digest}.pending");
            assert!(!registry.join(&name).exists());
            assert_eq!(
                std::fs::read(registry.join("quarantine").join(&name)).unwrap(),
                bytes
            );
            let fence = registry.join(format!("{token}.{digest}.cancelling"));
            assert_eq!(
                std::fs::metadata(&fence).unwrap().ino(),
                std::fs::metadata(registry.join("quarantine").join(&name))
                    .unwrap()
                    .ino(),
                "legacy scripts must see the same malformed record as a cancellation fence",
            );
            let legacy_marker = directory.path().join(format!("escaped-{token}"));
            legacy_preflight(&registry, token, &legacy_marker).await;
            for operation in ["acquire", "recover"] {
                let output = test_source_intent(&registry, &roots, token, operation).await;
                assert_eq!(output.status.code(), Some(73));
                assert!(String::from_utf8_lossy(&output.stderr).contains("quarantined"));
            }
            let changed = vec![directory.path().join("different").display().to_string()];
            assert_eq!(
                test_source_intent(&registry, &changed, token, "cancel")
                    .await
                    .status
                    .code(),
                Some(73)
            );
            let cancelled = test_source_intent(&registry, &roots, token, "cancel").await;
            assert!(cancelled.status.success(), "{cancelled:?}");
            assert_eq!(cancelled.stdout, b"unowned");
            assert_eq!(
                std::fs::read_to_string(
                    registry
                        .join("cancelled")
                        .join(format!("{token}.{digest}.claim"))
                )
                .unwrap(),
                contents,
            );
            assert!(
                !test_source_intent(&registry, &roots, token, "acquire")
                    .await
                    .status
                    .success()
            );
            legacy_preflight(&registry, token, &legacy_marker).await;
        }
        assert!(
            test_source_intent(&registry, &roots, winner, "release")
                .await
                .status
                .success()
        );
        assert!(
            test_source_intent(&registry, &roots, "aa05", "acquire")
                .await
                .status
                .success()
        );
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn durable_source_registry_does_not_bless_unrelated_corrupt_cancellation() {
        let directory = tempfile::tempdir().unwrap();
        let registry = directory.path().join("registry");
        std::fs::create_dir_all(registry.join("quarantine")).unwrap();
        let roots = vec![directory.path().join("source").display().to_string()];
        let (_, digest) = source_claim_roots(&roots).unwrap();
        let quarantined = registry
            .join("quarantine")
            .join(format!("ad01.{digest}.pending"));
        let cancelling = registry.join(format!("ad01.{digest}.cancelling"));
        std::fs::write(&quarantined, b"/truncated").unwrap();
        std::fs::write(&cancelling, b"/truncated").unwrap();
        let output = test_source_intent(&registry, &roots, "ad01", "cancel").await;
        assert_eq!(output.status.code(), Some(73));
        assert!(
            !registry
                .join("cancelled")
                .join(format!("ad01.{digest}.claim"))
                .exists()
        );
        assert_eq!(std::fs::read(quarantined).unwrap(), b"/truncated");
        assert_eq!(std::fs::read(cancelling).unwrap(), b"/truncated");
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn durable_source_registry_repairs_empty_legacy_cancellation_as_unowned() {
        let directory = tempfile::tempdir().unwrap();
        let registry = directory.path().join("registry");
        std::fs::create_dir_all(&registry).unwrap();
        let roots = vec![directory.path().join("source").display().to_string()];
        let (content, digest) = source_claim_roots(&roots).unwrap();
        // rch <= 2.1.16 left exactly this when its cancellation redirect hit
        // ENOSPC: the record was created and never written.
        let cancelling = registry.join(format!("ad02.{digest}.cancelling"));
        std::fs::write(&cancelling, b"").unwrap();
        let acquire = test_source_intent(&registry, &roots, "ad02", "acquire").await;
        assert_eq!(acquire.status.code(), Some(73));
        assert_eq!(std::fs::read(&cancelling).unwrap(), b"");
        let other_roots = vec![directory.path().join("other").display().to_string()];
        let mismatched = test_source_intent(&registry, &other_roots, "ad02", "cancel").await;
        assert_eq!(mismatched.status.code(), Some(73));
        assert_eq!(std::fs::read(&cancelling).unwrap(), b"");
        for _ in 0..2 {
            let output = test_source_intent(&registry, &roots, "ad02", "cancel").await;
            assert!(
                output.status.success(),
                "{}",
                String::from_utf8_lossy(&output.stderr)
            );
            assert_eq!(output.stdout, b"unowned");
        }
        let cancelled = registry
            .join("cancelled")
            .join(format!("ad02.{digest}.claim"));
        assert_eq!(std::fs::read(cancelled).unwrap(), content.as_bytes());
        assert!(!cancelling.exists());
        let late = test_source_intent(&registry, &roots, "ad02", "acquire").await;
        assert_eq!(late.status.code(), Some(73));
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn durable_source_registry_keeps_empty_cancellation_beside_a_claim() {
        let directory = tempfile::tempdir().unwrap();
        let registry = directory.path().join("registry");
        std::fs::create_dir_all(&registry).unwrap();
        let roots = vec![directory.path().join("source").display().to_string()];
        let (content, digest) = source_claim_roots(&roots).unwrap();
        // An active grant means ownership is real: the empty record is not
        // provably the never-granted legacy case, so it must still refuse.
        let active = registry.join(format!("ad03.{digest}.claim"));
        let cancelling = registry.join(format!("ad03.{digest}.cancelling"));
        std::fs::write(&active, content.as_bytes()).unwrap();
        std::fs::write(&cancelling, b"").unwrap();
        let output = test_source_intent(&registry, &roots, "ad03", "cancel").await;
        assert_eq!(output.status.code(), Some(73));
        assert_eq!(std::fs::read(&cancelling).unwrap(), b"");
        assert_eq!(std::fs::read(&active).unwrap(), content.as_bytes());
        assert!(
            !registry
                .join("cancelled")
                .join(format!("ad03.{digest}.claim"))
                .exists()
        );
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn durable_source_registry_write_failure_keeps_partial_bytes_private() {
        for limit in [0, 1] {
            let directory = tempfile::tempdir().unwrap();
            let registry = directory.path().join("registry");
            // Real EFBIG from RLIMIT_FSIZE exercises zero-byte and truncated
            // writes, without a mocked printf, filesystem, sync, or rename.
            let roots = vec![format!(
                "{}/{}source",
                directory.path().display(),
                "nested/".repeat(400)
            )];
            let (_, digest) = source_claim_roots(&roots).unwrap();
            let script =
                source_intent_command(registry.to_str().unwrap(), &roots, "bb01", "acquire")
                    .unwrap();
            let output = Command::new("sh")
                .args(["-c", &format!("trap '' XFSZ; ulimit -f {limit}; {script}")])
                .kill_on_drop(true)
                .output()
                .await
                .unwrap();
            assert!(
                !output.status.success(),
                "write limit must cause a real failure"
            );
            assert!(!registry.join(format!("bb01.{digest}.pending")).exists());
            assert!(!registry.join(format!("bb01.{digest}.claim")).exists());
            let private: Vec<_> = std::fs::read_dir(&registry)
                .unwrap()
                .map(Result::unwrap)
                .filter(|entry| {
                    entry
                        .file_name()
                        .to_string_lossy()
                        .starts_with(".record-write.")
                })
                .collect();
            assert_eq!(private.len(), 1, "retain the failed bytes for inspection");
            let size = private[0].metadata().unwrap().len();
            assert_eq!(size == 0, limit == 0);
            assert!(size < roots[0].len() as u64);
            let other = vec![directory.path().join("other").display().to_string()];
            assert!(
                test_source_intent(&registry, &other, "bb02", "acquire")
                    .await
                    .status
                    .success()
            );
            let cancelled = test_source_intent(&registry, &roots, "bb01", "cancel").await;
            assert!(cancelled.status.success(), "{cancelled:?}");
            assert_eq!(cancelled.stdout, b"unowned");
        }

        let directory = tempfile::tempdir().unwrap();
        let registry = directory.path().join("registry");
        let roots = vec![directory.path().join("source").display().to_string()];
        let (contents, digest) = source_claim_roots(&roots).unwrap();
        assert!(
            test_source_intent(&registry, &roots, "bc01", "acquire")
                .await
                .status
                .success()
        );
        let script =
            source_intent_command(registry.to_str().unwrap(), &roots, "bc01", "cancel").unwrap();
        let output = Command::new("sh")
            .args(["-c", &format!("trap '' XFSZ; ulimit -f 0; {script}")])
            .kill_on_drop(true)
            .output()
            .await
            .unwrap();
        assert!(!output.status.success());
        assert!(!registry.join(format!("bc01.{digest}.cancelling")).exists());
        assert_eq!(
            std::fs::read_to_string(registry.join(format!("bc01.{digest}.claim"))).unwrap(),
            contents
        );
        assert!(
            !test_source_intent(&registry, &roots, "bc02", "acquire")
                .await
                .status
                .success()
        );
        let cancelled = test_source_intent(&registry, &roots, "bc01", "cancel").await;
        assert!(cancelled.status.success());
        assert_eq!(cancelled.stdout, b"owned");
        assert!(
            test_source_intent(&registry, &roots, "bc01", "finish-cancel")
                .await
                .status
                .success()
        );
        assert!(
            test_source_intent(&registry, &roots, "bc02", "acquire")
                .await
                .status
                .success()
        );
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn durable_source_holder_loss_preserves_snapshot_until_surviving_activity_drains() {
        use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader};
        let directory = source_lock_test_dir();
        let registry = directory.join("registry");
        let parent = directory.join("parent with ' quotes; $cash");
        let nested = parent.join("nested");
        std::fs::create_dir_all(&nested).unwrap();
        let source = nested.join("source");
        let parent_roots = vec![parent.display().to_string()];
        let nested_roots = vec![nested.display().to_string()];
        for (kill, roots, competing) in [
            (false, &nested_roots, &parent_roots),
            (true, &parent_roots, &nested_roots),
        ] {
            let identity = uuid::Uuid::new_v4().simple().to_string();
            std::fs::write(&source, "revision A\n").unwrap();
            let mut owner =
                claim_test_durable_source_closure(&registry, roots, &identity, "acquire")
                    .await
                    .unwrap();
            let prefix =
                source_authority_activity_prefix_at(registry.to_str().unwrap(), &identity).unwrap();
            // Close inherited descriptors deliberately. The flock supervisor
            // must retain ownership even when a tool sanitizes its own FDs.
            let reader_script = "exec 3>&- 4>&- 5>&- 6>&- 7>&- 8>&- 9>&-; cat -- \"$1\"; IFS= read -r resume; cat -- \"$1\"";
            let command = format!(
                "exec {prefix} sh -c {} source-reader {}",
                shell_escape::escape(reader_script.into()),
                shell_escape::escape(source.to_string_lossy()),
            );
            let mut reader = Command::new("sh")
                .args(["-c", &command])
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .kill_on_drop(true)
                .spawn()
                .unwrap();
            let mut lines = BufReader::new(reader.stdout.take().unwrap()).lines();
            assert_eq!(
                lines.next_line().await.unwrap().as_deref(),
                Some("revision A")
            );
            assert!(
                Command::new("kill")
                    .args(["-HUP", &reader.id().unwrap().to_string()])
                    .status()
                    .await
                    .unwrap()
                    .success()
            );
            if kill {
                owner.child.as_mut().unwrap().start_kill().unwrap();
            } else {
                drop(owner.stdin.take());
            }
            owner.child.as_mut().unwrap().wait().await.unwrap();
            drop(owner);
            let fresh_identity = uuid::Uuid::new_v4().simple().to_string();
            let rejected =
                claim_test_durable_source_closure(&registry, competing, &fresh_identity, "acquire")
                    .await;
            assert!(
                rejected.is_err(),
                "dead holder allowed overlapping source mutation"
            );
            assert_eq!(std::fs::read_to_string(&source).unwrap(), "revision A\n");
            let recovered =
                claim_test_durable_source_closure(&registry, roots, &identity, "recover")
                    .await
                    .unwrap();
            let mut release = Box::pin(recovered.release());
            assert!(
                timeout(Duration::from_millis(150), &mut release)
                    .await
                    .is_err()
            );
            reader
                .stdin
                .as_mut()
                .unwrap()
                .write_all(b"resume\n")
                .await
                .unwrap();
            assert_eq!(
                lines.next_line().await.unwrap().as_deref(),
                Some("revision A")
            );
            assert!(reader.wait().await.unwrap().success());
            timeout(Duration::from_secs(10), release)
                .await
                .unwrap()
                .unwrap();
            assert_eq!(
                test_source_intent(&registry, roots, &identity, "released")
                    .await
                    .stdout,
                b"released"
            );
            assert!(
                claim_test_durable_source_closure(&registry, roots, &identity, "recover")
                    .await
                    .is_err()
            );
            let fresh =
                claim_test_durable_source_closure(&registry, competing, &fresh_identity, "acquire")
                    .await
                    .unwrap();
            std::fs::write(&source, "revision B\n").unwrap();
            fresh.release().await.unwrap();
        }
    }

    /// The registry runs under the WORKER's `sh`. macOS workers have bash 3.2
    /// there (a bare `pattern)` inside `$(...)` is a parse error), BSD awk
    /// (no NUL in strings) and BSD realpath/mv, so every source-claimed build
    /// to a Mac worker was refused at the registry (2026-10-13).
    #[test]
    fn source_registry_script_parses_under_the_system_sh() {
        let script = format!(
            "{}\n{}",
            rch_common::stale_target_reap::SOURCE_CLAIM_RECORD_HELPERS,
            SOURCE_CLAIM_REGISTRY,
        );
        let output = std::process::Command::new("/bin/sh")
            .args(["-n", "-c", &script])
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn durable_source_registry_lifecycle_runs_on_the_workers_userland() {
        let gnu_realpath = ["realpath -m /", "grealpath -m /"].iter().any(|probe| {
            std::process::Command::new("sh")
                .args(["-c", &format!("{probe} >/dev/null 2>&1")])
                .status()
                .is_ok_and(|status| status.success())
        });
        let flock = std::process::Command::new("sh")
            .args(["-c", "command -v flock >/dev/null"])
            .status()
            .is_ok_and(|status| status.success());
        if !gnu_realpath || !flock {
            eprintln!("skipping: needs flock and GNU realpath (grealpath on macOS)");
            return;
        }
        let directory = tempfile::Builder::new()
            .prefix("rch-source-registry-portable-")
            .tempdir_in("/tmp")
            .unwrap();
        let registry = directory.path().join("registry");
        let root = directory.path().join("source");
        std::fs::create_dir_all(root.join("sub")).unwrap();
        std::fs::create_dir_all(directory.path().join("other")).unwrap();
        let roots = |path: &Path| vec![path.display().to_string()];
        let run = |path: PathBuf, identity: String, operation: &'static str| {
            let registry = registry.clone();
            async move {
                let command = source_intent_command(
                    registry.to_str().unwrap(),
                    &roots(&path),
                    &identity,
                    operation,
                )
                .unwrap();
                Command::new("sh")
                    .args(["-c", &command])
                    .kill_on_drop(true)
                    .output()
                    .await
                    .unwrap()
            }
        };
        let id = || uuid::Uuid::new_v4().simple().to_string();
        let owner = id();
        let ok = |output: &Output| {
            assert!(
                output.status.success(),
                "{}",
                String::from_utf8_lossy(&output.stderr)
            );
        };

        ok(&run(root.clone(), owner.clone(), "acquire").await);
        let overlapping = run(root.join("sub"), id(), "acquire").await;
        assert!(!overlapping.status.success());
        assert!(
            String::from_utf8_lossy(&overlapping.stderr).contains("overlapping source owner"),
            "{}",
            String::from_utf8_lossy(&overlapping.stderr)
        );
        ok(&run(directory.path().join("other"), id(), "acquire").await);
        ok(&run(root.clone(), owner.clone(), "recover").await);
        ok(&run(root.clone(), owner, "release").await);
        ok(&run(root.join("sub"), id(), "acquire").await);
        // Cancelling an intent that never acquired leaves an unowned tombstone.
        ok(&run(directory.path().join("never"), id(), "cancel").await);
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn durable_source_intent_cancel_fences_absent_and_late_claims() {
        let directory = source_lock_test_dir();
        let registry = directory.join("registry");
        let roots = vec![directory.join("source").display().to_string()];
        let identity = uuid::Uuid::new_v4().simple().to_string();
        for _ in 0..2 {
            let output = test_source_intent(&registry, &roots, &identity, "cancel").await;
            assert!(
                output.status.success(),
                "{}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
        assert!(
            claim_test_durable_source_closure(&registry, &roots, &identity, "acquire")
                .await
                .is_err()
        );
        assert!(
            claim_test_durable_source_closure(&registry, &roots, "ab12", "recover")
                .await
                .is_err()
        );
        let different = vec![directory.join("other").display().to_string()];
        assert!(
            !test_source_intent(&registry, &different, &identity, "cancel")
                .await
                .status
                .success()
        );
        let marker = directory.join("late-mutation");
        let prefix =
            source_authority_activity_prefix_at(registry.to_str().unwrap(), &identity).unwrap();
        let output = Command::new("sh")
            .args([
                "-c",
                &format!(
                    "{prefix} touch {}",
                    shell_escape::escape(marker.to_string_lossy())
                ),
            ])
            .output()
            .await
            .unwrap();
        assert!(!output.status.success());
        assert!(!marker.exists());
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn durable_source_activity_serializes_surviving_writer_before_compiler() {
        use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
        let directory = source_lock_test_dir();
        let registry = directory.join("registry");
        let root = directory.join("source");
        std::fs::create_dir_all(&root).unwrap();
        let source = root.join("input");
        let artifact = root.join("artifact");
        std::fs::write(&source, "before writer\n").unwrap();
        let owner = claim_test_durable_source_closure(
            &registry,
            &[root.display().to_string()],
            "ab21",
            "acquire",
        )
        .await
        .unwrap();
        let prefix =
            source_authority_activity_prefix_at(registry.to_str().unwrap(), "ab21").unwrap();
        let script = "exec 3>&- 4>&- 5>&-; printf writing; IFS= read -r done; printf 'after writer\\n' > \"$1\"";
        let mut writer = Command::new("sh")
            .args([
                "-c",
                &format!(
                    "exec {prefix} sh -c {} writer {}",
                    shell_escape::escape(script.into()),
                    shell_escape::escape(source.to_string_lossy()),
                ),
            ])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .unwrap();
        let mut writing = [0; 7];
        writer
            .stdout
            .as_mut()
            .unwrap()
            .read_exact(&mut writing)
            .await
            .unwrap();
        assert_eq!(&writing, b"writing");
        assert!(
            Command::new("kill")
                .args(["-HUP", &writer.id().unwrap().to_string()])
                .status()
                .await
                .unwrap()
                .success()
        );
        let mut compiler = Command::new("sh")
            .args([
                "-c",
                &format!(
                    "exec {prefix} cp -- {} {}",
                    shell_escape::escape(source.to_string_lossy()),
                    shell_escape::escape(artifact.to_string_lossy()),
                ),
            ])
            .kill_on_drop(true)
            .spawn()
            .unwrap();
        assert!(
            timeout(Duration::from_millis(150), compiler.wait())
                .await
                .is_err()
        );
        assert!(
            !artifact.exists(),
            "compiler ran while an old writer was alive"
        );
        writer
            .stdin
            .as_mut()
            .unwrap()
            .write_all(b"done\n")
            .await
            .unwrap();
        assert!(writer.wait().await.unwrap().success());
        assert!(compiler.wait().await.unwrap().success());
        assert_eq!(
            std::fs::read_to_string(&artifact).unwrap(),
            "after writer\n"
        );
        owner.release().await.unwrap();
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn durable_source_cancellation_blocks_overlapping_writers_through_cleanup() {
        use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
        let directory = source_lock_test_dir();
        let registry = directory.join("registry");
        let parent = directory.join("parent");
        let nested = parent.join("nested");
        std::fs::create_dir_all(&nested).unwrap();
        let roots = vec![nested.display().to_string()];
        let competing = vec![parent.display().to_string()];
        let mut owner = claim_test_durable_source_closure(&registry, &roots, "ab11", "acquire")
            .await
            .unwrap();
        drop(owner.stdin.take());
        owner.child.as_mut().unwrap().wait().await.unwrap();
        drop(owner);
        let cancellation = test_source_intent(&registry, &roots, "ab11", "cancel").await;
        assert!(cancellation.status.success());
        assert_eq!(cancellation.stdout, b"owned");
        assert!(
            claim_test_durable_source_closure(&registry, &competing, "ab12", "acquire")
                .await
                .is_err()
        );
        let cleanup =
            source_authority_activity_prefix_for_mode(registry.to_str().unwrap(), "ab11", true)
                .unwrap();
        let mut child = Command::new("sh")
            .args([
                "-c",
                &format!("exec {cleanup} sh -c 'printf ready; IFS= read -r done'"),
            ])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .unwrap();
        let mut ready = [0; 5];
        child
            .stdout
            .as_mut()
            .unwrap()
            .read_exact(&mut ready)
            .await
            .unwrap();
        assert_eq!(&ready, b"ready");
        let mut finish = Box::pin(test_source_intent(
            &registry,
            &roots,
            "ab11",
            "finish-cancel",
        ));
        assert!(
            timeout(Duration::from_millis(150), &mut finish)
                .await
                .is_err()
        );
        child
            .stdin
            .as_mut()
            .unwrap()
            .write_all(b"done\n")
            .await
            .unwrap();
        assert!(child.wait().await.unwrap().success());
        assert!(
            timeout(Duration::from_secs(10), finish)
                .await
                .unwrap()
                .status
                .success()
        );
        let fresh = claim_test_durable_source_closure(&registry, &competing, "ab12", "acquire")
            .await
            .unwrap();
        fresh.release().await.unwrap();
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn durable_source_siblings_and_exact_pending_recovery_preserve_authority() {
        let directory = source_lock_test_dir();
        let registry = directory.join("registry");
        let left = vec![directory.join("left").display().to_string()];
        let right = vec![directory.join("right").display().to_string()];
        let first = claim_test_durable_source_closure(&registry, &left, "a1", "acquire")
            .await
            .unwrap();
        let second = claim_test_durable_source_closure(&registry, &right, "a2", "acquire")
            .await
            .unwrap();
        second.release().await.unwrap();
        first.release().await.unwrap();
        // Crash after complete pending data was persisted but before its rename.
        // Strict recovery may finish that exact transition, never invent it.
        let (contents, digest) = source_claim_roots(&left).unwrap();
        std::fs::write(registry.join(format!("a3.{digest}.pending")), contents).unwrap();
        let recovered = claim_test_durable_source_closure(&registry, &left, "a3", "recover")
            .await
            .unwrap();
        recovered.release().await.unwrap();
        // Historical token roots cannot change after its active claim is gone.
        assert!(
            claim_test_durable_source_closure(&registry, &right, "a3", "acquire")
                .await
                .is_err()
        );
        std::fs::write(
            registry.join(format!("a4.{}.claim", "0".repeat(64))),
            format!("{}\n", left[0]),
        )
        .unwrap();
        assert!(
            claim_test_durable_source_closure(&registry, &right, "a5", "acquire")
                .await
                .is_err()
        );
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn durable_source_claims_fence_worker_path_aliases_after_holder_loss() {
        let directory = source_lock_test_dir();
        let registry = directory.join("registry");
        let real = directory.join("physical");
        std::fs::create_dir_all(real.join("nested")).unwrap();
        let alias = directory.join("alias");
        std::os::unix::fs::symlink(&real, &alias).unwrap();
        let real_roots = vec![real.join("nested").display().to_string()];
        let alias_roots = vec![alias.join("nested").display().to_string()];
        for (roots, contender, identity) in [
            (&real_roots, &alias_roots, "ac11"),
            (&alias_roots, &real_roots, "ac12"),
        ] {
            let mut owner =
                claim_test_durable_source_closure(&registry, roots, identity, "acquire")
                    .await
                    .unwrap();
            owner.child.as_mut().unwrap().start_kill().unwrap();
            owner.child.as_mut().unwrap().wait().await.unwrap();
            drop(owner);
            // Lexical hierarchy keys differ. Physical comparison must retain
            // exclusion even after all of the owner's kernel locks disappear.
            assert!(
                claim_test_durable_source_closure(&registry, contender, "ac13", "acquire")
                    .await
                    .is_err()
            );
            let recovered =
                claim_test_durable_source_closure(&registry, roots, identity, "recover")
                    .await
                    .unwrap();
            recovered.release().await.unwrap();
        }
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn explicit_topology_setup_waits_for_sources_and_cancellation_fences_late_retarget() {
        let directory = source_lock_test_dir();
        let registry = directory.join("registry");
        for (index, job_uses_alias) in [false, true].into_iter().enumerate() {
            let fixture = directory.join(format!("topology-{index}"));
            let previous = fixture.join("previous sources");
            let canonical = fixture.join("new sources");
            let alias = fixture.join("alias ' quoted");
            std::fs::create_dir_all(previous.join("repo")).unwrap();
            std::fs::create_dir_all(canonical.join("repo")).unwrap();
            std::fs::write(previous.join("repo/input"), b"existing build\n").unwrap();
            std::fs::write(canonical.join("repo/input"), b"next build\n").unwrap();
            std::os::unix::fs::symlink(&previous, &alias).unwrap();
            let job_root = if job_uses_alias { &alias } else { &previous };
            let job_roots = vec![job_root.join("repo").display().to_string()];
            let setup_roots = vec![canonical.display().to_string(), alias.display().to_string()];
            let job_token = format!("da{index}1");
            let cancelled_token = format!("da{index}2");
            let setup_token = format!("da{index}3");
            let next_token = format!("da{index}4");
            let job =
                claim_test_durable_source_closure(&registry, &job_roots, &job_token, "acquire")
                    .await
                    .unwrap();

            // Exercise the actual metadata admission transaction directly so
            // lexical hierarchy locks cannot hide a missing physical check.
            let blocked =
                test_source_intent(&registry, &setup_roots, &cancelled_token, "acquire").await;
            assert_eq!(blocked.status.code(), Some(73));
            assert!(String::from_utf8_lossy(&blocked.stderr).contains("overlapping"));
            assert_eq!(std::fs::read_link(&alias).unwrap(), previous);

            let cancellation =
                test_source_intent(&registry, &setup_roots, &cancelled_token, "cancel").await;
            assert!(cancellation.status.success());
            assert_eq!(cancellation.stdout, b"unowned");
            let retarget = |prefix: &str| {
                format!(
                    "exec {prefix} ln -sfn -- {} {}",
                    shell_escape::escape(canonical.to_string_lossy()),
                    shell_escape::escape(alias.to_string_lossy()),
                )
            };
            let cancelled_prefix =
                source_authority_activity_prefix_at(registry.to_str().unwrap(), &cancelled_token)
                    .unwrap();
            let late = Command::new("sh")
                .args(["-c", &retarget(&cancelled_prefix)])
                .output()
                .await
                .unwrap();
            assert!(!late.status.success());
            assert_eq!(std::fs::read_link(&alias).unwrap(), previous);
            assert_eq!(
                std::fs::read(alias.join("repo/input")).unwrap(),
                b"existing build\n"
            );

            job.release().await.unwrap();
            let setup =
                claim_test_durable_source_closure(&registry, &setup_roots, &setup_token, "acquire")
                    .await
                    .unwrap();
            let setup_prefix =
                source_authority_activity_prefix_at(registry.to_str().unwrap(), &setup_token)
                    .unwrap();
            let output = Command::new("sh")
                .args(["-c", &retarget(&setup_prefix)])
                .output()
                .await
                .unwrap();
            assert!(
                output.status.success(),
                "{}",
                String::from_utf8_lossy(&output.stderr)
            );
            assert_eq!(std::fs::read_link(&alias).unwrap(), canonical);
            assert_eq!(
                std::fs::read(alias.join("repo/input")).unwrap(),
                b"next build\n"
            );
            setup.release().await.unwrap();
            let next = claim_test_durable_source_closure(
                &registry,
                &[alias.join("repo").display().to_string()],
                &next_token,
                "acquire",
            )
            .await
            .unwrap();
            next.release().await.unwrap();
        }
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn source_authority_hierarchy_prevents_nested_snapshot_mutation() {
        use super::super::dependency_closure::build_sync_closure_plan;
        use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader};

        let dir = source_lock_test_dir();
        let parent = dir.join("repository");
        let nested = parent.join("standalone");
        std::fs::create_dir_all(nested.join("src")).unwrap();
        std::fs::write(
            parent.join("Cargo.toml"),
            "[package]\nname='parent'\nversion='0.1.0'\n[dependencies]\nchild={path='standalone'}\n",
        )
        .unwrap();
        std::fs::write(
            nested.join("Cargo.toml"),
            "[package]\nname='child'\nversion='0.1.0'\n",
        )
        .unwrap();
        let source = nested.join("src/lib.rs");
        let policy = PathTopologyPolicy::new(dir.clone(), dir.join("alias"));
        // Exercise the production collapse that caused this race: the parent
        // transfer covers the child, while a child-cwd invocation syncs only
        // the child. Neither manifest declares a Cargo workspace.
        let parent_plan = build_sync_closure_plan(
            &[parent.clone(), nested.clone()],
            &parent,
            "parent-revision",
            &policy,
        );
        let nested_plan = build_sync_closure_plan(
            std::slice::from_ref(&nested),
            &nested,
            "child-revision",
            &policy,
        );
        assert_eq!(parent_plan.len(), 1);
        assert_eq!(nested_plan.len(), 1);
        assert_ne!(parent_plan[0].remote_root, nested_plan[0].remote_root);
        let parent_roots = vec![parent_plan[0].remote_root.clone()];
        let nested_roots = vec![nested_plan[0].remote_root.clone()];

        // Prove exclusion in both directions: ancestor writes versus a child
        // reader, and child writes versus an ancestor reader.
        for (reader_roots, writer_roots) in [
            (&parent_roots, &nested_roots),
            (&nested_roots, &parent_roots),
        ] {
            std::fs::write(&source, "revision A\n").unwrap();
            let first = claim_test_source_closure(reader_roots).await;
            let mut reader = Command::new("sh")
                .args([
                    "-c",
                    "cat -- \"$1\"; IFS= read -r resume; cat -- \"$1\"",
                    "snapshot-reader",
                ])
                .arg(&source)
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .kill_on_drop(true)
                .spawn()
                .unwrap();
            let mut lines = BufReader::new(reader.stdout.take().unwrap()).lines();
            assert_eq!(
                timeout(Duration::from_secs(5), lines.next_line())
                    .await
                    .unwrap()
                    .unwrap()
                    .as_deref(),
                Some("revision A")
            );
            let mut competing_sync = Box::pin(async {
                let second = claim_test_source_closure(writer_roots).await;
                let status = Command::new("sh")
                    .args(["-c", "printf 'revision B\\n' > \"$1\"", "snapshot-writer"])
                    .arg(&source)
                    .kill_on_drop(true)
                    .status()
                    .await
                    .unwrap();
                assert!(status.success());
                second.release().await.unwrap();
            });
            let early_write = timeout(Duration::from_millis(150), &mut competing_sync).await;
            assert_eq!(
                std::fs::read_to_string(&source).unwrap(),
                "revision A\n",
                "a concurrent closure sync changed bytes while the reader was active"
            );
            assert!(
                early_write.is_err(),
                "overlapping sync acquired before reader exit"
            );
            reader
                .stdin
                .as_mut()
                .unwrap()
                .write_all(b"resume\n")
                .await
                .unwrap();
            assert_eq!(
                timeout(Duration::from_secs(5), lines.next_line())
                    .await
                    .unwrap()
                    .unwrap()
                    .as_deref(),
                Some("revision A")
            );
            assert!(
                timeout(Duration::from_secs(5), reader.wait())
                    .await
                    .unwrap()
                    .unwrap()
                    .success()
            );
            first.release().await.unwrap();
            timeout(Duration::from_secs(10), competing_sync)
                .await
                .unwrap();
            assert_eq!(std::fs::read_to_string(&source).unwrap(), "revision B\n");
        }
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn source_authority_hierarchy_disjoint_siblings_proceed_concurrently() {
        let dir = source_lock_test_dir();
        let first_root = dir.join("left");
        let second_root = dir.join("right");
        std::fs::create_dir_all(&first_root).unwrap();
        std::fs::create_dir_all(&second_root).unwrap();
        let mut first = claim_test_source_closure(&[first_root.display().to_string()]).await;
        let second = timeout(
            Duration::from_secs(5),
            claim_test_source_closure(&[second_root.display().to_string()]),
        )
        .await
        .expect("shared ancestors must not serialize disjoint sibling closures");
        let source = second_root.join("source");
        let status = Command::new("sh")
            .args(["-c", "printf 'second writer' > \"$1\"", "sibling-writer"])
            .arg(&source)
            .kill_on_drop(true)
            .status()
            .await
            .unwrap();
        assert!(status.success());
        assert_eq!(std::fs::read_to_string(source).unwrap(), "second writer");
        first.ensure_held().unwrap();
        second.release().await.unwrap();
        first.release().await.unwrap();
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn source_authority_hierarchy_reversed_multi_root_claims_finish() {
        async fn read_under_closure(roots: &[String], source: &Path) -> Vec<u8> {
            let guard = claim_test_source_closure(roots).await;
            let output = Command::new("cat")
                .arg(source)
                .kill_on_drop(true)
                .output()
                .await
                .unwrap();
            assert!(output.status.success());
            guard.release().await.unwrap();
            output.stdout
        }
        let dir = source_lock_test_dir();
        let parent = dir.join("a");
        let nested = parent.join("child");
        let sibling = dir.join("z");
        std::fs::create_dir_all(&nested).unwrap();
        std::fs::create_dir_all(&sibling).unwrap();
        let source = nested.join("source");
        std::fs::write(&source, "one coherent revision").unwrap();
        let forward = vec![
            nested.display().to_string(),
            parent.display().to_string(),
            sibling.display().to_string(),
        ];
        let reverse = forward.iter().rev().cloned().collect::<Vec<_>>();
        let (first, second) = timeout(Duration::from_secs(10), async {
            tokio::join!(
                read_under_closure(&forward, &source),
                read_under_closure(&reverse, &source)
            )
        })
        .await
        .expect("reversed overlapping root sets deadlocked");
        assert_eq!(first, b"one coherent revision");
        assert_eq!(second, b"one coherent revision");
    }

    /// How long a test may wait to ACQUIRE a source-authority lock.
    ///
    /// Generous on purpose. What these tests assert is serialization —
    /// "the second claimant does not get in while the first holds it", checked
    /// with a short NEGATIVE wait — and that property does not get weaker as
    /// this budget grows. A tight budget only adds a second, unintended
    /// assertion: "and the machine was not busy". Under a 3000-test parallel
    /// run on a loaded worker that one fails, and a suite that fails only under
    /// load is a suite people learn to ignore (bd-es64k).
    #[cfg(target_os = "linux")]
    const TEST_LOCK_ACQUIRE_BUDGET: Duration = Duration::from_secs(60);

    #[cfg(target_os = "linux")]
    async fn claim_test_source_pair(
        lock: &Path,
        root: &Path,
    ) -> anyhow::Result<RemoteSourceAuthorityLock> {
        let token = uuid::Uuid::new_v4().to_string();
        let ready = format!("ready:{token}");
        let release = format!("release:{token}");
        let script = clean_overlay_source_pair_lock_command(
            lock.to_str().unwrap(),
            root.to_str().unwrap(),
            &token,
            &ready,
            &release,
        );
        let (child, bootstrap) = local_source_lock_transport(WorkerPlatform::Posix, &script);
        let mut guard = finish_source_authority_lock_acquisition(
            child,
            WorkerId::new("local-pair-test"),
            &ready,
            bootstrap.as_deref(),
            TEST_LOCK_ACQUIRE_BUDGET,
        )
        .await?;
        guard.release_request = Some(release);
        // Pair ownership itself creates no source directory. These existing
        // pair lifecycle fixtures model the later, separately owned upload.
        std::fs::create_dir_all(root)?;
        Ok(guard)
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn source_pair_claim_does_not_mutate_source_before_full_grant() {
        let directory = tempfile::tempdir().unwrap().keep();
        let root = directory.join("not-yet-materialized");
        let lock = directory.join("pair.lock");
        let token = uuid::Uuid::new_v4().simple().to_string();
        let ready = format!("ready:{token}");
        let release = format!("release:{token}");
        let script = clean_overlay_source_pair_lock_command(
            lock.to_str().unwrap(),
            root.to_str().unwrap(),
            &token,
            &ready,
            &release,
        );
        let (child, bootstrap) = local_source_lock_transport(WorkerPlatform::Posix, &script);
        let mut guard = finish_source_authority_lock_acquisition(
            child,
            WorkerId::new("pair-intent-only"),
            &ready,
            bootstrap.as_deref(),
            TEST_LOCK_ACQUIRE_BUDGET,
        )
        .await
        .unwrap();
        assert!(
            !root.exists(),
            "pair intent mutated sources before full grant"
        );
        assert_eq!(
            std::fs::read_to_string(directory.join("pair.lock.owner")).unwrap(),
            format!("{token}\n")
        );
        guard.release_request = Some(release);
        guard.release().await.unwrap();
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn source_pair_serializes_until_retirement_and_explicit_release() {
        let dir = tempfile::tempdir().unwrap().keep();
        let root = dir.join("source with ' quotes");
        let lock = dir.join("pair.lock");
        let first = claim_test_source_pair(&lock, &root).await.unwrap();
        std::fs::write(root.join("fixture"), "first").unwrap();
        let second_lock = lock.clone();
        let second_root = root.clone();
        let mut second =
            tokio::spawn(async move { claim_test_source_pair(&second_lock, &second_root).await });
        assert!(
            timeout(Duration::from_millis(100), &mut second)
                .await
                .is_err()
        );
        assert_eq!(
            std::fs::read_to_string(root.join("fixture")).unwrap(),
            "first"
        );
        // Retire rather than delete so the test preserves its evidence.
        std::fs::rename(&root, dir.join("first-retired")).unwrap();
        first.release().await.unwrap();
        // The serialization assertion is the 100ms negative wait above; this
        // one only says the release eventually lets the waiter through.
        let second = timeout(TEST_LOCK_ACQUIRE_BUDGET, second)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        assert!(root.is_dir());
        assert!(!root.join("fixture").exists());
        std::fs::write(root.join("fixture"), "second").unwrap();
        std::fs::rename(&root, dir.join("second-retired")).unwrap();
        second.release().await.unwrap();
        assert_eq!(
            std::fs::read_to_string(dir.join("first-retired/fixture")).unwrap(),
            "first"
        );
        assert_eq!(
            std::fs::read_to_string(dir.join("second-retired/fixture")).unwrap(),
            "second"
        );
        assert_eq!(
            std::fs::read_to_string(dir.join("pair.lock.owner")).unwrap(),
            "released\n"
        );
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn source_pair_holder_loss_never_authorizes_another_writer() {
        let dir = tempfile::tempdir().unwrap().keep();
        let root = dir.join("source");
        let lock = dir.join("pair.lock");
        let first = claim_test_source_pair(&lock, &root).await.unwrap();
        std::fs::write(root.join("fixture"), "owned by interrupted job").unwrap();
        drop(first);
        let error = match claim_test_source_pair(&lock, &root).await {
            Ok(_) => panic!("holder loss must not release a reusable source path"),
            Err(error) => error,
        };
        assert!(error.to_string().contains("unfinished owner"), "{error:#}");
        assert_eq!(
            std::fs::read_to_string(root.join("fixture")).unwrap(),
            "owned by interrupted job"
        );
        assert_ne!(
            std::fs::read_to_string(dir.join("pair.lock.owner")).unwrap(),
            "released\n"
        );
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn source_pair_holder_loss_blocks_setup_capability_fallback() {
        use crate::transfer::{RemoteExecutionUnconfirmed, RemoteProcessSetupUnavailable};

        let dir = tempfile::tempdir().unwrap().keep();
        let root = dir.join("source");
        let lock = dir.join("pair.lock");
        let mut owner = claim_test_source_pair(&lock, &root).await.unwrap();
        std::fs::write(root.join("fixture"), "source retained for original owner").unwrap();
        let ownership_path = dir.join("pair.lock.owner");
        let ownership = std::fs::read(&ownership_path).unwrap();
        let pipeline = TransferPipeline::new(
            root.clone(),
            "setup-capability-test".to_owned(),
            "source-pair".to_owned(),
            TransferConfig::default(),
        );
        let result = rch_common::CommandResult {
            exit_code: 125,
            stdout: String::new(),
            stderr: format!("{}\n", pipeline.remote_process_setup_marker()),
            duration_ms: 0,
        };

        // Establish that this exact setup receipt reaches the worker-fallback
        // classification while the real holder and source pair remain owned.
        let setup_error =
            super::super::transfer_orchestration::ensure_remote_process_setup_after_completion(
                &pipeline,
                &result,
                Some(&mut owner),
            )
            .unwrap_err();
        assert!(
            setup_error
                .downcast_ref::<RemoteProcessSetupUnavailable>()
                .is_some()
        );
        assert_eq!(
            classify_remote_pipeline_failure(&setup_error),
            RemotePipelineFailurePolicy::AllowLocalFallback
        );

        // Lose the actual holder after the execution receipt arrived. The
        // production boundary must recheck it before authorizing any fallback.
        owner.child.as_mut().unwrap().kill().await.unwrap();
        let error =
            super::super::transfer_orchestration::ensure_remote_process_setup_after_completion(
                &pipeline,
                &result,
                Some(&mut owner),
            )
            .unwrap_err();
        assert!(error.downcast_ref::<RemoteExecutionUnconfirmed>().is_some());
        assert!(
            error
                .downcast_ref::<RemoteProcessSetupUnavailable>()
                .is_none()
        );
        assert_eq!(
            classify_remote_pipeline_failure(&error),
            RemotePipelineFailurePolicy::FailClosedNoLocalFallback
        );
        drop(owner);

        let claim_error = match claim_test_source_pair(&lock, &root).await {
            Ok(_) => panic!("setup refusal must not release a pair whose ownership was lost"),
            Err(error) => error,
        };
        assert!(
            claim_error.to_string().contains("unfinished owner"),
            "{claim_error:#}"
        );
        assert_eq!(std::fs::read(&ownership_path).unwrap(), ownership);
        assert_eq!(
            std::fs::read_to_string(root.join("fixture")).unwrap(),
            "source retained for original owner"
        );
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn source_pair_execution_transport_loss_preserves_a_running_reader() {
        use tokio::io::AsyncWriteExt as _;

        for exit_code in [255, -1] {
            let dir = tempfile::tempdir().unwrap().keep();
            let root = dir.join("source");
            let lock = dir.join("pair.lock");
            let mut owner = claim_test_source_pair(&lock, &root).await.unwrap();
            std::fs::write(root.join("fixture"), "original source").unwrap();
            // A separate execution process can survive a transport failure.
            // Hold it until another claimant has attempted to reuse the pair.
            let mut reader = Command::new("sh")
                .current_dir(&root)
                .args(["-c", "IFS= read -r signal; cat fixture"])
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .kill_on_drop(true)
                .spawn()
                .unwrap();
            owner.ensure_execution_finished(0).unwrap();
            owner.ensure_execution_finished(101).unwrap();
            assert!(owner.ensure_execution_finished(exit_code).is_err());
            drop(owner);
            assert!(claim_test_source_pair(&lock, &root).await.is_err());
            let mut stdin = reader.stdin.take().unwrap();
            stdin.write_all(b"read\n").await.unwrap();
            drop(stdin);
            let output = timeout(Duration::from_secs(5), reader.wait_with_output())
                .await
                .unwrap()
                .unwrap();
            assert!(output.status.success());
            assert_eq!(output.stdout, b"original source");
            assert!(root.is_dir());
        }
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn source_pair_rejects_empty_or_malformed_ownership_state() {
        let dir = tempfile::tempdir().unwrap().keep();
        for (index, contents) in ["", "release", "released\noccupied", "unknown"]
            .iter()
            .enumerate()
        {
            let lock = dir.join(format!("pair-{index}.lock"));
            let root = dir.join(format!("source-{index}"));
            std::fs::write(dir.join(format!("pair-{index}.lock.owner")), contents).unwrap();
            assert!(claim_test_source_pair(&lock, &root).await.is_err());
            assert!(!root.exists());
        }
    }

    #[cfg(target_os = "linux")]
    fn spawn_local_source_lock(
        lock_path: &str,
        marker: &str,
    ) -> (
        std::process::Child,
        std::sync::mpsc::Receiver<std::io::Result<String>>,
    ) {
        use std::io::BufRead as _;

        let command = build_remote_source_authority_lock_cmd(
            "/tmp",
            &exclusive_source_locks(&[lock_path.to_string()]),
            marker,
        )
        .expect("build source lock command");
        let mut child = std::process::Command::new("sh")
            .arg("-lc")
            .arg(command)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::inherit())
            .spawn()
            .expect("spawn local source lock holder");
        let stdout = child.stdout.take().expect("lock holder stdout");
        let (sender, receiver) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let mut line = String::new();
            let result = std::io::BufReader::new(stdout)
                .read_line(&mut line)
                .map(|_| line);
            let _ = sender.send(result);
        });
        (child, receiver)
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn source_authority_lock_is_held_until_owner_stdin_closes() {
        let _guard = test_guard!();
        // Production locks are hashed regular files (source_authority_lock_path);
        // the GNU holder refuses a directory, so never lock a root directly.
        let locks = tempfile::tempdir().unwrap();
        let lock = locks.path().join("authority.lock");
        let lock = lock.to_string_lossy();
        let (mut first, first_ready) = spawn_local_source_lock(&lock, "FIRST_READY");
        assert_eq!(
            first_ready
                .recv_timeout(Duration::from_secs(2))
                .expect("first lock acquisition")
                .expect("first ready line")
                .trim_end(),
            "FIRST_READY"
        );

        let (mut second, second_ready) = spawn_local_source_lock(&lock, "SECOND_READY");
        assert!(
            matches!(
                second_ready.recv_timeout(Duration::from_millis(200)),
                Err(std::sync::mpsc::RecvTimeoutError::Timeout)
            ),
            "a competing sync must remain blocked for the entire execution phase"
        );

        drop(first.stdin.take());
        assert!(first.wait().expect("wait for first lock holder").success());
        assert_eq!(
            second_ready
                .recv_timeout(Duration::from_secs(2))
                .expect("second lock acquisition after first exits")
                .expect("second ready line")
                .trim_end(),
            "SECOND_READY"
        );
        drop(second.stdin.take());
        assert!(
            second
                .wait()
                .expect("wait for second lock holder")
                .success()
        );
    }

    #[cfg(target_os = "linux")]
    fn local_source_lock_transport(
        platform: WorkerPlatform,
        script: &str,
    ) -> (tokio::process::Child, Option<String>) {
        let (remote_arg, bootstrap) = source_authority_lock_transport(platform, script);
        let expected = if platform.is_windows() {
            "sh -s".to_owned()
        } else {
            build_remote_shell_command(platform, "exec sh -s")
        };
        assert_eq!(remote_arg, expected);
        assert_eq!(
            bootstrap.as_deref(),
            Some(format!("{{\n{script}\n}}\n").as_str())
        );
        // Actual POSIX reader/flock processes exercise the production stdin
        // and guard path. This does not emulate or claim native Windows SSH.
        let child = Command::new("sh")
            .args(["-c", &format!("exec {remote_arg}")])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .expect("spawn source lock transport");
        (child, bootstrap)
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn windows_source_lock_bootstrap_preserves_exclusion_eof_and_drop_release() {
        let _guard = test_guard!();
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().to_str().unwrap();
        let locks = vec![
            dir.path()
                .join("quote' %!& lock")
                .to_string_lossy()
                .into_owned(),
        ];
        let marker = "READY ' \" % ! & $()";
        let script =
            build_remote_source_authority_lock_cmd(root, &exclusive_source_locks(&locks), marker)
                .unwrap();
        let (child, bootstrap) = local_source_lock_transport(WorkerPlatform::Windows, &script);
        let mut first = finish_source_authority_lock_acquisition(
            child,
            WorkerId::new("windows-reader"),
            marker,
            bootstrap.as_deref(),
            TEST_LOCK_ACQUIRE_BUDGET,
        )
        .await
        .unwrap();
        first.ensure_held().unwrap();

        let (child, bootstrap) = local_source_lock_transport(WorkerPlatform::Posix, &script);
        let mut competing = Box::pin(finish_source_authority_lock_acquisition(
            child,
            WorkerId::new("posix-reader"),
            marker,
            bootstrap.as_deref(),
            TEST_LOCK_ACQUIRE_BUDGET,
        ));
        assert!(
            timeout(Duration::from_millis(100), &mut competing)
                .await
                .is_err()
        );
        first.ensure_held().unwrap();
        first.release().await.unwrap();
        let mut second = competing.await.unwrap();
        second.ensure_held().unwrap();
        drop(second);

        // Guard cancellation must close the inherited pipe as well: a fresh
        // Windows bootstrap acquires the same lock after the dropped owner.
        let (child, bootstrap) = local_source_lock_transport(WorkerPlatform::Windows, &script);
        let mut third = finish_source_authority_lock_acquisition(
            child,
            WorkerId::new("windows-after-drop"),
            marker,
            bootstrap.as_deref(),
            TEST_LOCK_ACQUIRE_BUDGET,
        )
        .await
        .unwrap();
        third.ensure_held().unwrap();
        third.release().await.unwrap();
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn windows_source_lock_bootstrap_failures_keep_stderr_and_reap_child() {
        let _guard = test_guard!();
        for (script, expected) in [
            (
                "printf 'lock refused\\n' >&2; exit 37",
                "exited before acquisition",
            ),
            (
                "printf 'lock refused\\n' >&2; printf 'WRONG\\n'; exec cat",
                "invalid ready marker",
            ),
        ] {
            let (child, bootstrap) = local_source_lock_transport(WorkerPlatform::Windows, script);
            let pid = child.id().unwrap();
            let result = finish_source_authority_lock_acquisition(
                child,
                WorkerId::new("windows-failure"),
                "READY",
                bootstrap.as_deref(),
                Duration::from_secs(3),
            )
            .await;
            let error = match result {
                Ok(_) => panic!("invalid holder must fail acquisition"),
                Err(error) => error.to_string(),
            };
            assert!(error.contains(expected), "{error}");
            assert!(error.contains("lock refused"), "{error}");
            assert!(
                !Path::new(&format!("/proc/{pid}")).exists(),
                "owned child must be reaped"
            );
        }
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn source_lock_bootstrap_and_readiness_share_deadline_and_reap_timeout() {
        let _guard = test_guard!();
        // A write larger than the pipe cannot finish until the first delay;
        // readiness follows a second delay. Each is below the one deadline,
        // but their sum exceeds it, catching a reset between write and read.
        let script = format!(
            "{}\nsleep 0.15; printf 'READY\\n'; exec cat",
            "#pad\n".repeat(18 * 1024)
        );
        let (_, bootstrap) = source_authority_lock_transport(WorkerPlatform::Windows, &script);
        let child = Command::new("sh")
            .args(["-c", "sleep 0.15; exec sh -s"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .unwrap();
        let pid = child.id().unwrap();
        let result = finish_source_authority_lock_acquisition(
            child,
            WorkerId::new("windows-deadline"),
            "READY",
            bootstrap.as_deref(),
            Duration::from_millis(250),
        )
        .await;
        let error = match result {
            Ok(_) => panic!("combined write/readiness deadline must not reset"),
            Err(error) => error.to_string(),
        };
        assert!(error.contains("timed out waiting"), "{error}");
        assert!(!Path::new(&format!("/proc/{pid}")).exists());
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn source_lock_bootstrap_write_is_bounded_when_child_never_reads() {
        let _guard = test_guard!();
        let child = Command::new("sh")
            .args(["-c", "exec sleep 60"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .unwrap();
        let pid = child.id().unwrap();
        let bootstrap = "x".repeat(1024 * 1024);
        let result = finish_source_authority_lock_acquisition(
            child,
            WorkerId::new("blocked-writer"),
            "READY",
            Some(&bootstrap),
            Duration::from_millis(100),
        )
        .await;
        let error = match result {
            Ok(_) => panic!("blocked bootstrap writer must time out"),
            Err(error) => error.to_string(),
        };
        assert!(error.contains("timed out waiting"), "{error}");
        assert!(!Path::new(&format!("/proc/{pid}")).exists());

        let child = Command::new("sh")
            .args(["-c", "exec sleep 60"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .unwrap();
        let pid = child.id().unwrap();
        let mut acquisition = Box::pin(finish_source_authority_lock_acquisition(
            child,
            WorkerId::new("cancelled-writer"),
            "READY",
            Some(&bootstrap),
            Duration::from_secs(60),
        ));
        // Poll the real acquisition while its large write and readiness are
        // pending. Cancelling an unpolled future would miss the drain/guard
        // ownership established inside the acquisition function.
        assert!(
            timeout(Duration::from_millis(50), &mut acquisition)
                .await
                .is_err()
        );
        assert!(Path::new(&format!("/proc/{pid}")).exists());
        drop(acquisition);
        timeout(Duration::from_secs(2), async {
            while Path::new(&format!("/proc/{pid}")).exists() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("cancelled acquisition must kill and reap its owned child");
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn disjoint_source_authorities_do_not_serialize() {
        let _guard = test_guard!();
        let locks = tempfile::tempdir().unwrap();
        let tmp_lock = locks.path().join("tmp.lock");
        let repo_lock = locks.path().join("repo.lock");
        let (mut first, first_ready) =
            spawn_local_source_lock(&tmp_lock.to_string_lossy(), "TMP_READY");
        let (mut second, second_ready) =
            spawn_local_source_lock(&repo_lock.to_string_lossy(), "REPO_READY");

        assert_eq!(
            first_ready
                .recv_timeout(Duration::from_secs(2))
                .expect("tmp authority acquisition")
                .expect("tmp ready line")
                .trim_end(),
            "TMP_READY"
        );
        assert_eq!(
            second_ready
                .recv_timeout(Duration::from_secs(2))
                .expect("disjoint authority must acquire concurrently")
                .expect("repo ready line")
                .trim_end(),
            "REPO_READY"
        );

        drop(first.stdin.take());
        drop(second.stdin.take());
        assert!(first.wait().expect("wait for tmp holder").success());
        assert!(second.wait().expect("wait for repo holder").success());
    }

    /// Platform-portable tempdir wrapper that canonicalizes its path
    /// (macOS resolves `/tmp` to `/private/tmp`).
    ///
    /// This is a local copy of the shared `topology_tempdir` helper in
    /// `hook::tests` (which serves the other ~26 topology tests). Keeping a
    /// private copy here lets the SSH tests stay self-contained without
    /// exposing the helper across module boundaries — the same pattern used
    /// for `create_test_state_dir` in the `auto_start` submodule.
    ///
    /// Gated `#[cfg(unix)]` because its only consumer here is the unix-only
    /// `..._treats_file_exists_race_as_success` test; without the gate it would
    /// be unused (dead_code → clippy `-D warnings`) on non-unix targets.
    #[cfg(unix)]
    struct CanonicalTempDir {
        _dir: tempfile::TempDir,
        path: PathBuf,
    }

    #[cfg(unix)]
    impl CanonicalTempDir {
        fn path(&self) -> &Path {
            &self.path
        }
    }

    #[cfg(unix)]
    fn topology_tempdir() -> (CanonicalTempDir, PathTopologyPolicy) {
        let raw = tempfile::tempdir().expect("create tempdir");
        let canonical = std::fs::canonicalize(raw.path()).expect("canonicalize tempdir");
        let alias_root = canonical
            .parent()
            .map(|parent| {
                let leaf = canonical
                    .file_name()
                    .and_then(|s| s.to_str())
                    .unwrap_or("tmp");
                parent.join(format!("{leaf}__rch_alias_sentinel"))
            })
            .unwrap_or_else(|| canonical.clone());
        let policy = PathTopologyPolicy::new(canonical.clone(), alias_root);
        (
            CanonicalTempDir {
                _dir: raw,
                path: canonical,
            },
            policy,
        )
    }

    #[test]
    fn isolated_staging_maps_worker_paths_without_changing_controller_policy() {
        let controller = PathTopologyPolicy::default();
        let base = "/Users/jemanuel/.cache/rch-release";
        let roots = vec![PathBuf::from(format!("{base}/asupersync/job-1"))];
        for (clean_overlay, source_content_receipt) in [(true, false), (false, true), (true, true)]
        {
            let staged = remote_preflight_topology_policy(
                &controller,
                clean_overlay,
                source_content_receipt,
                base,
                &roots,
            )
            .expect("Mac staging path is independent of Linux controller source path");
            assert_eq!(staged.canonical_root(), Path::new(base));
            assert_eq!(staged.alias_root(), staged.canonical_root());
            assert_eq!(controller.canonical_root(), Path::new("/data/projects"));
            assert_eq!(controller.alias_root(), Path::new("/dp"));
        }

        let ordinary = remote_preflight_topology_policy(
            &controller,
            false,
            false,
            base,
            &[PathBuf::from("/data/projects/asupersync")],
        )
        .expect("ordinary source mirrors retain the controller topology");
        assert_eq!(ordinary.canonical_root(), controller.canonical_root());
        assert_eq!(ordinary.alias_root(), controller.alias_root());
    }

    #[test]
    fn isolated_staging_refuses_every_destination_outside_the_exact_base() {
        let controller = PathTopologyPolicy::default();
        let base = "/Users/jemanuel/.cache/rch-release";
        let valid = PathBuf::from(format!("{base}/asupersync/job-1"));
        for (clean_overlay, source_content_receipt) in [(true, false), (false, true), (true, true)]
        {
            for invalid in [
                base.to_string(),
                format!("{base}-peer/asupersync/job-1"),
                format!("{base}/../peer/job-1"),
                format!("{base}/asupersync/../../peer"),
                format!("{base}/./asupersync/job-1"),
                format!("{base}/asupersync/evil\npath"),
                format!("{base}/asupersync\\peer"),
                "/data/projects/asupersync".to_string(),
                "asupersync/job-1".to_string(),
            ] {
                let roots = vec![valid.clone(), PathBuf::from(&invalid)];
                assert!(
                    remote_preflight_topology_policy(
                        &controller,
                        clean_overlay,
                        source_content_receipt,
                        base,
                        &roots,
                    )
                    .is_err(),
                    "a valid first root must not hide invalid destination {invalid:?}"
                );
            }
            assert!(
                remote_preflight_topology_policy(
                    &controller,
                    clean_overlay,
                    source_content_receipt,
                    base,
                    &[],
                )
                .is_err()
            );
            for invalid_base in [
                "/",
                "/tmp",
                "relative/base",
                "/tmp/rch/../peer",
                "/tmp/rch\n",
            ] {
                assert!(
                    remote_preflight_topology_policy(
                        &controller,
                        clean_overlay,
                        source_content_receipt,
                        invalid_base,
                        std::slice::from_ref(&valid),
                    )
                    .is_err(),
                    "invalid staging base {invalid_base:?} must refuse before any remote command"
                );
            }
        }
    }

    #[cfg(unix)]
    #[test]
    fn isolated_staging_preflight_creates_only_its_base_without_an_alias() {
        let _guard = test_guard!();
        for (clean_overlay, source_content_receipt) in [(true, false), (false, true), (true, true)]
        {
            let raw = tempfile::tempdir().expect("owned topology fixture");
            let fixture = raw.path().canonicalize().expect("physical fixture path");
            let controller_root = fixture.join("controller-projects");
            let controller_alias = fixture.join("controller-alias");
            // Both controller paths are intentionally unusable as worker topology.
            // The old preflight would refuse this regular-file canonical root.
            std::fs::write(&controller_root, b"controller source must stay untouched")
                .expect("controller sentinel");
            std::fs::write(&controller_alias, b"peer alias must stay untouched")
                .expect("peer alias sentinel");
            let controller =
                PathTopologyPolicy::new(controller_root.clone(), controller_alias.clone());
            let staging_base = fixture.join("worker staging");
            let source_roots = [
                staging_base.join("asupersync/job-1"),
                staging_base.join("asupersync/dependency-1"),
            ];
            let staged = remote_preflight_topology_policy(
                &controller,
                clean_overlay,
                source_content_receipt,
                staging_base.to_str().expect("UTF-8 fixture path"),
                &source_roots,
            )
            .expect("valid isolated staging topology");
            let command = build_worker_projects_topology_cmd(&staged, true);
            for _ in 0..2 {
                let output = std::process::Command::new("sh")
                    .args(["-c", &command])
                    .output()
                    .expect("execute actual topology shell command");
                assert!(
                    output.status.success(),
                    "staging preflight failed: status={:?}, stdout={}, stderr={}",
                    output.status.code(),
                    String::from_utf8_lossy(&output.stdout),
                    String::from_utf8_lossy(&output.stderr)
                );
                assert!(String::from_utf8_lossy(&output.stdout).contains("RCH_TOPOLOGY_OK"));
                assert!(staging_base.is_dir());
                assert!(
                    !staging_base.is_symlink(),
                    "alias==canonical stays a directory"
                );
                assert!(
                    source_roots.iter().all(|root| !root.exists()),
                    "preflight only prepares the staging base"
                );
                assert_eq!(
                    std::fs::read(&controller_root).expect("controller sentinel survives"),
                    b"controller source must stay untouched"
                );
                assert_eq!(
                    std::fs::read(&controller_alias).expect("peer alias sentinel survives"),
                    b"peer alias must stay untouched"
                );
                assert_eq!(
                    std::fs::read_dir(&fixture)
                        .expect("fixture entries")
                        .count(),
                    3,
                    "preflight must not create another alias or touch a peer tree"
                );
            }
        }
    }

    #[test]
    fn test_build_remote_shell_command_wraps_and_escapes_script() {
        let _guard = test_guard!();
        let command = "missing=0; if [ \"$missing\" -ne 0 ]; then echo 'bad'; fi";

        let wrapped = build_remote_shell_command(WorkerPlatform::Posix, command);

        assert!(wrapped.starts_with("sh -lc "));
        assert!(
            wrapped.starts_with("sh -lc '"),
            "shell wrapper must quote the script as a single argument"
        );
        assert!(
            !wrapped.starts_with("sh -lc missing=0"),
            "script must not be passed unquoted"
        );
        assert!(
            wrapped.contains("if ["),
            "wrapped command should preserve the full script"
        );
    }

    #[test]
    fn test_windows_stdin_reader_avoids_login_but_scripts_remain_quoted() {
        let _guard = test_guard!();
        let script = "printf '%s\\n' 'C:/rch/a b/Cargo.toml'; exit 43";

        assert_eq!(
            build_remote_shell_command(WorkerPlatform::Windows, "sh -s"),
            "sh -s"
        );
        assert_eq!(
            build_remote_shell_command(WorkerPlatform::Windows, script),
            format!("sh -lc {}", shell_escape::escape(script.into()))
        );

        assert_eq!(
            build_remote_shell_command(WorkerPlatform::Posix, "sh -s"),
            "sh -lc 'sh -s'"
        );
    }

    #[test]
    fn test_build_worker_projects_topology_cmd_uses_supplied_policy() {
        let _guard = test_guard!();
        let policy = PathTopologyPolicy::new(
            PathBuf::from("/custom/projects"),
            PathBuf::from("/custom/dp"),
        );

        let command = build_worker_projects_topology_cmd(&policy, true);

        assert!(
            command.contains("/custom/projects"),
            "preflight command must use the supplied canonical root: {command}"
        );
        assert!(
            command.contains("/custom/dp"),
            "preflight command must use the supplied alias root: {command}"
        );
        assert!(
            !command.contains("/data/projects"),
            "preflight command must not silently fall back to default canonical root: {command}"
        );
    }

    #[test]
    fn test_build_worker_projects_topology_cmd_shell_escapes_policy_paths() {
        let _guard = test_guard!();
        let policy = PathTopologyPolicy::new(
            PathBuf::from("/tmp/rch weird'root"),
            PathBuf::from("/tmp/rch alias;bad"),
        );

        let command = build_worker_projects_topology_cmd(&policy, true);

        assert!(
            command.contains("'/tmp/rch weird'\\''root'"),
            "single quotes in canonical root must be shell escaped: {command}"
        );
        assert!(
            command.contains("'/tmp/rch alias;bad'"),
            "shell metacharacters in alias root must be quoted: {command}"
        );
    }

    #[test]
    fn test_build_worker_projects_topology_cmd_terminates_path_options() {
        let _guard = test_guard!();
        let policy = PathTopologyPolicy::new(
            PathBuf::from("-custom/projects"),
            PathBuf::from("-custom/dp"),
        );
        let canonical =
            shell_escape::escape(std::borrow::Cow::from("-custom/projects")).to_string();
        let alias = shell_escape::escape(std::borrow::Cow::from("-custom/dp")).to_string();

        let command = build_worker_projects_topology_cmd(&policy, true);

        assert!(
            command.contains(&format!("mkdir -p -- {canonical}")),
            "mkdir must terminate options before configured paths: {command}"
        );
        assert!(
            command.contains(&format!("readlink -- {alias}")),
            "readlink must terminate options before configured paths: {command}"
        );
        assert!(
            !command.contains("ln -sfn"),
            "build preflight must never retarget an existing alias: {command}"
        );
        assert!(
            command.contains(&format!("ln -s -- {canonical} {alias}")),
            "ln create must terminate options before configured paths: {command}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn topology_initialization_requires_the_planned_grant_and_probe_is_read_only() {
        let _guard = test_guard!();
        let directory = tempfile::tempdir().unwrap().keep();
        let canonical = directory.join("canonical");
        let alias = directory.join("alias");
        let policy = PathTopologyPolicy::new(canonical.clone(), alias.clone());
        let run = |command: String| {
            std::process::Command::new("sh")
                .args(["-c", &command])
                .output()
                .unwrap()
        };

        let probe = run(build_worker_projects_topology_probe_cmd(&policy));
        assert!(probe.status.success());
        assert_eq!(probe.stdout, b"RCH_TOPOLOGY_INITIALIZATION_REQUIRED\n");
        assert!(!canonical.exists() && !alias.exists());
        let denied = run(build_worker_projects_topology_cmd(&policy, false));
        assert_eq!(denied.status.code(), Some(48));
        assert!(!canonical.exists() && !alias.exists());

        std::fs::create_dir(&canonical).unwrap();
        let probe = run(build_worker_projects_topology_probe_cmd(&policy));
        assert!(probe.status.success());
        assert_eq!(probe.stdout, b"RCH_TOPOLOGY_INITIALIZATION_REQUIRED\n");
        let denied = run(build_worker_projects_topology_cmd(&policy, false));
        assert_eq!(denied.status.code(), Some(48));
        assert!(!alias.exists() && !alias.is_symlink());
        assert_eq!(std::fs::read_dir(&canonical).unwrap().count(), 0);

        let initialized = run(build_worker_projects_topology_cmd(&policy, true));
        assert!(
            initialized.status.success(),
            "{}",
            String::from_utf8_lossy(&initialized.stderr)
        );
        assert_eq!(std::fs::read_link(&alias).unwrap(), canonical);
        let probe = run(build_worker_projects_topology_probe_cmd(&policy));
        assert!(probe.status.success());
        assert_eq!(probe.stdout, b"RCH_TOPOLOGY_PATHS_PRESENT\n");
        let healthy = run(build_worker_projects_topology_cmd(&policy, false));
        assert!(healthy.status.success());
        assert_eq!(healthy.stdout, b"RCH_TOPOLOGY_OK\n");
    }

    #[cfg(unix)]
    #[test]
    fn topology_preflight_never_retargets_an_existing_source_alias() {
        let _guard = test_guard!();
        let directory = tempfile::tempdir().unwrap().keep();
        let canonical = directory.join("new canonical");
        let previous = directory.join("existing sources");
        let alias = directory.join("alias");
        std::fs::create_dir(&canonical).unwrap();
        std::fs::create_dir(&previous).unwrap();
        std::fs::write(previous.join("input"), b"old reader's source\n").unwrap();
        std::os::unix::fs::symlink(&previous, &alias).unwrap();
        let policy = PathTopologyPolicy::new(canonical, alias.clone());

        for allow_initialization in [false, true] {
            let output = std::process::Command::new("sh")
                .args([
                    "-c",
                    &build_worker_projects_topology_cmd(&policy, allow_initialization),
                ])
                .output()
                .unwrap();
            assert_eq!(output.status.code(), Some(43));
            assert!(
                String::from_utf8_lossy(&output.stderr)
                    .contains("RCH_TOPOLOGY_ERR_ALIAS_TARGET_CONFLICT")
            );
            assert_eq!(std::fs::read_link(&alias).unwrap(), previous);
            assert_eq!(
                std::fs::read(alias.join("input")).unwrap(),
                b"old reader's source\n"
            );
        }
    }

    #[test]
    fn test_build_worker_ownership_repair_cmd_scopes_and_never_deletes() {
        let _guard = test_guard!();
        let command = build_worker_ownership_repair_cmd(
            &[
                PathBuf::from("/data/projects"),
                PathBuf::from("/data/projects/franken_node"),
            ],
            "deploy-user",
        );

        assert!(
            command.contains("'--user root'") || command.contains("-user root"),
            "sweep must target root-owned entries only: {command}"
        );
        assert!(
            command.contains("for r in /data/projects /data/projects/franken_node"),
            "every dispatch closure root binds into the sweep loop: {command}"
        );
        let spaced = build_worker_ownership_repair_cmd(
            &[PathBuf::from("/data/projects with space")],
            "deploy u",
        );
        assert!(
            spaced.contains("for r in '/data/projects with space'")
                && spaced.contains("u='deploy u'"),
            "paths or users with shell metacharacters must be single-quote escaped: {spaced}"
        );
        assert!(
            command.contains("-xdev"),
            "sweep must not cross filesystem boundaries: {command}"
        );
        assert!(
            command.contains("-exec chown -h"),
            "repair must chown links themselves without following them: {command}"
        );
        assert!(
            !command.contains(" rm ") && !command.contains("rm -"),
            "repair must never delete anything (bd-8iwkm constraint): {command}"
        );
        assert!(
            command.contains("RCH_OWNERSHIP_OK")
                && command.contains("RCH_OWNERSHIP_REPAIRED:count=")
                && command.contains("exit 46")
                && command.contains("exit 47"),
            "all outcome markers and the 46/47 exit codes must be present: {command}"
        );
    }

    #[test]
    fn test_build_worker_projects_topology_cmd_rechecks_alias_after_create_race() {
        let _guard = test_guard!();
        let policy = PathTopologyPolicy::new(
            PathBuf::from("/custom/projects"),
            PathBuf::from("/custom/dp"),
        );
        let canonical =
            shell_escape::escape(std::borrow::Cow::from("/custom/projects")).to_string();
        let alias = shell_escape::escape(std::borrow::Cow::from("/custom/dp")).to_string();

        let command = build_worker_projects_topology_cmd(&policy, true);

        assert!(
            command.contains(&format!(
                "create_stderr=$(ln -s -- {canonical} {alias} 2>&1) && return 0"
            )),
            "create path must handle normal symlink creation inside the alias helper: {command}"
        );
        assert!(
            command.contains(&format!(
                "if [ -L {alias} ]; then ensure_alias_symlink; return $?; fi"
            )),
            "failed create must re-check alias state so a concurrent correct symlink is harmless: {command}"
        );
        assert!(
            command.contains("RCH_TOPOLOGY_ERR_ALIAS_NOT_SYMLINK"),
            "regular-file alias conflicts must still fail with a structured reason: {command}"
        );
        assert!(
            command.contains("RCH_TOPOLOGY_ERR_ALIAS_CREATE_FAILED"),
            "missing-alias create failures must report a structured reason: {command}"
        );
        assert!(
            command.contains(&format!(
                "printf 'RCH_TOPOLOGY_ERR_ALIAS_CREATE_FAILED:path=%s:target=%s:%s\\n' {alias} {canonical} \"$create_stderr\""
            )),
            "missing-alias create failures must report the exact alias and canonical paths: {command}"
        );
        assert!(
            command.contains(&format!(
                "printf 'RCH_TOPOLOGY_ERR_ALIAS_TARGET_CONFLICT:path=%s:target=%s:expected=%s\\n' {alias} \"$target\" {canonical}"
            )),
            "alias conflicts must report the current target without rewriting it: {command}"
        );
        assert!(
            command.contains(&format!(
                "printf 'RCH_TOPOLOGY_ERR_CANONICAL_CREATE_FAILED:path=%s:%s\\n' {canonical} \"$mkdir_stderr\""
            )),
            "canonical mkdir failures must report the exact canonical path: {command}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_build_worker_projects_topology_cmd_treats_file_exists_race_as_success() {
        let _guard = test_guard!();
        use std::os::unix::fs::PermissionsExt;

        let (temp_dir, policy) = topology_tempdir();
        let fake_bin = temp_dir.path().join("fake-bin");
        std::fs::create_dir_all(&fake_bin).expect("create fake bin dir");
        let fake_ln = fake_bin.join("ln");
        std::fs::write(
            &fake_ln,
            "#!/bin/sh\n\
if [ \"$1\" = \"-s\" ] && [ \"$2\" = \"--\" ]; then\n\
  /bin/ln -s \"$3\" \"$4\" 2>/dev/null || true\n\
  echo \"ln: failed to create symbolic link '$4': File exists\" >&2\n\
  exit 1\n\
fi\n\
exec /bin/ln \"$@\"\n",
        )
        .expect("write fake ln");
        let mut perms = std::fs::metadata(&fake_ln)
            .expect("fake ln metadata")
            .permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&fake_ln, perms).expect("chmod fake ln");

        let command = build_worker_projects_topology_cmd(&policy, true);
        let path = format!(
            "{}:{}",
            fake_bin.display(),
            std::env::var("PATH").unwrap_or_default()
        );
        let output = std::process::Command::new("sh")
            .arg("-c")
            .arg(command)
            .env("PATH", path)
            .output()
            .expect("run topology command");

        assert!(
            output.status.success(),
            "file-exists create race should be harmless; status={:?} stdout={} stderr={}",
            output.status.code(),
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(
            String::from_utf8_lossy(&output.stdout).contains("RCH_TOPOLOGY_OK"),
            "successful preflight should emit OK"
        );
        assert_eq!(
            std::fs::read_link(policy.alias_root()).expect("alias symlink target"),
            policy.canonical_root().to_path_buf()
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_build_worker_projects_topology_cmd_reports_alias_create_collision_path() {
        let _guard = test_guard!();
        use std::os::unix::fs::PermissionsExt;

        let temp_dir = tempfile::tempdir().expect("temp dir");
        let sentinel = temp_dir.path().join("diagnostic-substitution-ran");
        let policy = PathTopologyPolicy::new(
            temp_dir.path().join("projects"),
            temp_dir
                .path()
                .join(format!("dp_$(touch {})", sentinel.display())),
        );
        let fake_bin = temp_dir.path().join("fake-bin");
        std::fs::create_dir_all(&fake_bin).expect("create fake bin dir");
        let fake_ln = fake_bin.join("ln");
        std::fs::write(
            &fake_ln,
            "#!/bin/sh\n\
if [ \"$1\" = \"-s\" ] && [ \"$2\" = \"--\" ]; then\n\
  echo \"ln: Already exists\" >&2\n\
  exit 1\n\
fi\n\
exec /bin/ln \"$@\"\n",
        )
        .expect("write fake ln");
        let mut perms = std::fs::metadata(&fake_ln)
            .expect("fake ln metadata")
            .permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&fake_ln, perms).expect("chmod fake ln");

        let command = build_worker_projects_topology_cmd(&policy, true);
        let path = format!(
            "{}:{}",
            fake_bin.display(),
            std::env::var("PATH").unwrap_or_default()
        );
        let output = std::process::Command::new("sh")
            .arg("-c")
            .arg(command)
            .env("PATH", path)
            .output()
            .expect("run topology command");
        let stderr = String::from_utf8_lossy(&output.stderr);

        assert!(
            !output.status.success(),
            "unresolved alias create collision should fail"
        );
        assert!(
            stderr.contains("RCH_TOPOLOGY_ERR_ALIAS_CREATE_FAILED"),
            "stderr should keep a structured failure code: {stderr}"
        );
        assert!(
            stderr.contains(&format!("path={}", policy.alias_root().display())),
            "stderr should include the exact colliding alias path: {stderr}"
        );
        assert!(
            stderr.contains("$(touch "),
            "stderr should include the literal configured path: {stderr}"
        );
        assert!(
            stderr.contains(&format!("target={}", policy.canonical_root().display())),
            "stderr should include the intended canonical target: {stderr}"
        );
        assert!(
            stderr.contains("ln: Already exists"),
            "stderr should preserve the underlying ln diagnostic: {stderr}"
        );
        assert!(
            !sentinel.exists(),
            "diagnostic formatting must not re-expand command substitutions from configured paths"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_build_worker_projects_topology_cmd_accepts_resolved_alias_target() {
        let _guard = test_guard!();
        use std::os::unix::fs::symlink;

        let temp_dir = tempfile::tempdir().expect("temp dir");
        let real_root = temp_dir.path().join("data/projects");
        let configured_root = temp_dir.path().join("Users/jemanuel/projects");
        let alias_root = temp_dir.path().join("dp");
        std::fs::create_dir_all(&real_root).expect("create real root");
        std::fs::create_dir_all(configured_root.parent().expect("configured parent"))
            .expect("create configured parent");
        symlink(&real_root, &configured_root).expect("create configured canonical symlink");
        symlink(&real_root, &alias_root).expect("create alias symlink");

        let policy = PathTopologyPolicy::new(configured_root.clone(), alias_root.clone());
        let output = std::process::Command::new("sh")
            .arg("-lc")
            .arg(build_worker_projects_topology_cmd(&policy, true))
            .output()
            .expect("run topology command");

        assert!(
            output.status.success(),
            "resolved alias target should be accepted; status={:?} stdout={} stderr={}",
            output.status.code(),
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(
            String::from_utf8_lossy(&output.stdout).contains("RCH_TOPOLOGY_OK"),
            "successful preflight should emit OK"
        );
        assert_eq!(
            std::fs::read_link(&alias_root).expect("alias symlink target"),
            real_root,
            "alias should not be rewritten when it resolves to the configured canonical root"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_build_worker_projects_topology_cmd_accepts_identity_policy() {
        let _guard = test_guard!();

        // rch#32: an identity policy (alias root == canonical root, a plain
        // directory) is accepted host-side, so the worker preflight must accept it
        // too — a non-symlink alias whose realpath equals canonical is satisfied,
        // not refused with RCH_TOPOLOGY_ERR_ALIAS_NOT_SYMLINK on every worker.
        let temp_dir = tempfile::tempdir().expect("temp dir");
        let root = temp_dir.path().join("scratch");
        std::fs::create_dir_all(&root).expect("create root");

        let policy = PathTopologyPolicy::new(root.clone(), root.clone());
        let output = std::process::Command::new("sh")
            .arg("-lc")
            .arg(build_worker_projects_topology_cmd(&policy, true))
            .output()
            .expect("run topology command");

        assert!(
            output.status.success(),
            "identity policy (alias == canonical directory) must be accepted; status={:?} stdout={} stderr={}",
            output.status.code(),
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(
            String::from_utf8_lossy(&output.stdout).contains("RCH_TOPOLOGY_OK"),
            "identity policy preflight should emit OK, not a per-worker refusal"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_build_worker_projects_topology_cmd_still_refuses_unrelated_dir_alias() {
        let _guard = test_guard!();

        // The realpath-equality relaxation must NOT admit a non-symlink alias that
        // resolves somewhere OTHER than canonical — that stays a structured exit-42.
        let temp_dir = tempfile::tempdir().expect("temp dir");
        let canonical = temp_dir.path().join("canonical");
        let alias = temp_dir.path().join("alias");
        std::fs::create_dir_all(&canonical).expect("create canonical");
        std::fs::create_dir_all(&alias).expect("create unrelated alias dir");

        let policy = PathTopologyPolicy::new(canonical, alias);
        let output = std::process::Command::new("sh")
            .arg("-lc")
            .arg(build_worker_projects_topology_cmd(&policy, true))
            .output()
            .expect("run topology command");

        assert!(
            !output.status.success(),
            "an unrelated non-symlink alias directory must still be refused"
        );
        assert_eq!(output.status.code(), Some(42));
        assert!(
            String::from_utf8_lossy(&output.stderr).contains("RCH_TOPOLOGY_ERR_ALIAS_NOT_SYMLINK"),
            "refusal must keep its structured error code"
        );
    }

    #[test]
    fn test_parse_ownership_detect_output_classifies_all_contract_paths() {
        let _guard = test_guard!();

        assert_eq!(
            parse_ownership_detect_output(true, "RCH_OWNERSHIP_OK\n", ""),
            MirrorOwnershipProbe::Healthy
        );
        assert_eq!(
            parse_ownership_detect_output(true, "RCH_OWNERSHIP_DRIFT:count=7\n", ""),
            MirrorOwnershipProbe::Drift { count: 7 }
        );
        assert_eq!(
            parse_ownership_detect_output(true, "", "RCH_OWNERSHIP_CHECK_UNAVAILABLE\n"),
            MirrorOwnershipProbe::CheckUnavailable
        );
        // Non-zero exit is unprobeable even when a sentinel also appears —
        // `set -e` means the script never intends a non-zero exit.
        assert!(matches!(
            parse_ownership_detect_output(false, "", "boom"),
            MirrorOwnershipProbe::Unprobeable(_)
        ));
        // Unrecognized stdout with exit 0 is honestly unprobeable too.
        assert!(matches!(
            parse_ownership_detect_output(true, "hello?", ""),
            MirrorOwnershipProbe::Unprobeable(_)
        ));
    }

    #[test]
    fn test_build_worker_ownership_detect_cmd_is_read_only_and_escapes_root() {
        let _guard = test_guard!();

        let weird = PathBuf::from("/tmp/rch own';root");
        let cmd = build_worker_ownership_detect_cmd(&weird);

        assert!(
            !cmd.contains("chown"),
            "detect command must never mutate worker state: {cmd}"
        );
        assert!(
            !cmd.contains("rm "),
            "detect command must never delete: {cmd}"
        );
        assert!(
            cmd.contains("sudo -n find \"$r\" -xdev -user root -print"),
            "detect command must only count root-owned entries: {cmd}"
        );
        assert!(
            cmd.contains("'\\''"),
            "shell metacharacters in the configured root must be escaped: {cmd}"
        );

        // The generated script must execute as valid shell. Run it against
        // a tempdir root; depending on whether passwordless sudo exists in
        // this environment it either reports OK/DRIFT or CHECK_UNAVAILABLE,
        // but it must always exit 0 (fail-open contract).
        let scratch = tempfile::tempdir().expect("temp dir");
        std::fs::write(scratch.path().join("marker"), b"x").expect("write marker");
        let output = std::process::Command::new("sh")
            .arg("-lc")
            .arg(build_worker_ownership_detect_cmd(scratch.path()))
            .output()
            .expect("run detect command locally");
        assert_eq!(
            output.status.code(),
            Some(0),
            "detect command is fail-open; status={:?} stderr={}",
            output.status.code(),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[cfg(unix)]
    async fn source_lock_pending_release_fixture() -> (
        RemoteSourceAuthorityLock,
        Vec<tokio::io::DuplexStream>,
        Vec<tokio::sync::oneshot::Receiver<()>>,
    ) {
        struct ReaderDropped(Option<tokio::sync::oneshot::Sender<()>>);
        impl Drop for ReaderDropped {
            fn drop(&mut self) {
                if let Some(sender) = self.0.take() {
                    let _ = sender.send(());
                }
            }
        }

        let mut child = Command::new("/bin/sh")
            .args(["-c", "exit 0"])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .kill_on_drop(true)
            .spawn()
            .unwrap();
        // Establish the exact regression boundary: SSH already exited, but
        // both reader pipes remain open as if inherited by descendants.
        assert!(child.wait().await.unwrap().success());
        let mut writers = Vec::new();
        let mut notices = Vec::new();
        let mut tasks = Vec::new();
        for _ in 0..2 {
            let (reader, writer) = tokio::io::duplex(16);
            let (sender, notice) = tokio::sync::oneshot::channel();
            let dropped = ReaderDropped(Some(sender));
            tasks.push(tokio::spawn(async move {
                let _dropped = dropped;
                crate::transfer::read_bounded_output_stream(reader, MAX_SOURCE_LOCK_OUTPUT_BYTES)
                    .await
            }));
            writers.push(writer);
            notices.push(notice);
        }
        let stderr_drain = tasks.pop();
        let stdout_drain = tasks.pop();
        (
            RemoteSourceAuthorityLock {
                worker_id: WorkerId::new("pending-lock-release"),
                child: Some(child),
                stdin: None,
                stdout_drain,
                stderr_drain,
                release_request: None,
                pair_root: None,
            },
            writers,
            notices,
        )
    }

    #[cfg(unix)]
    async fn source_lock_assert_readers_dropped(notices: Vec<tokio::sync::oneshot::Receiver<()>>) {
        for notice in notices {
            timeout(Duration::from_secs(1), notice)
                .await
                .expect("release detached an output reader")
                .expect("reader drop notification lost");
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn source_lock_lifecycle_release_deadline_includes_eof_after_child_exit() {
        let (guard, _writers, notices) = source_lock_pending_release_fixture().await;
        let error = timeout(
            Duration::from_secs(1),
            guard.release_with_timeout(Duration::from_millis(40)),
        )
        .await
        .expect("release ignored its deadline after child exit")
        .unwrap_err();
        assert!(
            error.to_string().contains("timed out releasing"),
            "{error:#}"
        );
        source_lock_assert_readers_dropped(notices).await;
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn source_lock_lifecycle_release_surfaces_stderr_error_without_waiting_for_stdout() {
        let (mut guard, _writers, notices) = source_lock_pending_release_fixture().await;
        guard.stderr_drain.take().unwrap().abort();
        guard.stderr_drain = Some(tokio::spawn(async {
            Err(std::io::Error::other("injected lock stderr failure"))
        }));
        let error = timeout(
            Duration::from_secs(1),
            guard.release_with_timeout(Duration::from_secs(60)),
        )
        .await
        .expect("stderr failure was hidden behind a pending stdout reader")
        .unwrap_err();
        assert!(error.to_string().contains("injected lock stderr failure"));
        source_lock_assert_readers_dropped(notices).await;
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn source_lock_lifecycle_caller_cancellation_aborts_both_release_readers() {
        let (guard, _writers, notices) = source_lock_pending_release_fixture().await;
        let mut release = Box::pin(guard.release_with_timeout(Duration::from_secs(60)));
        assert!(
            timeout(Duration::from_millis(40), &mut release)
                .await
                .is_err()
        );
        drop(release);
        source_lock_assert_readers_dropped(notices).await;
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn source_lock_lifecycle_release_requires_complete_ack_and_successful_exit() {
        for (reply, expected) in [
            ("printf '%s\\n' \"$request\"", true),
            ("printf '%s' \"$request\"", false),
            ("printf 'WRONG\\n'", false),
            ("printf '%s\\n' \"$request\" \"$request\"", false),
            ("printf '%s\\n' \"$request\"; exit 37", false),
        ] {
            let script = format!("printf 'READY\\n'; IFS= read -r request; {reply}");
            let child = Command::new("/bin/sh")
                .args(["-c", &script])
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .kill_on_drop(true)
                .spawn()
                .unwrap();
            let mut guard = finish_source_authority_lock_acquisition(
                child,
                WorkerId::new("lock-ack-fixture"),
                "READY",
                None,
                Duration::from_secs(2),
            )
            .await
            .unwrap();
            guard.release_request = Some("RELEASE".to_owned());
            let result = guard.release_with_timeout(Duration::from_secs(2)).await;
            assert_eq!(result.is_ok(), expected, "{reply}: {result:?}");
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn source_lock_lifecycle_readiness_refuses_truncated_padded_and_oversized_frames() {
        for script in [
            "printf READY".to_owned(),
            "printf 'READY \\n'; exec cat".to_owned(),
            format!(
                "printf %s {}; exec cat",
                "x".repeat(MAX_SOURCE_LOCK_READY_BYTES + 1)
            ),
        ] {
            let child = Command::new("/bin/sh")
                .args(["-c", &script])
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .kill_on_drop(true)
                .spawn()
                .unwrap();
            let result = timeout(
                Duration::from_secs(2),
                finish_source_authority_lock_acquisition(
                    child,
                    WorkerId::new("invalid-lock-ready"),
                    "READY",
                    None,
                    Duration::from_secs(60),
                ),
            )
            .await
            .expect("invalid readiness waited for EOF or the acquisition timeout");
            assert!(
                result.is_err(),
                "invalid readiness authorized a source writer"
            );
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn source_lock_lifecycle_stdout_overflow_cannot_certify_release() {
        let script = format!(
            "printf 'READY\\n'; IFS= read -r request; head -c {} /dev/zero; exit 0",
            MAX_SOURCE_LOCK_OUTPUT_BYTES + 1
        );
        let child = Command::new("/bin/sh")
            .args(["-c", &script])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .unwrap();
        let mut guard = finish_source_authority_lock_acquisition(
            child,
            WorkerId::new("oversized-lock-output"),
            "READY",
            None,
            Duration::from_secs(2),
        )
        .await
        .unwrap();
        guard.release_request = Some("RELEASE".to_owned());
        let error = guard
            .release_with_timeout(Duration::from_secs(2))
            .await
            .unwrap_err();
        assert!(error.to_string().contains("exceeded"), "{error:#}");
    }

    #[test]
    fn source_lock_scaling_rejects_ambiguous_path_records() {
        assert!(build_remote_source_authority_lock_cmd("/tmp", &[], "READY").is_err());
        for path in ["relative", "/tmp/a\n/tmp/b", "/tmp/a\r", "/tmp/a\0b"] {
            let paths = vec!["/tmp/valid".to_owned(), path.to_owned()];
            assert!(
                build_remote_source_authority_lock_cmd(
                    "/tmp",
                    &exclusive_source_locks(&paths),
                    "READY"
                )
                .is_err()
            );
        }
        let duplicate = vec!["/tmp/same".to_owned(); 2];
        assert!(
            build_remote_source_authority_lock_cmd(
                "/tmp",
                &exclusive_source_locks(&duplicate),
                "READY"
            )
            .is_err()
        );
        for marker in ["", "READY\nFORGED", "READY\r", "READY\0"] {
            assert!(
                build_remote_source_authority_lock_cmd(
                    "/tmp",
                    &exclusive_source_locks(&["/tmp/one".into()]),
                    marker
                )
                .is_err()
            );
        }
    }

    #[cfg(target_os = "linux")]
    async fn source_lock_scaling_is_held(path: &str) -> bool {
        let output = timeout(
            Duration::from_secs(5),
            Command::new("flock")
                .args(["-n", "-x", "--", path, "sh", "-c", "exit 0"])
                .stdin(Stdio::null())
                .kill_on_drop(true)
                .output(),
        )
        .await
        .expect("independent nonblocking lock probe hung")
        .unwrap();
        assert!(matches!(output.status.code(), Some(0 | 1)), "{output:?}");
        output.status.code() == Some(1)
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn source_lock_scaling_streams_548_roots_and_preserves_exclusion() {
        let dir = tempfile::tempdir().unwrap().keep();
        let lock_dir = dir.join("d".repeat(100));
        std::fs::create_dir_all(&lock_dir).unwrap();
        let mut locks = (0..548)
            .map(|index| {
                lock_dir
                    .join(format!("{index:04}-{}.lock", "k".repeat(180)))
                    .display()
                    .to_string()
            })
            .collect::<Vec<_>>();
        locks[547] = lock_dir
            .join(format!("quote' $cash `literal`; {}", "z".repeat(170)))
            .display()
            .to_string();
        let marker = "READY ' \" $() ; `literal`";
        let script = build_remote_source_authority_lock_cmd(
            lock_dir.to_str().unwrap(),
            &exclusive_source_locks(&locks),
            marker,
        )
        .unwrap();
        assert!(script.len() > 128 * 1024);
        for platform in [WorkerPlatform::Posix, WorkerPlatform::Windows] {
            let (child, bootstrap) = local_source_lock_transport(platform, &script);
            let pid = child.id().unwrap();
            let mut first = finish_source_authority_lock_acquisition(
                child,
                WorkerId::new("large-closure"),
                marker,
                bootstrap.as_deref(),
                Duration::from_secs(20),
            )
            .await
            .unwrap();
            first.ensure_held().unwrap();
            // No nesting of live flock parents: the original process becomes
            // the final stdin holder. A shell may retain one heredoc helper.
            timeout(Duration::from_secs(3), async {
                loop {
                    if std::fs::read_link(format!("/proc/{pid}/exe"))
                        .ok()
                        .and_then(|path| path.file_name().map(|name| name == "cat"))
                        == Some(true)
                    {
                        break;
                    }
                    tokio::time::sleep(Duration::from_millis(10)).await;
                }
            })
            .await
            .expect("lock acquisition retained a flock process chain");
            for index in [0, 274, 547] {
                assert!(source_lock_scaling_is_held(&locks[index]).await);
            }
            assert!(
                !source_lock_scaling_is_held(dir.join("disjoint.lock").to_str().unwrap()).await
            );
            let overlap = build_remote_source_authority_lock_cmd(
                lock_dir.to_str().unwrap(),
                &exclusive_source_locks(std::slice::from_ref(&locks[547])),
                "SECOND",
            )
            .unwrap();
            let (child, bootstrap) = local_source_lock_transport(platform, &overlap);
            let mut second = Box::pin(finish_source_authority_lock_acquisition(
                child,
                WorkerId::new("overlapping-closure"),
                "SECOND",
                bootstrap.as_deref(),
                Duration::from_secs(20),
            ));
            assert!(
                timeout(Duration::from_millis(100), &mut second)
                    .await
                    .is_err()
            );
            first.release().await.unwrap();
            let second = second.await.unwrap();
            second.release().await.unwrap();
            for index in [0, 274, 547] {
                assert!(!source_lock_scaling_is_held(&locks[index]).await);
            }
        }
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn source_lock_scaling_descriptor_exhaustion_never_publishes_readiness() {
        let dir = tempfile::tempdir().unwrap().keep();
        let locks = (0..32)
            .map(|index| dir.join(format!("{index}.lock")).display().to_string())
            .collect::<Vec<_>>();
        let script = format!(
            "ulimit -n 16\n{}",
            build_remote_source_authority_lock_cmd(
                dir.to_str().unwrap(),
                &exclusive_source_locks(&locks),
                "READY"
            )
            .unwrap()
        );
        let (child, bootstrap) = local_source_lock_transport(WorkerPlatform::Posix, &script);
        let result = finish_source_authority_lock_acquisition(
            child,
            WorkerId::new("limited-descriptors"),
            "READY",
            bootstrap.as_deref(),
            Duration::from_secs(5),
        )
        .await;
        assert!(
            result.is_err(),
            "partial lock set must never authorize a source writer"
        );
        for path in &locks {
            assert!(!source_lock_scaling_is_held(path).await);
        }
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn source_lock_scaling_cancelled_acquisition_releases_its_prefix() {
        let dir = tempfile::tempdir().unwrap().keep();
        let a = dir.join("a.lock").display().to_string();
        let b = dir.join("b.lock").display().to_string();
        let first_script = build_remote_source_authority_lock_cmd(
            dir.to_str().unwrap(),
            &exclusive_source_locks(std::slice::from_ref(&b)),
            "FIRST",
        )
        .unwrap();
        let (child, bootstrap) = local_source_lock_transport(WorkerPlatform::Posix, &first_script);
        let first = finish_source_authority_lock_acquisition(
            child,
            WorkerId::new("blocking-owner"),
            "FIRST",
            bootstrap.as_deref(),
            Duration::from_secs(5),
        )
        .await
        .unwrap();
        let script = build_remote_source_authority_lock_cmd(
            dir.to_str().unwrap(),
            &exclusive_source_locks(&[a.clone(), b.clone()]),
            "SECOND",
        )
        .unwrap();
        let (child, bootstrap) = local_source_lock_transport(WorkerPlatform::Posix, &script);
        let mut second = Box::pin(finish_source_authority_lock_acquisition(
            child,
            WorkerId::new("partial-owner"),
            "SECOND",
            bootstrap.as_deref(),
            Duration::from_secs(20),
        ));
        timeout(Duration::from_secs(5), async {
            loop {
                assert!(
                    timeout(Duration::from_millis(50), &mut second)
                        .await
                        .is_err()
                );
                if source_lock_scaling_is_held(&a).await {
                    break;
                }
            }
        })
        .await
        .unwrap();
        drop(second);
        timeout(Duration::from_secs(5), async {
            while source_lock_scaling_is_held(&a).await {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("aborted acquisition leaked its partial lock set");
        assert!(source_lock_scaling_is_held(&b).await);
        first.release().await.unwrap();
        assert!(!source_lock_scaling_is_held(&b).await);
    }
}