rch 2.1.19

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
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
use super::*;
// Submodule helpers exercised directly by the hook test suite (the submodules
// keep them `pub(super)`; they are test-only so they are imported here rather
// than re-exported into the non-test hook namespace).
use super::artifact_patterns::{
    expected_output_glob_list, get_artifact_patterns, get_custom_target_artifact_patterns,
    get_project_artifact_patterns, kind_produces_transferable_artifacts,
    sync_back_verified_zero_build_outputs, sync_back_verified_zero_package_archives,
};
use super::cargo_target_dir::{
    extract_cargo_target_dir_from_command_tokens, feature_set_for_command,
    parse_stale_target_reap_idle_hours, remote_cargo_pooled_target_dir_name,
    remote_cargo_target_dir_name, resolve_forwarded_cargo_target_dir_with_lookup,
    strip_cargo_target_dir_assignments_from_command_tokens,
    strip_cargo_target_dir_flags_from_command_tokens, target_reuse_disabled_from_value,
    target_triple_for_command,
};
use super::command_parsing::{
    cargo_custom_profile_output_dir, has_exact_flag, has_ignored_only_flag,
    is_filtered_test_command, parse_jobs_flag, parse_test_threads,
};
use super::daemon_ipc::{
    DEFAULT_DAEMON_RESPONSE_TIMEOUT_SECS, DEFAULT_DAEMON_WAIT_RESPONSE_TIMEOUT_SECS,
    daemon_response_timeout_for, queue_when_busy_enabled_from, urlencoding_encode,
};
use super::dependency_closure::{
    DEPENDENCY_PREFLIGHT_CODE_MISSING, DEPENDENCY_PREFLIGHT_CODE_STALE,
    DEPENDENCY_PREFLIGHT_REMEDIATION_MISSING, DEPENDENCY_PREFLIGHT_REMEDIATION_STALE,
    DependencyPreflightCheck, SyncClosureMode, SyncClosurePlanEntry, SyncRootOutcome,
    build_dependency_preflight_report, build_remote_dependency_preflight_command,
    build_sync_closure_manifest, build_sync_closure_plan, canonicalize_sync_root_for_plan,
    cargo_package_source_entrypoints, cargo_workspace_member_source_entrypoints,
    dependency_preflight_checks_for_entry, dependency_preflight_timeout, is_within_sync_topology,
    parse_dependency_preflight_probe_output, synced_dependency_preflight_checks,
    verify_remote_dependency_manifests,
};
use super::fallback_selection::WorkerCapacitySnapshot;
use super::progress_reporting::BuildHeartbeatLoop;
use super::repo_updater::{
    auto_tune_repo_updater_contract, build_repo_sync_idempotency_key_for_command,
    collect_repo_updater_roots_and_specs, hydrate_repo_updater_auth_context_defaults,
    infer_repo_updater_auth_context_with_env_lookup, repo_updater_command_name,
};
use super::ssh::offload_remote_command_transport;
use super::timing_history::{
    MAX_TIMING_SAMPLES, ProjectTimingData, TimingEstimate, TimingHistory, TimingRecord,
    estimate_timing_for_build, record_build_timing, timing_cache,
};
use super::transfer_orchestration::{
    apply_source_sync_integrity_policy, source_sync_terminal_summary, wrap_command_with_telemetry,
};
use proptest::prelude::*;
use rch_common::mock::{
    self, MockConfig, MockRsyncConfig, clear_mock_overrides, set_mock_enabled_override,
    set_mock_rsync_config_override, set_mock_ssh_config_override,
};
use rch_common::test_guard;
use rch_common::{SelectionReason, TierDecision, ToolInput, classify_command_detailed};
use serial_test::serial;
use std::sync::OnceLock;
use tokio::io::BufReader as TokioBufReader;
use tokio::net::UnixListener;
use tokio::sync::Mutex;

#[tokio::test]
async fn queued_cancellation_replaces_hook_command_with_terminal_exit() {
    let reporter = HookReporter::new(OutputVisibility::None);
    let response = SelectionResponse {
        worker: None,
        reason: SelectionReason::SelectionError("job_cancelled_before_start".into()),
        build_id: None,
        diagnostics: None,
    };
    assert!(selection_cancelled_before_start(&response));
    let output = handle_selection_response(
        response,
        "cargo build",
        &rch_common::RchConfig::default(),
        &reporter,
        None,
        Some(CompilationKind::CargoBuild),
        "queued",
        2,
    )
    .await;
    assert_eq!(delegated_command(&output), "exit 130");
    let busy = SelectionResponse {
        worker: None,
        reason: SelectionReason::AllWorkersBusy,
        build_id: None,
        diagnostics: None,
    };
    assert!(!selection_cancelled_before_start(&busy));
}

fn delegated_command(output: &HookOutput) -> &str {
    if let HookOutput::AllowWithModifiedCommand(modified) = output {
        &modified.hook_specific_output.updated_input.command
    } else {
        assert!(
            matches!(output, HookOutput::AllowWithModifiedCommand(_)),
            "expected AllowWithModifiedCommand"
        );
        ""
    }
}

fn init_clean_overlay_test_repo() -> tempfile::TempDir {
    let temp = tempfile::tempdir().expect("create clean-overlay test repo");
    let root = temp.path();
    for args in [
        vec!["init", "-q"],
        vec!["config", "user.email", "rch-test@example.invalid"],
        vec!["config", "user.name", "RCH Test"],
    ] {
        let status = std::process::Command::new("git")
            .current_dir(root)
            .args(args)
            .status()
            .expect("run git setup command");
        assert!(status.success());
    }
    std::fs::create_dir_all(root.join("src")).expect("create src");
    std::fs::write(
        root.join("Cargo.toml"),
        "[package]\nname='overlay-fixture'\nversion='0.1.0'\n",
    )
    .expect("write manifest");
    std::fs::write(root.join("src/lib.rs"), "pub fn baseline() {}\n").expect("write source");
    let add = std::process::Command::new("git")
        .current_dir(root)
        .args(["add", "Cargo.toml", "src/lib.rs"])
        .status()
        .expect("git add fixture");
    assert!(add.success());
    let commit = std::process::Command::new("git")
        .current_dir(root)
        .args(["commit", "-q", "--no-gpg-sign", "-m", "fixture"])
        .status()
        .expect("git commit fixture");
    assert!(commit.success());
    temp
}

#[tokio::test]
async fn clean_overlay_cargo_preflight_reads_selected_base_not_ambient_manifest() {
    let _guard = test_guard!();
    let root = init_clean_overlay_test_repo().keep();
    let good = git_output(&root, &["rev-parse", "HEAD"]).await.unwrap();
    let bad = "[package]\nname='overlay-fixture'\nversion='0.1.0'\n[dependencies]\nstale={path='../stale-sibling'}\n";
    std::fs::write(root.join("Cargo.toml"), bad).unwrap();
    git_output(&root, &["add", "Cargo.toml"]).await.unwrap();
    git_output(
        &root,
        &["commit", "-q", "--no-gpg-sign", "-m", "external dependency"],
    )
    .await
    .unwrap();
    // Ambient bytes disagree in the opposite direction from the selected base.
    std::fs::write(
        root.join("Cargo.toml"),
        "[package]\nname='ambient'\nversion='0.1.0'\n",
    )
    .unwrap();
    let bad_spec = prepare_clean_overlay_spec(&root, Some("HEAD".into()), true, vec![], true)
        .await
        .unwrap()
        .unwrap();
    let error = validate_clean_overlay_cargo_sources(&root, &bad_spec, "cargo test")
        .await
        .unwrap_err();
    assert!(format!("{error:#}").contains("stale-sibling"));
    let good_spec = prepare_clean_overlay_spec(&root, Some(good), true, vec![], true)
        .await
        .unwrap()
        .unwrap();
    validate_clean_overlay_cargo_sources(&root, &good_spec, "cargo test")
        .await
        .unwrap();
}

async fn retained_clean_overlay_sibling_fixture() -> (PathBuf, PathBuf, PathBuf) {
    let parent = tempfile::tempdir().unwrap().keep();
    let app = parent.join("app");
    let dep = parent.join("dep");
    for (root, manifest) in [
        (
            &app,
            "[package]\nname='app'\nversion='0.1.0'\n[workspace]\n[dependencies]\ndep={path='../dep'}\n",
        ),
        (
            &dep,
            "[package]\nname='dep'\nversion='0.1.0'\n[workspace]\n",
        ),
    ] {
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("Cargo.toml"), manifest).unwrap();
        std::fs::write(root.join("src/lib.rs"), "pub fn value() -> u32 { 1 }\n").unwrap();
        git_output(root, &["init", "-q", "-b", "main"])
            .await
            .unwrap();
        git_output(root, &["config", "user.email", "rch-test@example.invalid"])
            .await
            .unwrap();
        git_output(root, &["config", "user.name", "RCH Test"])
            .await
            .unwrap();
        git_output(root, &["config", "core.hooksPath", "/dev/null"])
            .await
            .unwrap();
        git_output(root, &["add", "Cargo.toml", "src/lib.rs"])
            .await
            .unwrap();
        git_output(
            root,
            &[
                "commit",
                "-q",
                "--no-gpg-sign",
                "-m",
                "selected sibling fixture",
            ],
        )
        .await
        .unwrap();
    }
    (parent, app, dep)
}

#[tokio::test]
async fn clean_overlay_dependency_binding_captures_committed_tree_and_ignores_peer_dirt() {
    let _guard = test_guard!();
    let (_retained_parent, app, dep) = retained_clean_overlay_sibling_fixture().await;
    let commit = git_output(&dep, &["rev-parse", "HEAD"]).await.unwrap();
    let tree = git_output(&dep, &["rev-parse", "HEAD^{tree}"])
        .await
        .unwrap();
    std::fs::write(
        dep.join("Cargo.toml"),
        "[dependencies]\nambient={path='../unselected'}\n",
    )
    .unwrap();
    std::fs::write(dep.join("src/lib.rs"), "pub fn value() -> u32 { 2 }\n").unwrap();
    let mut spec = prepare_clean_overlay_spec(&app, Some("HEAD".into()), true, vec![], true)
        .await
        .unwrap()
        .unwrap();
    assert!(
        validate_clean_overlay_cargo_sources(&app, &spec, "cargo test")
            .await
            .is_err()
    );
    bind_clean_overlay_dependencies(&app, &mut spec, &["../dep=HEAD".into()])
        .await
        .unwrap();
    assert_eq!(spec.primary_directory.as_deref(), Some(Path::new("app")));
    assert_eq!(spec.dependencies.len(), 1);
    assert_eq!(spec.dependencies[0].1.base_commit, commit);
    assert_eq!(spec.dependencies[0].1.tree_object, tree);
    validate_clean_overlay_cargo_sources(&app, &spec, "cargo test")
        .await
        .unwrap();
    // Moving the symbolic revision after admission cannot change selected bytes.
    git_output(&dep, &["add", "Cargo.toml", "src/lib.rs"])
        .await
        .unwrap();
    git_output(
        &dep,
        &[
            "commit",
            "-q",
            "--no-gpg-sign",
            "-m",
            "different later HEAD",
        ],
    )
    .await
    .unwrap();
    assert_ne!(
        git_output(&dep, &["rev-parse", "HEAD"]).await.unwrap(),
        commit
    );
    validate_clean_overlay_cargo_sources(&app, &spec, "cargo test")
        .await
        .unwrap();
    let selected = selected_clean_overlay_cargo_tree(&dep, &spec.dependencies[0].1)
        .await
        .unwrap();
    assert!(
        matches!(selected.get(Path::new("Cargo.toml")), Some(rch_common::cargo_path_deps::SelectedCargoEntry::File(Some(text))) if !text.contains("unselected"))
    );
    let receipt = spec.execution_receipt();
    assert!(
        receipt.contains(&format!("commit={commit} tree={tree}")),
        "{receipt}"
    );
    assert!(
        receipt.contains(&format!(
            "dependency-root={}",
            dep.canonicalize().unwrap().display()
        )),
        "{receipt}"
    );
}

#[tokio::test]
async fn clean_overlay_dependency_bindings_refuse_duplicate_non_sibling_and_missing_revisions() {
    let _guard = test_guard!();
    let (parent, app, _dep) = retained_clean_overlay_sibling_fixture().await;
    std::fs::create_dir_all(app.join("nested")).unwrap();
    std::fs::create_dir_all(parent.join("other/deep")).unwrap();
    for bindings in [
        vec!["../dep=HEAD", "../dep=HEAD"],
        vec![".=HEAD"],
        vec!["nested=HEAD"],
        vec!["../other/deep=HEAD"],
        vec!["../dep=missing-ref"],
        vec!["../dep"],
        vec!["../dep="],
    ] {
        let mut spec = prepare_clean_overlay_spec(&app, Some("HEAD".into()), true, vec![], true)
            .await
            .unwrap()
            .unwrap();
        let arguments = bindings
            .iter()
            .map(|value| (*value).to_owned())
            .collect::<Vec<_>>();
        assert!(
            bind_clean_overlay_dependencies(&app, &mut spec, &arguments)
                .await
                .is_err(),
            "{bindings:?}"
        );
    }
}

#[tokio::test]
async fn clean_overlay_dependency_binding_still_rejects_unbound_transitive_root() {
    let _guard = test_guard!();
    let (_retained_parent, app, dep) = retained_clean_overlay_sibling_fixture().await;
    std::fs::write(dep.join("Cargo.toml"), "[package]\nname='dep'\nversion='0.1.0'\n[workspace]\n[dependencies]\nunbound={path='../third'}\n").unwrap();
    git_output(&dep, &["add", "Cargo.toml"]).await.unwrap();
    git_output(
        &dep,
        &[
            "commit",
            "-q",
            "--no-gpg-sign",
            "-m",
            "unbound transitive sibling",
        ],
    )
    .await
    .unwrap();
    let mut spec = prepare_clean_overlay_spec(&app, Some("HEAD".into()), true, vec![], true)
        .await
        .unwrap()
        .unwrap();
    bind_clean_overlay_dependencies(&app, &mut spec, &["../dep=HEAD".into()])
        .await
        .unwrap();
    let error = validate_clean_overlay_cargo_sources(&app, &spec, "cargo test")
        .await
        .unwrap_err();
    assert!(format!("{error:#}").contains("third"), "{error:#}");
}

#[tokio::test]
async fn clean_overlay_cargo_preflight_honors_selected_manifest_overlay() {
    let _guard = test_guard!();
    let root = init_clean_overlay_test_repo().keep();
    std::fs::write(root.join("Cargo.toml"), "[package]\nname='overlay-fixture'\nversion='0.1.0'\n[dependencies]\nstale={path='../stale-sibling'}\n").unwrap();
    let base = prepare_clean_overlay_spec(&root, Some("HEAD".into()), true, vec![], true)
        .await
        .unwrap()
        .unwrap();
    validate_clean_overlay_cargo_sources(&root, &base, "cargo check")
        .await
        .unwrap();
    let overlay = prepare_clean_overlay_spec(
        &root,
        Some("HEAD".into()),
        true,
        vec![PathBuf::from("Cargo.toml")],
        false,
    )
    .await
    .unwrap()
    .unwrap();
    let error = validate_clean_overlay_cargo_sources(&root, &overlay, "cargo check")
        .await
        .unwrap_err();
    assert!(format!("{error:#}").contains("stale-sibling"));
}

#[tokio::test]
async fn clean_overlay_cargo_preflight_checks_cli_paths_and_inline_config() {
    let _guard = test_guard!();
    let root = init_clean_overlay_test_repo().keep();
    std::fs::create_dir(root.join(".cargo")).unwrap();
    // Selected config text must not be admitted as a manifest. Its unknown
    // package/dependencies keys are not dependency declarations in a config.
    std::fs::write(
        root.join(".cargo/config.toml"),
        "[package]\nname='wrong-kind'\n[dependencies]\nstale={path='../outside'}\n",
    )
    .unwrap();
    let spec = prepare_clean_overlay_spec(
        &root,
        Some("HEAD".into()),
        true,
        vec![PathBuf::from(".cargo/config.toml")],
        false,
    )
    .await
    .unwrap()
    .unwrap();
    for command in [
        "cargo test --manifest-path Cargo.toml",
        "cargo test --config 'build.build-dir=\"/managed later\"'",
        "cargo test -- --manifest-path ../ignored-test-argument",
    ] {
        validate_clean_overlay_cargo_sources(&root, &spec, command)
            .await
            .unwrap();
    }
    for command in [
        "cargo test --manifest-path ../outside/Cargo.toml",
        "cargo test --manifest-path .cargo/config.toml",
        "cargo test --config 'paths=[\"../outside\"]'",
        "cargo test --config ../outside/config.toml",
        "cargo -C ../outside test",
        "env --chdir=../outside cargo test",
    ] {
        assert!(
            validate_clean_overlay_cargo_sources(&root, &spec, command)
                .await
                .is_err(),
            "{command}"
        );
    }
}

#[tokio::test]
async fn clean_overlay_spec_accepts_base_only_and_resolves_commit() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    let spec =
        prepare_clean_overlay_spec(repo.path(), Some("HEAD".to_string()), true, vec![], true)
            .await
            .expect("prepare base-only clean overlay")
            .expect("clean-overlay spec");
    assert!(spec.is_base_only());
    assert!(matches!(spec.base_commit().len(), 40 | 64));
    assert!(
        spec.base_commit()
            .chars()
            .all(|character| character.is_ascii_hexdigit())
    );
}

#[tokio::test]
async fn clean_overlay_execution_receipt_names_the_resolved_base_and_content_fingerprint() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    let first = prepare_clean_overlay_spec(
        repo.path(),
        Some("HEAD".to_string()),
        true,
        vec![PathBuf::from("src/lib.rs")],
        false,
    )
    .await
    .expect("prepare first clean-overlay spec")
    .expect("first clean-overlay spec");
    let first_receipt = first.execution_receipt();
    assert!(first_receipt.contains(&format!("base={}", first.base_commit())));
    assert!(first_receipt.contains(&format!(
        "overlay-fingerprint={}",
        first.overlay_fingerprint()
    )));

    std::fs::write(repo.path().join("src/lib.rs"), "pub fn changed() {}\n")
        .expect("change selected overlay");
    let second = prepare_clean_overlay_spec(
        repo.path(),
        Some("HEAD".to_string()),
        true,
        vec![PathBuf::from("src/lib.rs")],
        false,
    )
    .await
    .expect("prepare second clean-overlay spec")
    .expect("second clean-overlay spec");
    assert_ne!(first.execution_receipt(), second.execution_receipt());
}

#[test]
fn clean_overlay_selection_identity_is_source_bound_and_per_job() {
    let _guard = test_guard!();
    let spec = CleanOverlaySpec {
        base_commit: "0123456789abcdef0123456789abcdef01234567".to_string(),
        tree_object: "0123456789abcdef0123456789abcdef01234567".to_string(),
        overlay_paths: vec![PathBuf::from("src/lib.rs")],
        overlay_fingerprint: "first-overlay-fingerprint".to_string(),
        dependencies: Vec::new(),
        primary_directory: None,
    };
    let plain = selection_project_for_execution("fixture-project", None, uuid::Uuid::from_u128(1));
    assert_eq!(plain, "fixture-project");

    let first =
        selection_project_for_execution("fixture-project", Some(&spec), uuid::Uuid::from_u128(2));
    let second_job =
        selection_project_for_execution("fixture-project", Some(&spec), uuid::Uuid::from_u128(3));
    let different_base = CleanOverlaySpec {
        base_commit: "fedcba9876543210fedcba9876543210fedcba98".to_string(),
        ..spec.clone()
    };
    let different_overlay = CleanOverlaySpec {
        overlay_fingerprint: "second-overlay-fingerprint".to_string(),
        ..spec.clone()
    };

    assert_ne!(
        first, second_job,
        "each clean-overlay job needs a new identity"
    );
    assert_ne!(
        first,
        selection_project_for_execution(
            "fixture-project",
            Some(&different_base),
            uuid::Uuid::from_u128(2),
        ),
        "the immutable base must bind the selection identity"
    );
    assert_ne!(
        first,
        selection_project_for_execution(
            "fixture-project",
            Some(&different_overlay),
            uuid::Uuid::from_u128(2),
        ),
        "the dirty overlay fingerprint must bind the selection identity"
    );
}

#[tokio::test]
async fn clean_overlay_spec_requires_exactly_one_overlay_scope() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    let missing =
        prepare_clean_overlay_spec(repo.path(), Some("HEAD".to_string()), true, vec![], false)
            .await
            .expect_err("missing overlay scope must fail");
    assert!(missing.to_string().contains("exactly one"));

    let conflicting = prepare_clean_overlay_spec(
        repo.path(),
        Some("HEAD".to_string()),
        true,
        vec![PathBuf::from("src/lib.rs")],
        true,
    )
    .await
    .expect_err("conflicting overlay scope must fail");
    assert!(conflicting.to_string().contains("exactly one"));
}

#[tokio::test]
async fn clean_overlay_spec_rejects_traversal_and_detects_source_churn() {
    let _guard = test_guard!();
    assert!(normalize_clean_overlay_path(Path::new("../peer.rs")).is_err());
    assert!(normalize_clean_overlay_path(Path::new("/absolute.rs")).is_err());
    assert!(normalize_clean_overlay_path(Path::new(r"src\backslash.rs")).is_err());
    let non_ascii = normalize_clean_overlay_path(Path::new("src/caf\u{e9}.rs"))
        .expect_err("non-ASCII overlay paths must fail closed");
    assert!(non_ascii.to_string().contains("only ASCII"));

    let repo = init_clean_overlay_test_repo();
    std::fs::write(repo.path().join("src/lib.rs"), "pub fn overlay() {}\n")
        .expect("write overlay source");
    let spec = prepare_clean_overlay_spec(
        repo.path(),
        Some("HEAD".to_string()),
        true,
        vec![PathBuf::from("src/lib.rs")],
        false,
    )
    .await
    .expect("prepare clean overlay")
    .expect("clean-overlay spec");
    spec.verify_overlay_unchanged(repo.path())
        .expect("unchanged overlay");

    std::fs::write(
        repo.path().join("src/lib.rs"),
        "pub fn changed_again() {}\n",
    )
    .expect("mutate overlay source");
    let error = spec
        .verify_overlay_unchanged(repo.path())
        .expect_err("source churn must fail closed");
    assert!(error.to_string().contains("changed after admission"));
}

#[tokio::test]
async fn clean_overlay_post_admission_spelling_drift_fails_closed() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    let spec = prepare_clean_overlay_spec(
        repo.path(),
        Some("HEAD".to_string()),
        true,
        vec![PathBuf::from("src/lib.rs")],
        false,
    )
    .await
    .expect("prepare clean overlay")
    .expect("clean-overlay spec");

    std::fs::rename(
        repo.path().join("src/lib.rs"),
        repo.path().join("src/LIB.rs"),
    )
    .expect("change selected path spelling");
    let error = spec
        .verify_overlay_unchanged(repo.path())
        .expect_err("post-admission spelling drift must fail closed");
    assert!(
        error
            .to_string()
            .contains("spelling does not exactly match")
    );
}

#[tokio::test]
async fn clean_overlay_directory_rejects_nested_non_ascii_path() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    std::fs::write(repo.path().join("src/caf\u{e9}.rs"), "pub fn coffee() {}\n")
        .expect("write non-ASCII nested path");

    let error = prepare_clean_overlay_spec(
        repo.path(),
        Some("HEAD".to_string()),
        true,
        vec![PathBuf::from("src")],
        false,
    )
    .await
    .expect_err("nested non-ASCII overlay paths must fail closed");
    assert!(error.to_string().contains("only ASCII"));
}

#[tokio::test]
async fn clean_overlay_directory_rejects_nested_backslash_or_control_path() {
    let _guard = test_guard!();
    for relative in ["src/back\\slash.rs", "src/line\nbreak.rs"] {
        let repo = init_clean_overlay_test_repo();
        std::fs::write(repo.path().join(relative), "pub fn hazard() {}\n")
            .expect("write nested portability hazard");

        let error = prepare_clean_overlay_spec(
            repo.path(),
            Some("HEAD".to_string()),
            true,
            vec![PathBuf::from("src")],
            false,
        )
        .await
        .expect_err("nested backslash/control overlay paths must fail closed");
        assert!(
            error
                .to_string()
                .contains("backslashes or control characters")
        );
    }
}

#[cfg(unix)]
#[tokio::test]
async fn clean_overlay_spec_rejects_nested_symlink() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    std::os::unix::fs::symlink("/dev/null", repo.path().join("src/escape"))
        .expect("create escaping fixture symlink");

    let error = prepare_clean_overlay_spec(
        repo.path(),
        Some("HEAD".to_string()),
        true,
        vec![PathBuf::from("src")],
        false,
    )
    .await
    .expect_err("nested symlink escape must fail closed");
    assert!(error.to_string().contains("do not support symlinks"));
}

#[tokio::test]
async fn clean_overlay_spec_rejects_nested_git_metadata() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    std::fs::create_dir_all(repo.path().join("src/vendor/.GIT"))
        .expect("create nested Git metadata fixture");

    let error = prepare_clean_overlay_spec(
        repo.path(),
        Some("HEAD".to_string()),
        true,
        vec![PathBuf::from("src")],
        false,
    )
    .await
    .expect_err("nested Git metadata must fail closed");
    assert!(error.to_string().contains("Git metadata"));
}

#[test]
fn clean_overlay_exact_spelling_check_rejects_case_drift() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    assert!(
        !clean_overlay_path_has_exact_spelling(repo.path(), Path::new("SRC/lib.rs"))
            .expect("check path spelling")
    );
}

#[tokio::test]
async fn clean_overlay_directory_rejects_base_path_rename() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    std::fs::rename(
        repo.path().join("src/lib.rs"),
        repo.path().join("src/renamed.rs"),
    )
    .expect("rename tracked fixture path");

    let error = prepare_clean_overlay_spec(
        repo.path(),
        Some("HEAD".to_string()),
        true,
        vec![PathBuf::from("src")],
        false,
    )
    .await
    .expect_err("directory overlay with base rename must fail closed");
    assert!(
        error
            .to_string()
            .contains("selected deletions are unsupported")
    );
}

#[tokio::test]
async fn clean_overlay_rejects_case_only_base_directory_alias() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    std::fs::rename(repo.path().join("src"), repo.path().join("SRC"))
        .expect("case-rename tracked fixture directory");

    let error = prepare_clean_overlay_spec(
        repo.path(),
        Some("HEAD".to_string()),
        true,
        vec![PathBuf::from("SRC")],
        false,
    )
    .await
    .expect_err("case-only base alias must fail closed");
    assert!(error.to_string().contains("case-only overlays"));
}

#[tokio::test]
async fn clean_overlay_rejects_new_file_under_case_aliased_base_directory() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    std::fs::rename(repo.path().join("src"), repo.path().join("SRC"))
        .expect("case-rename tracked fixture directory");
    std::fs::write(repo.path().join("SRC/new.rs"), "pub fn new_file() {}\n")
        .expect("write new file under case-aliased directory");

    let error = prepare_clean_overlay_spec(
        repo.path(),
        Some("HEAD".to_string()),
        true,
        vec![PathBuf::from("SRC/new.rs")],
        false,
    )
    .await
    .expect_err("new file under case-aliased base directory must fail closed");
    assert!(error.to_string().contains("case-only overlays"));
}

#[tokio::test]
async fn clean_overlay_spec_rejects_empty_overlay_directory() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    std::fs::create_dir_all(repo.path().join("src/empty")).expect("create empty overlay fixture");

    let error = prepare_clean_overlay_spec(
        repo.path(),
        Some("HEAD".to_string()),
        true,
        vec![PathBuf::from("src/empty")],
        false,
    )
    .await
    .expect_err("empty overlay directory must fail closed");
    assert!(error.to_string().contains("empty directories"));
}

#[tokio::test]
async fn clean_overlay_spec_rejects_gitlinks() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    let head = std::process::Command::new("git")
        .current_dir(repo.path())
        .args(["rev-parse", "HEAD"])
        .output()
        .expect("resolve fixture HEAD");
    assert!(head.status.success());
    let head = String::from_utf8(head.stdout)
        .expect("fixture HEAD is UTF-8")
        .trim()
        .to_string();
    let cache_info = format!("160000,{head},vendor/submodule");
    let update = std::process::Command::new("git")
        .current_dir(repo.path())
        .args(["update-index", "--add", "--cacheinfo", &cache_info])
        .status()
        .expect("add fixture gitlink");
    assert!(update.success());
    let commit = std::process::Command::new("git")
        .current_dir(repo.path())
        .args(["commit", "-q", "--no-gpg-sign", "-m", "add gitlink"])
        .status()
        .expect("commit fixture gitlink");
    assert!(commit.success());

    let error =
        prepare_clean_overlay_spec(repo.path(), Some("HEAD".to_string()), true, vec![], true)
            .await
            .expect_err("gitlink must fail closed");
    assert!(
        error
            .to_string()
            .contains("does not support Git submodules")
    );
}

#[tokio::test]
async fn clean_overlay_spec_rejects_git_archive_transform_attributes() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    std::fs::write(
        repo.path().join(".gitattributes"),
        "Cargo.toml export-ignore\nsrc/lib.rs export-subst\n",
    )
    .expect("write archive-transform attributes");
    let add = std::process::Command::new("git")
        .current_dir(repo.path())
        .args(["add", ".gitattributes"])
        .status()
        .expect("add attributes fixture");
    assert!(add.success());
    let commit = std::process::Command::new("git")
        .current_dir(repo.path())
        .args(["commit", "-q", "--no-gpg-sign", "-m", "add attributes"])
        .status()
        .expect("commit attributes fixture");
    assert!(commit.success());

    let error =
        prepare_clean_overlay_spec(repo.path(), Some("HEAD".to_string()), true, vec![], true)
            .await
            .expect_err("archive-transform attributes must fail closed");
    assert!(error.to_string().contains("non-checkout-equivalent"));
}

#[tokio::test]
async fn clean_overlay_spec_rejects_info_archive_transform_attributes() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    std::fs::write(
        repo.path().join(".git/info/attributes"),
        "Cargo.toml export-ignore\n",
    )
    .expect("write info attributes fixture");

    let error =
        prepare_clean_overlay_spec(repo.path(), Some("HEAD".to_string()), true, vec![], true)
            .await
            .expect_err("info archive-transform attributes must fail closed");
    assert!(error.to_string().contains("info/attributes"));
}

#[tokio::test]
async fn clean_overlay_rechecks_info_attributes_after_admission() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    let spec =
        prepare_clean_overlay_spec(repo.path(), Some("HEAD".to_string()), true, vec![], true)
            .await
            .expect("prepare clean overlay")
            .expect("clean-overlay spec");

    std::fs::write(
        repo.path().join(".git/info/attributes"),
        "Cargo.toml export-ignore\n",
    )
    .expect("mutate info attributes after admission");
    let error = spec
        .verify_archive_attributes(repo.path())
        .await
        .expect_err("post-admission info attributes must fail closed");
    assert!(error.to_string().contains("info/attributes"));
}

#[tokio::test]
async fn clean_overlay_git_reads_ignore_replace_refs() {
    let _guard = test_guard!();
    let repo = init_clean_overlay_test_repo();
    let original = std::process::Command::new("git")
        .current_dir(repo.path())
        .args(["rev-parse", "HEAD"])
        .output()
        .expect("resolve original fixture commit");
    assert!(original.status.success());
    let original = String::from_utf8(original.stdout)
        .expect("original fixture commit is UTF-8")
        .trim()
        .to_string();

    std::fs::write(repo.path().join("src/lib.rs"), "pub fn replacement() {}\n")
        .expect("write replacement source");
    let replacement_commit = std::process::Command::new("git")
        .current_dir(repo.path())
        .args(["commit", "-qam", "replacement", "--no-gpg-sign"])
        .status()
        .expect("commit replacement fixture");
    assert!(replacement_commit.success());
    let replacement = std::process::Command::new("git")
        .current_dir(repo.path())
        .args(["rev-parse", "HEAD"])
        .output()
        .expect("resolve replacement fixture commit");
    assert!(replacement.status.success());
    let replacement = String::from_utf8(replacement.stdout)
        .expect("replacement fixture commit is UTF-8")
        .trim()
        .to_string();
    let replace = std::process::Command::new("git")
        .current_dir(repo.path())
        .args(["replace", &original, &replacement])
        .status()
        .expect("install fixture replace ref");
    assert!(replace.success());

    let source = git_show_optional(repo.path(), &original, "src/lib.rs")
        .await
        .expect("read original source without replacement")
        .expect("original source exists");
    assert_eq!(source, "pub fn baseline() {}\n");
    let spec = prepare_clean_overlay_spec(repo.path(), Some(original.clone()), true, vec![], true)
        .await
        .expect("prepare original commit with replace ref present")
        .expect("clean-overlay spec");
    assert_eq!(spec.base_commit(), original);
}

// ------------------------------------------------------------------
// join_exec_command tests — guard against the `.join(" ")` round-trip
// corruption that was present when `rch exec --` rebuilt a command
// string for `sh -c` (bug audit 2026-04-23).
// ------------------------------------------------------------------

#[test]
fn join_exec_command_plain_args_unchanged() {
    let _guard = test_guard!();
    let parts = vec![
        "cargo".to_string(),
        "build".to_string(),
        "--release".to_string(),
    ];
    let joined = join_exec_command(&parts);
    // shell_words::split of the result should reproduce the original argv.
    let round_trip = shell_words::split(&joined).expect("valid shell words");
    assert_eq!(round_trip, parts);
}

/// `rch exec -- FOO=1 cmd` must keep FOO=1 an assignment. Quoting it as a
/// whole word made `sh` run a program named `FOO=1` (exit 127) on every local
/// fallback and non-cargo remote run. Run the joined text through a real shell.
#[cfg(unix)]
#[test]
fn join_exec_command_keeps_leading_assignments_as_assignments() {
    let _guard = test_guard!();
    let parts = vec![
        "RCH_T_A=one".to_string(),
        "RCH_T_B=two words".to_string(),
        "sh".to_string(),
        "-c".to_string(),
        "printf '%s|%s' \"$RCH_T_A\" \"$RCH_T_B\"".to_string(),
    ];
    let joined = join_exec_command(&parts);
    let output = std::process::Command::new("sh")
        .arg("-c")
        .arg(&joined)
        .output()
        .expect("run sh");
    assert!(output.status.success(), "{joined}: {output:?}");
    assert_eq!(String::from_utf8_lossy(&output.stdout), "one|two words");
    // The single-string form (`rch exec -- "FOO=1 cargo test"`) takes the same path.
    let single = join_exec_command(&["RCH_T_A=1 cargo test".to_string()]);
    assert_eq!(
        shell_words::split(&single).expect("valid shell words"),
        ["env", "RCH_T_A=1", "cargo", "test"]
    );
    // A non-assignment first word is untouched.
    assert_eq!(
        join_exec_command(&["=x".to_string(), "y".to_string()]),
        shell_words::join(["=x", "y"])
    );
}

#[test]
fn clean_overlay_fmt_check_allowlist_is_exact_and_read_only() {
    let _guard = test_guard!();
    assert!(is_clean_overlay_cargo_fmt_check(&[
        "cargo".into(),
        "fmt".into(),
        "--check".into(),
    ]));
    assert!(is_clean_overlay_cargo_fmt_check(&[
        "/usr/bin/cargo".into(),
        "+nightly".into(),
        "fmt".into(),
        "--all".into(),
        "--check".into(),
    ]));
    assert!(!is_clean_overlay_cargo_fmt_check(&[
        "cargo".into(),
        "fmt".into(),
    ]));
    assert!(!is_clean_overlay_cargo_fmt_check(&[
        "cargo".into(),
        "metadata".into(),
        "--check".into(),
    ]));
}

#[test]
fn join_exec_command_preserves_space_bearing_arg() {
    let _guard = test_guard!();
    // The outer shell merges `--features='foo bar'` into one argv
    // entry with a literal space. We must re-quote so `sh -c` does
    // not re-split it into two tokens.
    let parts = vec![
        "cargo".to_string(),
        "build".to_string(),
        "--features=foo bar".to_string(),
    ];
    let joined = join_exec_command(&parts);
    let round_trip = shell_words::split(&joined).expect("valid shell words");
    assert_eq!(
        round_trip, parts,
        "space must survive round-trip through sh"
    );
}

#[test]
fn join_exec_command_preserves_quote_metachars() {
    let _guard = test_guard!();
    let parts = vec![
        "cargo".to_string(),
        "run".to_string(),
        "--".to_string(),
        "he said \"hi\"".to_string(),
        "$PATH".to_string(),
        "a;b".to_string(),
    ];
    let joined = join_exec_command(&parts);
    let round_trip = shell_words::split(&joined).expect("valid shell words");
    assert_eq!(round_trip, parts);
}

#[test]
fn join_exec_command_splits_single_shell_command_arg() {
    let _guard = test_guard!();
    let parts =
        vec!["env RUSTFLAGS=\"-C linker=cc\" cargo build --bin generate_react_goldens".to_string()];
    let joined = join_exec_command(&parts);
    let round_trip = shell_words::split(&joined).expect("valid shell words");
    assert_eq!(
        round_trip,
        vec![
            "env".to_string(),
            "RUSTFLAGS=-C linker=cc".to_string(),
            "cargo".to_string(),
            "build".to_string(),
            "--bin".to_string(),
            "generate_react_goldens".to_string(),
        ]
    );
    assert!(
        !joined.starts_with("'env "),
        "env wrapper must remain the executable, not part of one quoted command: {joined}"
    );
}

#[test]
fn join_exec_command_preserves_already_split_env_prefix() {
    let _guard = test_guard!();
    let parts = vec![
        "env".to_string(),
        "RUSTFLAGS=-C linker=cc".to_string(),
        "cargo".to_string(),
        "build".to_string(),
    ];
    let joined = join_exec_command(&parts);
    let round_trip = shell_words::split(&joined).expect("valid shell words");
    assert_eq!(round_trip, parts);
}

#[test]
fn join_exec_command_empty_input() {
    let _guard = test_guard!();
    let parts: Vec<String> = Vec::new();
    assert_eq!(join_exec_command(&parts), "");
}

#[test]
fn local_fallback_command_bypasses_cargo_wrapper() {
    let _guard = test_guard!();
    let command = local_fallback_command("cargo test -p rch");

    let has_bypass = command.get_envs().any(|(key, value)| {
        key == std::ffi::OsStr::new(RCH_CARGO_WRAPPER_BYPASS_ENV)
            && value == Some(std::ffi::OsStr::new("1"))
    });
    assert!(
        has_bypass,
        "local fallback must bypass the PATH cargo wrapper to avoid recursive rch exec"
    );

    let args = command.get_args().collect::<Vec<_>>();
    assert_eq!(
        args,
        vec![
            std::ffi::OsStr::new("-c"),
            std::ffi::OsStr::new("cargo test -p rch")
        ]
    );
}

#[test]
fn shell_wrapped_cargo_command_is_detected_before_exec_fallback() {
    let _guard = test_guard!();
    assert!(shell_wrapped_cargo_command(&[
        "bash".to_string(),
        "-lc".to_string(),
        "cargo build --release".to_string(),
    ]));
    assert!(shell_wrapped_cargo_command(&[
        "sh".to_string(),
        "-c".to_string(),
        "cargo clippy --workspace --all-targets && cargo build --release --example probe"
            .to_string(),
    ]));
    assert!(!shell_wrapped_cargo_command(&[
        "sh".to_string(),
        "-c".to_string(),
        "echo cargo build".to_string(),
    ]));
    assert!(!shell_wrapped_cargo_command(&[
        "cargo".to_string(),
        "build".to_string(),
    ]));
}

#[test]
fn remote_required_fallback_refuses_before_building_local_shell_command() {
    let _guard = test_guard!();
    let command = "bash -lc 'cargo test --lib focused_case -- --nocapture'";

    assert!(
        matches!(
            local_fallback_command_for_policy(command, true),
            Err(LocalFallbackRefusal::RemoteRequired)
        ),
        "remote-required policy must refuse before constructing a local shell fallback"
    );
    assert!(
        local_fallback_command_for_policy(command, false).is_ok(),
        "ordinary local fallback behavior remains available when remote is not required"
    );
}

#[test]
fn remote_required_non_compilation_shell_wrapped_cargo_has_stable_refusal_code() {
    let _guard = test_guard!();
    let parts = vec![
        "bash".to_string(),
        "-lc".to_string(),
        "cargo test --lib focused_case -- --nocapture".to_string(),
    ];
    let command = join_exec_command(&parts);
    let classification = classify_command(&command);

    assert!(
        !classification.is_compilation,
        "global classification should keep arbitrary shell wrappers out of hook-mode offload"
    );
    assert!(
        matches!(
            local_fallback_command_for_policy(&command, true),
            Err(LocalFallbackRefusal::RemoteRequired)
        ),
        "RCH_REQUIRE_REMOTE must prevent the shell from running locally even when classification rejects it"
    );
    assert!(remote_required_refusal_summary("non-compilation command").contains("RCH-E301"));
    assert!(
        !remote_required_refusal_summary("dependency preflight failed").contains("RCH-E301"),
        "dependency-topology refusals should remain distinguishable from command-classification refusals"
    );
}

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

    for value in ["1", "true", "TRUE", "yes", "on"] {
        assert!(env_flag_enabled(value), "{value} should be truthy");
    }

    for value in ["", "0", "false", "no", "off", "remote"] {
        assert!(!env_flag_enabled(value), "{value} should not be truthy");
    }
}

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

    let previous = HOOK_MODE_PANIC_FAIL_OPEN.swap(false, Ordering::AcqRel);
    enable_hook_mode_panic_fail_open();
    assert!(
        hook_mode_panic_fail_open_enabled(),
        "installing the hook panic handler must mark no-subcommand hook mode as fail-open even when RCH_HOOK_MODE is unset"
    );
    HOOK_MODE_PANIC_FAIL_OPEN.store(previous, Ordering::Release);
}

fn test_lock() -> &'static Mutex<()> {
    static ENV_MUTEX: OnceLock<Mutex<()>> = OnceLock::new();
    ENV_MUTEX.get_or_init(|| Mutex::new(()))
}

struct TestOverridesGuard;

impl TestOverridesGuard {
    fn set(socket_path: &str, ssh_config: MockConfig, rsync_config: MockRsyncConfig) -> Self {
        let mut config = rch_common::RchConfig::default();
        config.general.socket_path = socket_path.to_string();
        crate::config::set_test_config_override(Some(config));

        set_mock_enabled_override(Some(true));
        set_mock_ssh_config_override(Some(ssh_config));
        set_mock_rsync_config_override(Some(rsync_config));

        Self
    }
}

impl Drop for TestOverridesGuard {
    fn drop(&mut self) {
        crate::config::set_test_config_override(None);
        clear_mock_overrides();
    }
}

struct ConfigOverrideGuard;

impl ConfigOverrideGuard {
    fn set(config: rch_common::RchConfig) -> Self {
        crate::config::set_test_config_override(Some(config));
        Self
    }
}

impl Drop for ConfigOverrideGuard {
    fn drop(&mut self) {
        crate::config::set_test_config_override(None);
    }
}

/// RAII wrapper around `tempfile::TempDir` that always reports the
/// canonical form of the scratch path via `.path()`, so subdirectories
/// derived from it pass `starts_with` against a canonicalized
/// topology root even when the OS routes `/tmp` through a symlink
/// (macOS resolves `/tmp` to `/private/tmp`).
///
/// Deliberately mimics the `tempfile::TempDir` shape (`.path()` only)
/// so call sites can continue to write
/// `temp_dir.path().join("subdir")` without change.
struct CanonicalTempDir {
    _dir: tempfile::TempDir,
    path: PathBuf,
}

impl CanonicalTempDir {
    fn path(&self) -> &Path {
        &self.path
    }
}

/// Create a platform-portable tempdir and a matching `PathTopologyPolicy`
/// whose canonical root points at the tempdir's canonical path.
///
/// Tests previously used `tempfile::tempdir_in("/data/projects")` +
/// `PathTopologyPolicy::default()` so the default `/data/projects`
/// topology would accept the tempdir paths. That pins tests to the
/// maintainer's dev machine and fails on every CI runner that doesn't
/// have `/data/projects`. This helper keeps the intent (tempdir paths
/// are "within topology") without the path pin — we simply build a
/// policy that recognises the tempdir itself as the topology root.
///
/// The tempdir path is canonicalized so macOS `/tmp -> /private/tmp`
/// and similar symlinks don't cause `starts_with` mismatches when
/// paths are compared against the policy.
///
/// The `alias_root` is set to a sibling path that is deliberately *not*
/// a prefix of the tempdir. This keeps
/// `normalize_project_path_with_policy` from trying to verify the alias
/// as a symlink (which fails when the alias is a plain directory or
/// missing) while still giving `is_within_sync_topology` a well-formed
/// second entry.
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,
    )
}

async fn spawn_mock_daemon(socket_path: &str, response: SelectionResponse) {
    let _ = std::fs::remove_file(socket_path);
    let listener = UnixListener::bind(socket_path).expect("Failed to bind mock socket");

    tokio::spawn(async move {
        let (stream, _) = listener.accept().await.expect("Accept failed");
        let (reader, mut writer) = stream.into_split();
        let mut buf_reader = TokioBufReader::new(reader);

        let mut request_line = String::new();
        buf_reader
            .read_line(&mut request_line)
            .await
            .expect("Failed to read request");

        let body = serde_json::to_string(&response).expect("Serialize response");
        let http = format!("HTTP/1.1 200 OK\r\n\r\n{}", body);
        writer
            .write_all(http.as_bytes())
            .await
            .expect("Failed to write response");
        writer.flush().await.expect("Failed to flush response");
    });
}

#[tokio::test]
async fn test_non_bash_allowed() {
    let input = HookInput {
        tool_name: "Read".to_string(),
        tool_input: ToolInput {
            command: "anything".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    assert!(output.is_allow());
}

#[tokio::test]
async fn test_non_compilation_allowed() {
    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "ls -la".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    assert!(output.is_allow());
}

#[tokio::test]
async fn test_process_hook_allows_beads_comment_with_embedded_build_text() {
    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command:
                r#"br comments add ft-4tp7g.1 "remote proof blocked: cargo test -p rchd --lib""#
                    .to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    assert!(
        matches!(output, HookOutput::Allow(_)),
        "embedded build text in a Beads comment must not delegate to rch exec: {output:?}"
    );
}

#[tokio::test]
async fn test_process_hook_allows_env_prefixed_beads_comment_with_embedded_build_text() {
    let input = HookInput {
            tool_name: "Bash".to_string(),
            tool_input: ToolInput {
                command: r#"AGENT_NAME=Codex br comments add ft-4tp7g.4 "proof lane: cargo clippy --workspace""#
                    .to_string(),
                description: None,
            },
            session_id: None,
        };

    let output = process_hook(input).await;
    assert!(
        matches!(output, HookOutput::Allow(_)),
        "env-prefixed Beads comments with build text must not delegate to rch exec: {output:?}"
    );
}

#[tokio::test]
async fn test_process_hook_bypasses_classification_cache_without_env_flag() {
    let unique_cmd = "echo rch-hook-cache-bypass-without-env-marker";
    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: unique_cmd.to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    assert!(output.is_allow());

    assert!(
        crate::cache::global_cache().get(unique_cmd).is_none(),
        "process_hook must bypass the cache even when RCH_HOOK_MODE is unset"
    );
}

#[tokio::test]
async fn test_compilation_detected() {
    let _lock = test_lock().lock().await;
    // Disable mock mode to test real fail-open behavior (no daemon = allow)
    mock::set_mock_enabled_override(Some(false));

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build --release".to_string(),
            description: None,
        },
        session_id: None,
    };

    // Without daemon, should fail-open and allow local execution
    // This tests that classification works and fail-open behavior is preserved
    let output = process_hook(input).await;
    assert!(
        output.is_allow(),
        "Expected allow when daemon unavailable (fail-open)"
    );

    // Reset mock override
    mock::set_mock_enabled_override(None);
}

// ========================================================================
// TimingEstimate and Timing Gating Tests
// ========================================================================

#[test]
fn test_timing_estimate_struct() {
    let _guard = test_guard!();
    let estimate = TimingEstimate {
        predicted_local_ms: 5000,
        predicted_speedup: Some(2.5),
    };
    assert_eq!(estimate.predicted_local_ms, 5000);
    assert_eq!(estimate.predicted_speedup, Some(2.5));
}

#[test]
fn test_timing_estimate_no_speedup() {
    let _guard = test_guard!();
    let estimate = TimingEstimate {
        predicted_local_ms: 3000,
        predicted_speedup: None,
    };
    assert_eq!(estimate.predicted_local_ms, 3000);
    assert!(estimate.predicted_speedup.is_none());
}

#[test]
fn test_estimate_timing_returns_none_without_history() {
    let _guard = test_guard!();
    // Currently returns None (fail-open) since no timing history exists
    let config = rch_common::RchConfig::default();
    let estimate =
        estimate_timing_for_build("test-project", Some(CompilationKind::CargoBuild), &config);
    assert!(estimate.is_none());
}

#[test]
fn test_timing_gating_thresholds_default() {
    let _guard = test_guard!();
    let config = rch_common::CompilationConfig::default();
    // Default min_local_time_ms: 2000ms
    assert_eq!(config.min_local_time_ms, 2000);
    // Default speedup threshold: 1.2x
    assert!((config.remote_speedup_threshold - 1.2).abs() < 0.001);
}

#[test]
fn test_urlencoding_encode_basic() {
    let _guard = test_guard!();
    assert_eq!(urlencoding_encode("hello world"), "hello%20world");
    assert_eq!(urlencoding_encode("path/to/file"), "path%2Fto%2Ffile");
    assert_eq!(urlencoding_encode("foo:bar"), "foo%3Abar");
}

#[test]
fn test_urlencoding_encode_special_chars() {
    let _guard = test_guard!();
    assert_eq!(urlencoding_encode("a&b=c"), "a%26b%3Dc");
    assert_eq!(urlencoding_encode("100%"), "100%25");
    assert_eq!(urlencoding_encode("hello+world"), "hello%2Bworld");
}

#[test]
fn test_urlencoding_encode_no_encoding_needed() {
    let _guard = test_guard!();
    assert_eq!(urlencoding_encode("simple"), "simple");
    assert_eq!(
        urlencoding_encode("with-dash_underscore.dot~tilde"),
        "with-dash_underscore.dot~tilde"
    );
    assert_eq!(urlencoding_encode("ABC123"), "ABC123");
}

#[test]
fn test_urlencoding_encode_unicode() {
    let _guard = test_guard!();
    // Unicode characters should be encoded as UTF-8 bytes
    let encoded = urlencoding_encode("café");
    assert!(encoded.contains("%")); // 'é' should be encoded
    assert!(encoded.starts_with("caf")); // ASCII part preserved
}

#[test]
fn test_parse_jobs_flag_variants() {
    let _guard = test_guard!();
    assert_eq!(parse_jobs_flag("cargo build -j 8"), Some(8));
    assert_eq!(parse_jobs_flag("cargo build -j8"), Some(8));
    assert_eq!(parse_jobs_flag("cargo build --jobs 4"), Some(4));
    assert_eq!(parse_jobs_flag("cargo build --jobs=12"), Some(12));
    assert_eq!(parse_jobs_flag("cargo build -j=16"), Some(16));
    assert_eq!(parse_jobs_flag("cargo build --jobs=12"), Some(12));
    assert_eq!(parse_jobs_flag("cargo build -j"), None);
    assert_eq!(parse_jobs_flag("cargo build --jobs"), None);
}

#[test]
fn test_parse_test_threads_variants() {
    let _guard = test_guard!();
    assert_eq!(
        parse_test_threads("cargo test -- --test-threads=4"),
        Some(4)
    );
    assert_eq!(
        parse_test_threads("cargo test -- --test-threads 2"),
        Some(2)
    );
    assert_eq!(parse_test_threads("cargo test"), None);
}

#[test]
fn test_go_classification_drives_reservations_and_test_kind() {
    let _guard = test_guard!();
    let config = rch_common::CompilationConfig {
        build_slots: 12,
        test_slots: 8,
        check_slots: 4,
        ..Default::default()
    };
    for (verb, kind, default, is_test) in [
        // Go builds offload only with an explicit output file (go_build_output).
        ("build -o bin/app", CompilationKind::GoBuild, 12, false),
        ("test", CompilationKind::GoTest, 8, true),
        ("vet", CompilationKind::GoVet, 4, false),
    ] {
        if kind == CompilationKind::GoBuild && !cfg!(unix) {
            continue;
        }
        for (command, expected) in [
            (format!("go {verb} ./..."), default),
            (format!("go {verb} -p 2 ./..."), 2),
        ] {
            let classification = classify_command(&command);
            assert!(classification.is_compilation, "{command}");
            assert_eq!(classification.kind, Some(kind), "{command}");
            assert_eq!(is_test_kind(classification.kind), is_test, "{command}");
            assert_eq!(
                estimate_cores_for_command(classification.kind, &command, &config),
                expected,
                "{command}"
            );
        }
    }
}

#[test]
fn test_estimate_cores_for_command() {
    let _guard = test_guard!();
    let config = rch_common::CompilationConfig {
        build_slots: 6,
        test_slots: 10,
        check_slots: 3,
        ..Default::default()
    };

    let build =
        estimate_cores_for_command(Some(CompilationKind::CargoBuild), "cargo build", &config);
    assert_eq!(build, 6);

    let build_jobs = estimate_cores_for_command(
        Some(CompilationKind::CargoBuild),
        "cargo build -j 12",
        &config,
    );
    assert_eq!(build_jobs, 12);

    let test_default =
        estimate_cores_for_command(Some(CompilationKind::CargoTest), "cargo test", &config);
    assert_eq!(test_default, 10);

    let test_threads = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "cargo test -- --test-threads=4",
        &config,
    );
    assert_eq!(test_threads, 4);

    let test_jobs = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "cargo test -j 1 -p rchd --lib",
        &config,
    );
    assert_eq!(test_jobs, 1);

    let test_long_jobs = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "cargo test --jobs=3 -p rchd --lib",
        &config,
    );
    assert_eq!(test_long_jobs, 3);

    let test_jobs_override_threads = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "cargo test -j 1 -- --test-threads=8",
        &config,
    );
    assert_eq!(test_jobs_override_threads, 1);

    let test_build_jobs_env = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "CARGO_BUILD_JOBS=2 cargo test -p rchd --lib",
        &config,
    );
    assert_eq!(test_build_jobs_env, 2);

    let test_env = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "RUST_TEST_THREADS=3 cargo test",
        &config,
    );
    assert_eq!(test_env, 3);

    let check_default =
        estimate_cores_for_command(Some(CompilationKind::CargoCheck), "cargo check", &config);
    assert_eq!(check_default, 3);
}

// =========================================================================
// Classification + threshold interaction tests
// =========================================================================

#[test]
fn test_cargo_xwin_quoted_options_preserve_classification_and_admission() {
    use rch_common::admit_preflight::{preflight, required_os_for_command};
    use rch_common::patterns::cargo_xwin_compilation_kind;

    let _guard = test_guard!();
    for (subcommand, kind, family) in [
        ("build", CompilationKind::CargoBuild, "cargo_build"),
        ("check", CompilationKind::CargoCheck, "cargo_check"),
        ("clippy", CompilationKind::CargoClippy, "cargo_clippy"),
    ] {
        for (prefix, toolchain) in [
            (vec!["cargo", "--config=build.jobs=2", "xwin"], None),
            (
                vec![
                    "cargo",
                    "+nightly-2026-08-31",
                    "--config=build.jobs=2",
                    "xwin",
                ],
                Some("nightly-2026-08-31"),
            ),
            (vec!["cargo-xwin"], None),
            (vec!["cargo-xwin", "xwin"], None),
            (
                vec![
                    "env",
                    "RCH_XWIN_NOTE=placeholder --target=aarch64-apple-darwin",
                    "cargo",
                    "--config=build.jobs=2",
                    "xwin",
                ],
                None,
            ),
        ] {
            for (target, expected_os) in [
                ("x86_64-pc-windows-msvc", None),
                ("aarch64-pc-windows-msvc", None),
                ("aarch64-apple-darwin", Some("darwin")),
            ] {
                let target_argument = format!("--target={target}");
                let mut argv = prefix.clone();
                argv.extend([
                    subcommand,
                    "--config=build.jobs=2",
                    "--locked",
                    "--all-targets",
                    target_argument.as_str(),
                ]);
                if subcommand == "clippy" {
                    argv.extend(["--", "-D", "warnings"]);
                }
                let command = shell_words::join(&argv);
                assert!(command.contains("'--config=build.jobs=2'"), "{command}");
                assert!(
                    command.contains(&format!("'{target_argument}'")),
                    "{command}"
                );
                assert_eq!(
                    cargo_xwin_compilation_kind(&command),
                    Some(kind),
                    "{command}"
                );
                let classification = classify_command(&command);
                assert!(classification.is_compilation, "{command}");
                assert_eq!(classification.kind, Some(kind), "{command}");

                let result = preflight(&command, true);
                let expected_toolchains: Vec<String> = toolchain
                    .into_iter()
                    .map(|value| value.to_string())
                    .collect();
                assert!(result.is_compilation, "{command}");
                assert_eq!(result.family.as_deref(), Some(family), "{command}");
                assert!(result.required.needs_cargo, "{command}");
                assert_eq!(
                    result.required.needs_targets,
                    vec![target.to_string()],
                    "{command}"
                );
                assert_eq!(
                    result.required.needs_toolchains, expected_toolchains,
                    "{command}"
                );
                assert_eq!(
                    result.required.needs_os.as_deref(),
                    expected_os,
                    "{command}"
                );
                assert_eq!(
                    required_os_for_command(&command).as_deref(),
                    expected_os,
                    "{command}"
                );
                let requirement = result.required.to_requirement(1);
                assert!(requirement.needs_cargo, "{command}");
                assert_eq!(
                    requirement.needs_targets, result.required.needs_targets,
                    "{command}"
                );
                assert_eq!(
                    requirement.needs_toolchains, result.required.needs_toolchains,
                    "{command}"
                );
                assert_eq!(requirement.needs_os.as_deref(), expected_os, "{command}");
            }
        }
    }
}

#[test]
fn test_cargo_xwin_quoted_mentions_and_nonliteral_options_do_not_authorize_offload() {
    use rch_common::admit_preflight::{preflight, required_os_for_command};
    use rch_common::patterns::cargo_xwin_compilation_kind;

    let _guard = test_guard!();
    for (subcommand, kind) in [
        ("build", CompilationKind::CargoBuild),
        ("check", CompilationKind::CargoCheck),
        ("clippy", CompilationKind::CargoClippy),
    ] {
        for argv in [
            vec![
                "cargo",
                "--config=xwin",
                subcommand,
                "--target",
                "x86_64-pc-windows-msvc",
            ],
            vec![
                "cargo",
                "--config",
                "xwin",
                subcommand,
                "--target",
                "x86_64-pc-windows-msvc",
            ],
            vec![
                "cargo",
                subcommand,
                "--manifest-path",
                "cargo xwin check",
                "--target",
                "x86_64-pc-windows-msvc",
            ],
        ] {
            let command = shell_words::join(&argv);
            assert_eq!(cargo_xwin_compilation_kind(&command), None, "{command}");
            assert_eq!(classify_command(&command).kind, Some(kind), "{command}");
            assert_eq!(
                preflight(&command, true).required.needs_os.as_deref(),
                Some("windows"),
                "{command}"
            );
            assert_eq!(
                required_os_for_command(&command).as_deref(),
                Some("windows"),
                "{command}"
            );
        }
    }
    for command in [
        "cargo 'xwin' check '--target=x86_64-pc-windows-msvc'",
        "cargo xwin 'check' '--target=x86_64-pc-windows-msvc'",
        "cargo-xwin 'xwin' clippy '--target=x86_64-pc-windows-msvc'",
        "cargo-xwin 'clippy' '--target=x86_64-pc-windows-msvc'",
        "'cargo-xwin' check '--target=x86_64-pc-windows-msvc'",
        "cargo xwin check '--help'",
        "cargo xwin check --config='build.jobs=2'",
    ] {
        assert_eq!(cargo_xwin_compilation_kind(command), None, "{command}");
        assert!(!classify_command(command).is_compilation, "{command}");
    }
    for value in [
        "two words",
        "a\"b",
        "a'b",
        r"a\b",
        "$value",
        "`value`",
        "a;b",
        "a|b",
        "a&b",
        "<value>",
        "(value)",
        "{a,b}",
        "*",
        "[value]",
        "#value",
        "~value",
    ] {
        let option = format!("--config={value}");
        let command = shell_words::join(["cargo", "xwin", "check", option.as_str()]);
        assert_eq!(cargo_xwin_compilation_kind(&command), None, "{command}");
        assert!(!classify_command(&command).is_compilation, "{command}");
    }
}

#[test]
fn test_classification_confidence_levels() {
    let _guard = test_guard!();
    // High confidence: explicit cargo build
    let result = classify_command("cargo build");
    assert!(result.is_compilation);
    assert!(result.confidence >= 0.90);

    // Still compilation but different command
    let result = classify_command("cargo test --release");
    assert!(result.is_compilation);
    assert!(result.confidence >= 0.85);

    // Non-compilation cargo commands should not trigger
    let result = classify_command("cargo fmt");
    assert!(!result.is_compilation);
}

#[test]
fn test_classification_bun_commands() {
    let _guard = test_guard!();
    // Bun compilation commands should be intercepted
    let result = classify_command("bun test");
    assert!(result.is_compilation);

    let result = classify_command("bun typecheck");
    assert!(result.is_compilation);

    // Bun watch modes should NOT be intercepted
    let result = classify_command("bun test --watch");
    assert!(!result.is_compilation);

    let result = classify_command("bun typecheck --watch");
    assert!(!result.is_compilation);

    // Bun package management should NOT be intercepted
    let result = classify_command("bun install");
    assert!(!result.is_compilation);

    let result = classify_command("bun add react");
    assert!(!result.is_compilation);

    let result = classify_command("bun remove react");
    assert!(!result.is_compilation);

    let result = classify_command("bun link");
    assert!(!result.is_compilation);

    // Bun execution helpers should NOT be intercepted
    let result = classify_command("bun run build");
    assert!(!result.is_compilation);

    let result = classify_command("bun build");
    assert!(!result.is_compilation);

    let result = classify_command("bun dev");
    assert!(!result.is_compilation);

    let result = classify_command("bun repl");
    assert!(!result.is_compilation);

    let result = classify_command("bun x vite build");
    assert!(!result.is_compilation);

    let result = classify_command("bunx vite build");
    assert!(!result.is_compilation);
}

#[test]
fn test_classification_c_compilers_and_build_systems() {
    let _guard = test_guard!();
    let result = classify_command("gcc -O2 -o hello hello.c");
    assert!(result.is_compilation);

    let result = classify_command("g++ -std=c++20 -o hello hello.cpp");
    assert!(result.is_compilation);

    let result = classify_command("clang -o hello hello.c");
    assert!(result.is_compilation);

    let result = classify_command("clang++ -o hello hello.cpp");
    assert!(result.is_compilation);

    let result = classify_command("make");
    assert!(result.is_compilation);

    let result = classify_command("ninja -C build");
    assert!(result.is_compilation);

    let result = classify_command("cmake --build build");
    assert!(result.is_compilation);
}

#[test]
fn test_classification_env_wrapped_commands() {
    let _guard = test_guard!();
    let result = classify_command("RUST_BACKTRACE=1 cargo test");
    assert!(result.is_compilation);

    let result = classify_command("RUST_TEST_THREADS=4 cargo test");
    assert!(result.is_compilation);
}

#[test]
fn test_classification_rejects_shell_metachars() {
    let _guard = test_guard!();
    // Issue #24: benign trailing structure (pipe to pager / background /
    // redirect) is now extracted and offloaded rather than declined.
    let result = classify_command("cargo build | tee log.txt");
    assert!(result.is_compilation, "got: {:?}", result.reason);
    assert_eq!(
        result.extracted_command.as_deref(),
        Some("cargo build | tee log.txt")
    );

    let result = classify_command("cargo build &");
    assert!(result.is_compilation, "got: {:?}", result.reason);
    assert_eq!(result.extracted_command.as_deref(), Some("cargo build &"));

    let result = classify_command("cargo build > output.log");
    assert!(result.is_compilation, "got: {:?}", result.reason);
    assert_eq!(
        result.extracted_command.as_deref(),
        Some("cargo build > output.log")
    );

    // Truly unsafe structures are still declined.
    // Subshell capture should not be intercepted.
    let result = classify_command("result=$(cargo build)");
    assert!(!result.is_compilation);
    assert!(result.reason.contains("subshell"));

    // Input redirect (transforms input) should not be intercepted.
    let result = classify_command("cargo build < input.txt");
    assert!(!result.is_compilation);
    assert!(result.reason.contains("input"));

    // Pipe into a non-pager command should not be intercepted.
    let result = classify_command("cargo build | xargs rm");
    assert!(!result.is_compilation);
    assert!(result.reason.contains("pipe"));
}

#[test]
fn test_extract_project_name() {
    let _guard = test_guard!();
    // The function uses current directory, but we can test it runs
    let project = command_parsing::extract_project_name();
    assert!(!project.is_empty());
}

/// Regression test for GitHub #9: when a custom [`PathTopologyPolicy`]
/// is supplied and the cwd lives under the configured canonical root,
/// normalization must succeed and must not fall back to the
/// default `/data/projects` root.
#[test]
fn test_extract_project_name_honors_custom_policy() {
    let _guard = test_guard!();
    use std::fs;

    // Create an isolated canonical root inside the OS temp dir.
    let tmp = std::env::temp_dir().join(format!(
        "rch_extract_custom_{}_{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
    ));
    fs::create_dir_all(&tmp).expect("create canonical root");
    let project_dir = tmp.join("sample_project");
    fs::create_dir_all(&project_dir).expect("create project dir");

    // Resolve to the real path so symlinked temp dirs (e.g. /tmp -> /private/tmp
    // on macOS) don't trip the `OutsideCanonicalRoot` check.
    let canonical_tmp = fs::canonicalize(&tmp).expect("canonicalize tmp");
    let canonical_project = fs::canonicalize(&project_dir).expect("canonicalize project");

    let policy = PathTopologyPolicy::new(canonical_tmp.clone(), canonical_tmp.clone());

    let prev_cwd = std::env::current_dir().ok();
    std::env::set_current_dir(&canonical_project).expect("cd into project dir");

    let project = extract_project_name_with_policy(&policy);

    // Restore cwd before any assertion so failure doesn't poison other tests.
    if let Some(prev) = prev_cwd {
        let _ = std::env::set_current_dir(prev);
    }
    let _ = fs::remove_dir_all(&tmp);

    // The project name must be based on the configured root's subdir,
    // and crucially must not equal "unknown" (the fallback when
    // normalization against the default `/data/projects` policy fails).
    assert!(
        project.starts_with("sample_project-"),
        "expected project name to start with sample_project-, got {:?} \
             (cwd was {:?})",
        project,
        canonical_project
    );
}

// =========================================================================
// Hook output protocol tests
// =========================================================================

#[test]
fn test_hook_output_allow_is_empty() {
    let _guard = test_guard!();
    // Allow output should serialize to nothing (empty stdout = allow)
    let output = HookOutput::allow();
    assert!(output.is_allow());
}

#[test]
fn test_hook_output_deny_serializes() {
    let _guard = test_guard!();
    let output = HookOutput::deny("Test denial reason".to_string());
    let json = serde_json::to_string(&output).expect("Should serialize");
    assert!(json.contains("deny"));
    assert!(json.contains("Test denial reason"));
}

#[test]
fn test_selected_worker_to_config() {
    let _guard = test_guard!();
    let worker = SelectedWorker {
        id: rch_common::WorkerId::new("test-worker"),
        host: "192.168.1.100".to_string(),
        user: "ubuntu".to_string(),
        identity_file: "~/.ssh/id_rsa".to_string(),
        slots_available: 8,
        speed_score: 75.5,
        declared_os: None,
    };

    let config = selected_worker_to_config(&worker);
    assert_eq!(config.id.as_str(), "test-worker");
    assert_eq!(config.host, "192.168.1.100");
    assert_eq!(config.user, "ubuntu");
    assert_eq!(config.total_slots, 8);
}

#[test]
fn test_parse_preferred_workers_dedupes_ordered_values() {
    let _guard = test_guard!();
    let workers = command_parsing::dedupe_worker_ids(command_parsing::parse_preferred_workers(
        " ts2, vmi1,,ts2 , vmi2 ",
    ));
    let ids: Vec<&str> = workers.iter().map(|worker| worker.as_str()).collect();
    assert_eq!(ids, vec!["ts2", "vmi1", "vmi2"]);
}

#[test]
fn test_parse_preferred_workers_from_toml_routing_section() {
    let _guard = test_guard!();
    let toml = r#"
[general]
enabled = true

[routing]
preferred_workers = ["hz2", " vmi1264463 ", ""]
"#;
    let ids: Vec<String> = command_parsing::parse_preferred_workers_from_toml(toml)
        .iter()
        .map(|w| w.as_str().to_string())
        .collect();
    assert_eq!(ids, vec!["hz2".to_string(), "vmi1264463".to_string()]);
}

#[test]
fn test_parse_preferred_workers_from_toml_absent_or_malformed_is_empty() {
    let _guard = test_guard!();
    assert!(
        command_parsing::parse_preferred_workers_from_toml("[general]\nenabled = true\n")
            .is_empty()
    );
    assert!(
        command_parsing::parse_preferred_workers_from_toml("[routing]\nother = 1\n").is_empty()
    );
    assert!(
        command_parsing::parse_preferred_workers_from_toml(
            "[routing]\npreferred_workers = \"hz2\"\n"
        )
        .is_empty()
    );
    assert!(command_parsing::parse_preferred_workers_from_toml("this is not toml {{{").is_empty());
    assert!(command_parsing::parse_preferred_workers_from_toml("").is_empty());
}

#[test]
fn test_preferred_workers_from_config_path_missing_file_is_empty() {
    let _guard = test_guard!();
    let missing = std::path::Path::new("/tmp/definitely-not-a-real-rch-config-xyz.toml");
    assert!(command_parsing::preferred_workers_from_config_path(missing).is_empty());
}

#[test]
fn test_remote_required_refusal_retryable_classification() {
    let _guard = test_guard!();
    // rch#31: transient capacity/daemon refusals are retryable (distinct exit
    // code 103); permanent per-invocation refusals stay EXIT_BUILD_ERROR.
    for retryable in [
        "daemon unavailable",
        "no worker assigned",
        "transfer skipped",
        "remote execution failed",
    ] {
        assert!(
            remote_required_refusal_is_retryable(retryable),
            "{retryable} should be retryable"
        );
        assert!(
            remote_required_refusal_summary(retryable).contains("retryable"),
            "{retryable} summary should carry the typed retryable marker"
        );
    }
    for permanent in ["non-compilation command", "config unavailable"] {
        assert!(
            !remote_required_refusal_is_retryable(permanent),
            "{permanent} should NOT be retryable"
        );
        assert!(
            !remote_required_refusal_summary(permanent).contains("retryable"),
            "{permanent} summary must not claim retryable"
        );
    }
}

#[test]
fn test_requested_worker_refusal_summary_is_stable_and_actionable() {
    let _guard = test_guard!();
    let response = SelectionResponse {
        worker: None,
        reason: SelectionReason::NoMatchingWorkers,
        build_id: None,
        diagnostics: None,
    };

    let summary = requested_worker_refusal_summary(&[WorkerId::new("missing")], &response)
        .expect("explicit request should produce a refusal summary");
    assert!(summary.starts_with("[RCH-I001]"));
    assert!(summary.contains("requested worker set [missing]"));
    assert!(summary.contains("run `rch diagnose -- <command>`"));
}

#[test]
fn test_selected_worker_must_belong_to_requested_set() {
    let _guard = test_guard!();
    let requested = [WorkerId::new("worker-a"), WorkerId::new("worker-b")];
    assert!(selected_worker_is_requested(
        &WorkerId::new("worker-b"),
        &requested
    ));
    assert!(!selected_worker_is_requested(
        &WorkerId::new("worker-c"),
        &requested
    ));
    assert!(selected_worker_is_requested(
        &WorkerId::new("automatic"),
        &[]
    ));
}

#[test]
fn exact_exec_worker_overrides_preferences_and_retries_cannot_escape() {
    let _guard = test_guard!();
    let inherited = vec![
        WorkerId::new("project-worker"),
        WorkerId::new("environment-worker"),
    ];
    let mut inherited_reads = 0;
    let pinned = exec_worker_preferences(Some(WorkerId::new("native-worker")), || {
        inherited_reads += 1;
        inherited.clone()
    });
    assert_eq!(
        inherited_reads, 0,
        "an explicit pin must not read merged preferences"
    );
    assert_eq!(pinned, vec![WorkerId::new("native-worker")]);
    assert!(selected_worker_is_requested(
        &WorkerId::new("native-worker"),
        &pinned
    ));
    assert!(!selected_worker_is_requested(
        &WorkerId::new("project-worker"),
        &pinned
    ));
    assert!(!selected_worker_is_requested(
        &WorkerId::new("environment-worker"),
        &pinned
    ));
    assert_eq!(
        exec_worker_preferences(None, || inherited.clone()),
        inherited
    );
    // The same original singleton feeds the capacity retry picker. These are
    // policy inputs, not a live worker/reservation or compilation receipt.
    let snapshots = vec![
        WorkerCapacitySnapshot {
            id: WorkerId::new("project-worker"),
            healthy: true,
            pressure_critical: false,
            free_slots: 64,
            total_slots: 64,
            speed_score: 100.0,
            memory_pressure: None,
        },
        WorkerCapacitySnapshot {
            id: WorkerId::new("native-worker"),
            healthy: true,
            pressure_critical: false,
            free_slots: 4,
            total_slots: 4,
            speed_score: 50.0,
            memory_pressure: None,
        },
    ];
    assert_eq!(
        pick_bigger_worker(&snapshots, &[], &pinned),
        Some(WorkerId::new("native-worker"))
    );
    assert!(pick_bigger_worker(&snapshots, &[WorkerId::new("native-worker")], &pinned).is_none());
}

// =========================================================================
// Mock daemon socket tests
// =========================================================================

#[tokio::test]
async fn test_daemon_query_missing_socket() {
    // Query a non-existent socket should fail gracefully
    let result = query_daemon(
        "/tmp/nonexistent_rch_test.sock",
        "testproj",
        4,
        0,
        "cargo build",
        None,
        RequiredRuntime::None,
        CommandPriority::Normal,
        100, // 100µs classification time
        None,
        None,
        false,
        &[],
        false,
        &[],
    )
    .await;
    assert!(result.is_err());
    let err_msg = result.unwrap_err().to_string();
    assert!(err_msg.contains("not found") || err_msg.contains("No such file"));
}

fn queued_selection_test_lease(path: PathBuf) -> DurableLeaseWriter {
    let writer = DurableLeaseWriter {
        path,
        #[cfg(unix)]
        recovery_ownership: None,
        lease: Arc::new(std::sync::Mutex::new(DurableJobLease::new(
            JobIdentity::new_local(),
            std::process::id(),
            None,
            None,
            0,
            false,
            true,
            "test-fingerprint".into(),
        ))),
    };
    writer.persist().unwrap();
    writer
}

#[test]
fn compiler_admission_reference_binds_one_durable_attempt_without_rounding() {
    let _guard = test_guard!();
    let retained = tempfile::tempdir().unwrap().keep();
    let journal = retained.join("lease.json");
    let writer = queued_selection_test_lease(journal.clone());
    let wrapper = writer.wrapper_id();
    let worker = WorkerId::new("attempt-worker-fixture");
    let build = 9_007_199_254_740_993_u64;
    let before = std::fs::read(&journal).unwrap();
    for invalid_build in [0, 1_u64 << 63, u64::MAX] {
        assert!(writer.admit(invalid_build, &worker).is_err());
        assert!(
            writer
                .admission_reference(&wrapper, invalid_build, &worker)
                .is_err()
        );
    }
    for invalid_worker in ["", " \t"] {
        assert!(writer.admit(build, &WorkerId::new(invalid_worker)).is_err());
    }
    assert_eq!(std::fs::read(&journal).unwrap(), before);
    assert_eq!(
        absolute_lease_path(PathBuf::from("relative-journal.json")).unwrap(),
        std::env::current_dir()
            .unwrap()
            .join("relative-journal.json")
    );
    assert_eq!(absolute_lease_path(journal.clone()).unwrap(), journal);
    assert!(
        writer
            .admission_reference(&wrapper, build, &worker)
            .is_err()
    );
    writer.admit(build, &worker).unwrap();
    let reference = writer
        .admission_reference(&wrapper, build, &worker)
        .unwrap();
    let value = serde_json::to_value(&reference).unwrap();
    assert_eq!(value["remote_build_id"], "9007199254740993");
    assert_eq!(value["local_wrapper_id"], wrapper);
    assert_eq!(value["worker_id"], worker.as_str());
    assert_eq!(value["journal_path"], journal.to_str().unwrap());
    assert_eq!(value["terminal_acknowledged"], false);
    let persisted: DurableJobLease =
        serde_json::from_slice(&std::fs::read(&journal).unwrap()).unwrap();
    assert_eq!(persisted.identity.remote_build_id, Some(build));
    assert_eq!(persisted.worker_id.as_deref(), Some(worker.as_str()));
    assert!(
        writer
            .admission_reference("other-wrapper", build, &worker)
            .is_err()
    );
    assert!(
        writer
            .admission_reference(&wrapper, build + 1, &worker)
            .is_err()
    );
    assert!(
        writer
            .admission_reference(&wrapper, build, &WorkerId::new("other-worker"))
            .is_err()
    );
    writer.record_exit(0).unwrap();
    let intent = writer.begin_retry_selection(true).unwrap();
    assert!(
        writer
            .admission_reference(&wrapper, build, &worker)
            .is_err()
    );
    writer.restore_after_unadmitted_retry(intent).unwrap();
    assert!(
        !writer
            .admission_reference(&wrapper, build, &worker)
            .unwrap()
            .terminal_acknowledged
    );
    assert!(
        writer
            .admission_reference(&wrapper, build + 1, &worker)
            .is_err()
    );
    writer.acknowledge_terminal().unwrap();
    assert!(
        writer
            .admission_reference(&wrapper, build, &worker)
            .unwrap()
            .terminal_acknowledged
    );
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStringExt;
        let mut invalid_path = writer.clone();
        invalid_path.path = retained.join(std::ffi::OsString::from_vec(vec![0xff]));
        assert!(
            invalid_path
                .admission_reference(&wrapper, build, &worker)
                .is_err()
        );
    }
    // Real retained journal I/O with supplied fixture identity, not a live
    // worker, SDK, reservation or compilation proof.
    assert!(journal.is_file());
}

#[cfg(unix)]
#[test]
#[cfg_attr(target_vendor = "apple", allow(unused_imports, unused_variables))]
fn recovery_journal_reader_keeps_large_receipts_and_rejects_redirected_entries() {
    use rustix::fs::{Mode, OFlags};
    use std::os::fd::AsFd;
    use std::os::unix::fs::FileTypeExt;

    let _guard = test_guard!();
    let retained = tempfile::tempdir().unwrap().keep();
    let journal = retained.join("valid.json");
    let writer = queued_selection_test_lease(journal.clone());
    writer
        .set_recovery(serde_json::json!({"retained_fixture": "x".repeat(2 * 1024 * 1024)}))
        .unwrap();
    let original = std::fs::read(&journal).unwrap();
    let wrapper = writer.wrapper_id();
    let read = DurableLeaseWriter::read_journal(&journal, &wrapper).unwrap();
    assert_eq!(read, writer.snapshot());
    assert!(DurableLeaseWriter::read_journal(&journal, "different-wrapper").is_err());
    let link = retained.join("linked.json");
    std::os::unix::fs::symlink(&journal, &link).unwrap();
    assert!(DurableLeaseWriter::read_journal(&link, &wrapper).is_err());
    let linked_directory = retained.join("linked-directory");
    std::os::unix::fs::symlink(&retained, &linked_directory).unwrap();
    assert!(
        DurableLeaseWriter::read_journal(&linked_directory.join("valid.json"), &wrapper).is_err()
    );
    let wrong_schema = retained.join("wrong-schema.json");
    let mut changed = read;
    changed.schema_version = 2;
    std::fs::write(&wrong_schema, serde_json::to_vec(&changed).unwrap()).unwrap();
    assert!(DurableLeaseWriter::read_journal(&wrong_schema, &wrapper).is_err());
    let directory =
        rustix::fs::open(&retained, OFlags::RDONLY | OFlags::DIRECTORY, Mode::empty()).unwrap();
    #[cfg(not(target_vendor = "apple"))]
    rustix::fs::mkfifoat(directory.as_fd(), c"fifo.json", Mode::RUSR | Mode::WUSR).unwrap();
    let fifo = retained.join("fifo.json");
    // rustix has no mkfifoat on Apple targets and this crate forbids unsafe
    // code, so make the FIFO by path; `directory` is open on `retained`.
    #[cfg(target_vendor = "apple")]
    assert!(
        std::process::Command::new("/usr/bin/mkfifo")
            .args(["-m", "600"])
            .arg(&fifo)
            .status()
            .unwrap()
            .success()
    );
    let (sender, receiver) = std::sync::mpsc::channel();
    let fifo_read = fifo.clone();
    let reader = std::thread::spawn(move || {
        sender
            .send(DurableLeaseWriter::read_journal(&fifo_read, &wrapper))
            .unwrap();
    });
    let error = receiver
        .recv_timeout(std::time::Duration::from_secs(2))
        .expect("recovery journal read blocked on a FIFO with no writer")
        .unwrap_err();
    reader.join().unwrap();
    assert!(format!("{error:#}").contains("journal is not a regular file"));
    assert!(
        std::fs::symlink_metadata(fifo)
            .unwrap()
            .file_type()
            .is_fifo()
    );
    assert_eq!(std::fs::read(&journal).unwrap(), original);
    assert_eq!(std::fs::read_link(link).unwrap(), journal);
    // Actual retained file I/O and supplied journal identity only; no daemon,
    // owner takeover, compiler execution, SDK or native qualification.
}

#[test]
fn terminal_job_report_uses_one_current_admission_and_observed_exit() {
    let _guard = test_guard!();
    let retained = tempfile::tempdir().unwrap().keep();
    let writer = queued_selection_test_lease(retained.join("job.json"));
    let wrapper = writer.wrapper_id();
    assert!(
        writer
            .terminal_job_report(&wrapper, "completed", None)
            .is_err()
    );
    let build = 9_007_199_254_740_993_u64;
    let worker = WorkerId::new("recovery-worker-fixture");
    writer.admit(build, &worker).unwrap();
    writer.record_exit(102).unwrap();
    assert!(
        writer
            .terminal_job_report(&wrapper, "recovered", Some(102))
            .is_err()
    );
    writer.acknowledge_terminal().unwrap();
    let report = writer
        .terminal_job_report(&wrapper, "recovered", Some(102))
        .unwrap();
    assert_eq!(report["identity"]["remote_build_id"], build);
    assert_eq!(report["admission"]["remote_build_id"], "9007199254740993");
    assert_eq!(report["admission"]["worker_id"], worker.as_str());
    assert_eq!(report["admission"]["terminal_acknowledged"], true);
    assert_eq!(report["exit_code"], 102);
    assert_eq!(
        report["admission"]["local_wrapper_id"],
        report["identity"]["local_wrapper_id"]
    );
    assert!(
        writer
            .terminal_job_report(&wrapper, "recovered", Some(0))
            .is_err()
    );
    assert!(
        writer
            .terminal_job_report("other-wrapper", "completed", None)
            .is_err()
    );
    assert!(
        writer
            .terminal_job_report(&wrapper, "active", None)
            .is_err()
    );
    let unadmitted = queued_selection_test_lease(retained.join("unadmitted.json"));
    let unadmitted_wrapper = unadmitted.wrapper_id();
    unadmitted.record_exit(EXIT_BUILD_ERROR).unwrap();
    unadmitted.acknowledge_terminal().unwrap();
    let no_admission = unadmitted
        .terminal_job_report(&unadmitted_wrapper, "completed", Some(EXIT_BUILD_ERROR))
        .unwrap();
    assert!(no_admission["admission"].is_null());
    assert!(no_admission["identity"]["remote_build_id"].is_null());
    let missing_exit = queued_selection_test_lease(retained.join("missing-exit.json"));
    let missing_bytes = std::fs::read(&missing_exit.path).unwrap();
    assert!(missing_exit.acknowledge_terminal().is_err());
    assert_eq!(std::fs::read(&missing_exit.path).unwrap(), missing_bytes);
    // Retain the old malformed-journal reader negative without allowing the
    // actual writer to create that state. This is a supplied legacy fixture.
    let mut legacy = missing_exit.snapshot();
    legacy.acknowledge_terminal(1);
    let legacy_path = retained.join("legacy-unknown-exit.json");
    std::fs::write(&legacy_path, serde_json::to_vec(&legacy).unwrap()).unwrap();
    let legacy_writer = DurableLeaseWriter {
        lease: Arc::new(std::sync::Mutex::new(
            DurableLeaseWriter::read_journal(&legacy_path, &legacy.identity.local_wrapper_id)
                .unwrap(),
        )),
        path: legacy_path,
        #[cfg(unix)]
        recovery_ownership: None,
    };
    assert!(
        legacy_writer
            .terminal_job_report(&missing_exit.wrapper_id(), "completed", None)
            .is_err()
    );
    for admitted in [true, false] {
        let mut incomplete = writer.snapshot();
        if admitted {
            incomplete.worker_id = None;
        } else {
            incomplete.identity.remote_build_id = None;
        }
        let invalid = DurableLeaseWriter {
            path: retained.join("incomplete-admission-fixture.json"),
            #[cfg(unix)]
            recovery_ownership: None,
            lease: Arc::new(std::sync::Mutex::new(incomplete)),
        };
        assert!(
            invalid
                .terminal_job_report(&wrapper, "completed", None)
                .is_err()
        );
    }
    let original = std::fs::read(&writer.path).unwrap();
    assert_eq!(
        writer
            .terminal_job_report(&wrapper, "recovered", Some(102))
            .unwrap(),
        report
    );
    assert_eq!(std::fs::read(&writer.path).unwrap(), original);
    // Supplied fixture identity/terminal journal are not an actual reservation
    // or replayed original ExecResultEnvelope, SDK or returned-artifact proof.
}

fn retry_selection_test_lease(path: PathBuf) -> DurableLeaseWriter {
    let writer = queued_selection_test_lease(path);
    writer.admit(41, &WorkerId::new("previous-worker")).unwrap();
    writer
        .set_recovery(serde_json::json!({
            "retired": true, "returned": 137,
            "wrapper_id": writer.wrapper_id(), "build_id": 41,
            "worker": {"id": "previous-worker"},
        }))
        .unwrap();
    writer.record_exit(137).unwrap();
    writer
}

#[test]
fn terminal_acknowledgement_requires_an_observed_result_and_preserves_its_final_value() {
    let _guard = test_guard!();
    let retained = tempfile::tempdir().unwrap().keep();
    for exit in [0, EXIT_BUILD_ERROR, 102, 130] {
        let writer = queued_selection_test_lease(retained.join(format!("exit-{exit}.json")));
        let pending = writer.snapshot();
        let bytes = std::fs::read(&writer.path).unwrap();
        assert!(writer.acknowledge_terminal().is_err());
        assert_eq!(writer.snapshot(), pending);
        assert_eq!(std::fs::read(&writer.path).unwrap(), bytes);
        writer.record_exit(exit).unwrap();
        writer.acknowledge_terminal().unwrap();
        let terminal = writer.snapshot();
        let bytes = std::fs::read(&writer.path).unwrap();
        assert!(terminal.terminal_acknowledged);
        assert_eq!(terminal.exit_code, Some(exit));
        writer.record_exit(exit).unwrap();
        assert_eq!(std::fs::read(&writer.path).unwrap(), bytes);
        assert!(writer.record_exit(exit + 1).is_err());
        assert_eq!(writer.snapshot(), terminal);
        assert_eq!(std::fs::read(&writer.path).unwrap(), bytes);
    }
    // Actual retained writer I/O with supplied result values, no daemon,
    // compiler execution or performance/native qualification.
}

#[test]
fn daemon_completion_cannot_replace_known_command_or_delivery_results() {
    let _guard = test_guard!();
    let retained = tempfile::tempdir().unwrap().keep();
    let writer = queued_selection_test_lease(retained.join("known-command.json"));
    writer.admit(42, &WorkerId::new("worker-fixture")).unwrap();
    writer.record_exit(102).unwrap();
    let observed = writer.snapshot();
    let bytes = std::fs::read(&writer.path).unwrap();
    assert!(
        writer
            .acknowledge_observed_completion(&observed, 0)
            .is_err()
    );
    assert_eq!(writer.snapshot(), observed);
    assert_eq!(std::fs::read(&writer.path).unwrap(), bytes);
    writer
        .acknowledge_observed_completion(&observed, 102)
        .unwrap();
    assert_eq!(writer.snapshot().exit_code, Some(102));
    assert!(writer.snapshot().terminal_acknowledged);

    let delivery = queued_selection_test_lease(retained.join("known-delivery.json"));
    delivery
        .admit(43, &WorkerId::new("worker-fixture"))
        .unwrap();
    // These are explicitly distinct facts: compiler/daemon success and a
    // failed artifact delivery. Retirement cannot make either one the other.
    delivery
        .set_recovery(serde_json::json!({
            "returned": 102, "retired": true, "daemon_exit_code": 0,
        }))
        .unwrap();
    let observed = delivery.snapshot();
    let bytes = std::fs::read(&delivery.path).unwrap();
    assert!(
        delivery
            .acknowledge_observed_completion(&observed, 0)
            .is_err()
    );
    assert_eq!(delivery.snapshot(), observed);
    assert_eq!(std::fs::read(&delivery.path).unwrap(), bytes);
    delivery.record_exit(0).unwrap();
    let wrong_result = delivery.snapshot();
    let wrong_bytes = std::fs::read(&delivery.path).unwrap();
    assert!(delivery.acknowledge_terminal().is_err());
    assert_eq!(delivery.snapshot(), wrong_result);
    assert_eq!(std::fs::read(&delivery.path).unwrap(), wrong_bytes);
    delivery.record_exit(102).unwrap();
    delivery.acknowledge_terminal().unwrap();
    let terminal = delivery.snapshot();
    assert_eq!(terminal.exit_code, Some(102));
    assert!(terminal.terminal_acknowledged);
    assert_eq!(terminal.recovery.unwrap()["daemon_exit_code"], 0);

    let receipt = queued_selection_test_lease(retained.join("retired-receipt.json"));
    receipt.admit(44, &WorkerId::new("worker-fixture")).unwrap();
    receipt
        .set_recovery(serde_json::json!({
            "returned": 130, "retired": true, "daemon_exit_code": 0,
        }))
        .unwrap();
    assert!(receipt.snapshot().exit_code.is_none());
    receipt.acknowledge_terminal().unwrap();
    let terminal = receipt.snapshot();
    let disk: DurableJobLease =
        serde_json::from_slice(&std::fs::read(&receipt.path).unwrap()).unwrap();
    assert_eq!(disk, terminal);
    assert_eq!(terminal.exit_code, Some(130));
    assert!(terminal.terminal_acknowledged);
    assert_eq!(terminal.recovery.unwrap()["daemon_exit_code"], 0);

    let unfinished = queued_selection_test_lease(retained.join("unfinished-receipt.json"));
    for recipe in [
        serde_json::json!({"returned": 130, "retired": false}),
        serde_json::json!({"retired": true}),
        serde_json::json!({"returned": i64::from(i32::MAX) + 1, "retired": true}),
    ] {
        unfinished.set_recovery(recipe).unwrap();
        let before = unfinished.snapshot();
        let bytes = std::fs::read(&unfinished.path).unwrap();
        assert!(unfinished.acknowledge_terminal().is_err());
        assert_eq!(unfinished.snapshot(), before);
        assert_eq!(std::fs::read(&unfinished.path).unwrap(), bytes);
    }
    // Supplied delivery/daemon facts test the real transactional writer only;
    // they are not live service, source-release or SDK observations.
}

fn read_retry_lease(writer: &DurableLeaseWriter) -> DurableJobLease {
    serde_json::from_slice(&std::fs::read(&writer.path).unwrap()).unwrap()
}

fn retry_unassigned_response() -> SelectionResponse {
    SelectionResponse {
        worker: None,
        build_id: None,
        reason: SelectionReason::AllWorkersBusy,
        diagnostics: None,
    }
}

fn assert_retry_pending(writer: &DurableLeaseWriter, previous: &DurableJobLease) {
    let disk = read_retry_lease(writer);
    assert_eq!(disk, writer.snapshot());
    assert_eq!(disk.phase, "selection_pending");
    assert_eq!(
        disk.state,
        rch_common::job_identity::JobLifecycleState::Queued
    );
    assert_eq!(
        disk.identity.local_wrapper_id,
        previous.identity.local_wrapper_id
    );
    assert_eq!(disk.wrapper_pid, previous.wrapper_pid);
    assert_eq!(disk.process_birth, previous.process_birth);
    assert_eq!(disk.process_start_ticks, previous.process_start_ticks);
    assert_eq!(disk.boot_id, previous.boot_id);
    assert_eq!(disk.command_fingerprint, previous.command_fingerprint);
    assert_eq!(disk.strict_remote, previous.strict_remote);
    assert_eq!(disk.self_healing_enabled, previous.self_healing_enabled);
    assert!(disk.identity.remote_build_id.is_none());
    assert!(disk.worker_id.is_none());
    assert!(disk.recovery.is_none());
    assert!(disk.exit_code.is_none());
    assert!(!disk.terminal_acknowledged);
}

#[tokio::test]
async fn retry_selection_unconfirmed_retains_new_intent_and_never_exhausts() {
    let directory = tempfile::tempdir().unwrap();
    let writer = retry_selection_test_lease(directory.path().join("lease.json"));
    let previous = writer.snapshot();
    let mut exhausted = false;
    let result: anyhow::Result<()> = async {
        dispatch_retry_selection(&writer, true, async || {
            // This is the production dispatch boundary. Evidence is durable
            // before a request can create another reservation.
            assert_retry_pending(&writer, &previous);
            anyhow::bail!(
                anyhow::anyhow!("reply lost after admission")
                    .context(daemon_ipc::SelectionOutcomeUnconfirmed)
                    .context("outer transport context")
            );
        })
        .await?;
        exhausted = true;
        writer.acknowledge_terminal()?;
        Ok(())
    }
    .await;
    assert!(
        result
            .unwrap_err()
            .downcast_ref::<daemon_ipc::SelectionOutcomeUnconfirmed>()
            .is_some()
    );
    assert!(
        !exhausted,
        "uncertain selection must not reach fault.on_exhaust"
    );
    let disk = read_retry_lease(&writer);
    assert_eq!(disk, writer.snapshot());
    assert_eq!(disk.phase, "selection_unconfirmed");
    assert!(disk.identity.remote_build_id.is_none());
    assert!(disk.worker_id.is_none());
    assert!(disk.recovery.is_none());
    assert!(disk.exit_code.is_none());
    assert!(!disk.terminal_acknowledged);
    assert!(writer.acknowledge_terminal().is_err());
    assert!(writer.record_exit(137).is_err());
    assert!(writer.heartbeat("finalize").is_err());
    assert!(writer.set_recovery(previous.recovery.unwrap()).is_err());
    assert_eq!(read_retry_lease(&writer), disk);
    assert!(
        dispatch_retry_selection(&writer, true, async || {
            panic!("an uncertain selection cannot dispatch again");
        })
        .await
        .is_err()
    );
}

#[tokio::test]
async fn retry_selection_definitive_refusal_restores_previous_settled_evidence() {
    for preconnect_error in [false, true] {
        let directory = tempfile::tempdir().unwrap();
        let writer = retry_selection_test_lease(directory.path().join("lease.json"));
        let previous = writer.snapshot();
        let bytes = std::fs::read(&writer.path).unwrap();
        let response = dispatch_retry_selection(&writer, true, async || {
            assert_retry_pending(&writer, &previous);
            if preconnect_error {
                anyhow::bail!(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "socket absent before dispatch"
                ));
            }
            Ok(retry_unassigned_response())
        })
        .await
        .unwrap();
        assert_eq!(response.is_none(), preconnect_error);
        assert_eq!(writer.snapshot(), previous);
        assert_eq!(std::fs::read(&writer.path).unwrap(), bytes);
        writer.acknowledge_terminal().unwrap();
        assert_eq!(read_retry_lease(&writer).exit_code, Some(137));
    }
}

#[tokio::test]
async fn retry_selection_selected_response_stays_pending_until_new_admission() {
    let directory = tempfile::tempdir().unwrap();
    let writer = retry_selection_test_lease(directory.path().join("lease.json"));
    let previous = writer.snapshot();
    let response = dispatch_retry_selection(&writer, true, async || {
        assert_retry_pending(&writer, &previous);
        Ok(SelectionResponse {
            worker: Some(rch_common::SelectedWorker {
                id: WorkerId::new("next-worker"),
                host: "not-contacted.invalid".into(),
                user: "test".into(),
                identity_file: "/unused/key".into(),
                slots_available: 4,
                speed_score: 90.0,
                declared_os: None,
            }),
            build_id: Some(42),
            reason: SelectionReason::Success,
            diagnostics: None,
        })
    })
    .await
    .unwrap()
    .unwrap();
    assert_retry_pending(&writer, &previous);
    assert!(writer.acknowledge_terminal().is_err());
    writer
        .admit(response.build_id.unwrap(), &response.worker.unwrap().id)
        .unwrap();
    let disk = read_retry_lease(&writer);
    assert_eq!(
        disk.identity.local_wrapper_id,
        previous.identity.local_wrapper_id
    );
    assert_eq!(disk.identity.remote_build_id, Some(42));
    assert_eq!(disk.worker_id.as_deref(), Some("next-worker"));
    assert_eq!(disk.phase, "sync_up");
    assert!(disk.recovery.is_none() && disk.exit_code.is_none());
    assert!(!disk.terminal_acknowledged);
    assert!(writer.confirm_selection_cancelled().is_err());
}

#[tokio::test]
async fn retry_selection_cancelled_response_requires_explicit_terminal_receipt() {
    let directory = tempfile::tempdir().unwrap();
    let writer = retry_selection_test_lease(directory.path().join("lease.json"));
    let previous = writer.snapshot();
    let response = dispatch_retry_selection(&writer, true, async || {
        assert_retry_pending(&writer, &previous);
        Ok(SelectionResponse {
            reason: SelectionReason::SelectionError("job_cancelled_before_start".into()),
            ..retry_unassigned_response()
        })
    })
    .await
    .unwrap()
    .unwrap();
    assert!(selection_cancelled_before_start(&response));
    assert_retry_pending(&writer, &previous);
    assert!(writer.acknowledge_terminal().is_err());
    writer.confirm_selection_cancelled().unwrap();
    let disk = read_retry_lease(&writer);
    assert_eq!(disk.exit_code, Some(130));
    assert_eq!(disk.phase, "finished");
    assert!(disk.terminal_acknowledged);
    assert!(disk.identity.remote_build_id.is_none() && disk.worker_id.is_none());
    assert!(writer.heartbeat("selection_unconfirmed").is_err());
    assert_eq!(read_retry_lease(&writer), disk);
}

#[test]
fn retry_selection_old_observed_completion_cannot_acknowledge_new_admission() {
    let directory = tempfile::tempdir().unwrap();
    let writer = retry_selection_test_lease(directory.path().join("lease.json"));
    // An older heartbeat retained this observation while waiting for the
    // daemon's cancellation/completion reply.
    let observed = writer.snapshot();
    writer.begin_retry_selection(true).unwrap();
    let pending = std::fs::read(&writer.path).unwrap();
    assert!(
        writer
            .acknowledge_observed_completion(&observed, 137)
            .is_err()
    );
    assert_eq!(std::fs::read(&writer.path).unwrap(), pending);
    writer.admit(42, &WorkerId::new("next-worker")).unwrap();
    writer
        .set_recovery(serde_json::json!({"retired": true, "returned": 0}))
        .unwrap();
    let next = writer.snapshot();
    let bytes = std::fs::read(&writer.path).unwrap();
    assert!(
        writer
            .acknowledge_observed_completion(&observed, 137)
            .is_err()
    );
    assert_eq!(writer.snapshot(), next);
    assert_eq!(std::fs::read(&writer.path).unwrap(), bytes);
    assert_eq!(next.identity.remote_build_id, Some(42));
    assert!(next.exit_code.is_none() && !next.terminal_acknowledged);
    // The next attempt's own exact receipt can still complete normally.
    writer.acknowledge_observed_completion(&next, 0).unwrap();
    let finished = read_retry_lease(&writer);
    assert_eq!(finished.identity, next.identity);
    assert_eq!(finished.worker_id, next.worker_id);
    assert_eq!(finished.exit_code, Some(0));
    assert!(finished.terminal_acknowledged);
}

#[test]
fn retry_selection_observed_completion_requires_worker_and_delivery_evidence() {
    let directory = tempfile::tempdir().unwrap();
    let writer = retry_selection_test_lease(directory.path().join("lease.json"));
    let observed = writer.snapshot();
    let mut wrong_worker = observed.clone();
    wrong_worker.worker_id = Some("other-worker".into());
    assert!(
        writer
            .acknowledge_observed_completion(&wrong_worker, 137)
            .is_err()
    );
    assert_eq!(read_retry_lease(&writer), observed);
    for recipe in [
        serde_json::json!({"retired": false, "returned": 137}),
        serde_json::json!({"retired": true}),
    ] {
        writer.set_recovery(recipe).unwrap();
        let before = writer.snapshot();
        assert!(
            writer
                .acknowledge_observed_completion(&observed, 137)
                .is_err()
        );
        assert_eq!(writer.snapshot(), before);
        assert_eq!(read_retry_lease(&writer), before);
    }
    writer
        .set_recovery(observed.recovery.clone().unwrap())
        .unwrap();
    writer
        .acknowledge_observed_completion(&observed, 137)
        .unwrap();
    let bytes = std::fs::read(&writer.path).unwrap();
    writer
        .acknowledge_observed_completion(&observed, 137)
        .unwrap();
    assert_eq!(std::fs::read(&writer.path).unwrap(), bytes);
    assert!(
        writer
            .acknowledge_observed_completion(&observed, 130)
            .is_err()
    );
    assert_eq!(std::fs::read(&writer.path).unwrap(), bytes);
}

#[tokio::test]
async fn retry_selection_requires_both_release_and_source_retirement_before_dispatch() {
    for (release_acknowledged, source_retired) in [(false, true), (true, false)] {
        let directory = tempfile::tempdir().unwrap();
        let writer = retry_selection_test_lease(directory.path().join("lease.json"));
        if !source_retired {
            let mut recipe = writer.snapshot().recovery.unwrap();
            recipe["retired"] = serde_json::Value::Bool(false);
            writer.set_recovery(recipe).unwrap();
        }
        let previous = writer.snapshot();
        let bytes = std::fs::read(&writer.path).unwrap();
        let result = dispatch_retry_selection(&writer, release_acknowledged, async || {
            panic!("unreleased prior ownership must prevent query dispatch");
        })
        .await;
        assert!(result.is_err());
        assert_eq!(writer.snapshot(), previous);
        assert_eq!(std::fs::read(&writer.path).unwrap(), bytes);
    }
}

#[tokio::test]
async fn retry_selection_failed_intent_publication_does_not_dispatch_or_change_memory() {
    let directory = tempfile::tempdir().unwrap();
    let writer = retry_selection_test_lease(directory.path().join("lease.json"));
    let previous = writer.snapshot();
    let bytes = std::fs::read(&writer.path).unwrap();
    // A real atomic file publication cannot replace a directory. Keep the
    // original journal available to establish that no state was lost.
    let blocked = DurableLeaseWriter {
        path: directory.path().to_path_buf(),
        #[cfg(unix)]
        recovery_ownership: None,
        lease: writer.lease.clone(),
    };
    let result = dispatch_retry_selection(&blocked, true, async || {
        panic!("failed durable intent must prevent network dispatch");
    })
    .await;
    assert!(result.is_err());
    assert_eq!(writer.snapshot(), previous);
    assert_eq!(std::fs::read(&writer.path).unwrap(), bytes);
}

#[tokio::test]
async fn retry_selection_late_refusal_cannot_restore_over_confirmed_cancellation() {
    let directory = tempfile::tempdir().unwrap();
    let writer = retry_selection_test_lease(directory.path().join("lease.json"));
    let result = dispatch_retry_selection(&writer, true, async || {
        writer.confirm_selection_cancelled().unwrap();
        Ok(retry_unassigned_response())
    })
    .await;
    assert!(result.is_err());
    let disk = read_retry_lease(&writer);
    assert_eq!(disk, writer.snapshot());
    assert!(disk.terminal_acknowledged);
    assert_eq!(disk.exit_code, Some(130));
    assert!(disk.identity.remote_build_id.is_none());
    assert!(disk.recovery.is_none());
}

#[tokio::test]
async fn retry_selection_dropped_query_leaves_durable_pending_without_old_receipt() {
    let directory = tempfile::tempdir().unwrap();
    let writer = retry_selection_test_lease(directory.path().join("lease.json"));
    let previous = writer.snapshot();
    let result = tokio::time::timeout(
        Duration::from_millis(10),
        dispatch_retry_selection(&writer, true, async || {
            assert_retry_pending(&writer, &previous);
            std::future::pending().await
        }),
    )
    .await;
    assert!(result.is_err());
    assert_retry_pending(&writer, &previous);
    assert!(writer.heartbeat("finalize").is_err());
    assert!(writer.record_exit(137).is_err());
    assert!(
        writer
            .set_recovery(previous.recovery.clone().unwrap())
            .is_err()
    );
    assert!(writer.acknowledge_terminal().is_err());
}

#[cfg(unix)]
#[tokio::test]
async fn retry_failover_socket_preserves_endpoint_and_admission_constraints() {
    let _guard = test_guard!();
    let directory = tempfile::Builder::new()
        .prefix("rch-retry-")
        .tempdir()
        .unwrap()
        .keep();
    let socket = directory.join("selected.sock");
    let listener = UnixListener::bind(&socket).unwrap();
    let mut config = rch_common::RchConfig::default();
    config.general.socket_path = directory.join("wrong.sock").display().to_string();
    let _config_guard = ConfigOverrideGuard::set(config);
    let writer = retry_selection_test_lease(directory.join("lease.json"));
    let previous = writer.snapshot();
    let server_writer = writer.clone();
    // A Rust admission deliberately refuses a missing caller toolchain before
    // dispatch. Bind one explicitly so this fixture reaches the retry socket.
    let toolchain = ToolchainInfo::new(
        "nightly",
        Some("2026-10-07".into()),
        "fixture toolchain identity",
    );
    let server_toolchain = toolchain.clone();
    let status = serde_json::json!({
        "daemon": {"pid": 9, "uptime_secs": 1, "version": "retry-endpoint", "socket_path": socket,
            "started_at": "2026-10-07T00:00:00Z", "workers_total": 1, "workers_healthy": 1,
            "slots_total": 16, "slots_available": 16},
        "workers": [{"id": "next-worker", "host": "unused.invalid", "user": "test",
            "status": "healthy", "circuit_state": "closed", "used_slots": 0,
            "total_slots": 16, "speed_score": 90.0, "last_error": null}],
        "active_builds": [], "recent_builds": [], "issues": [],
        "stats": {"total_builds": 0, "success_count": 0, "failure_count": 0,
            "remote_count": 0, "local_count": 0, "avg_duration_ms": 0}
    });
    let server = async move {
        for attempt in 0..2 {
            let (stream, _) = listener.accept().await.unwrap();
            let (reader, mut output) = stream.into_split();
            let mut reader = TokioBufReader::new(reader);
            let mut request = String::new();
            reader.read_line(&mut request).await.unwrap();
            let body = if attempt == 0 {
                assert_eq!(request, "GET /status\n");
                status.to_string()
            } else {
                assert_retry_pending(&server_writer, &previous);
                assert!(request.starts_with("GET /select-verified-tools/disk-budget?"));
                for parameter in [
                    "&cores=3",
                    "&disk_headroom_gib=12",
                    "&runtime=rust",
                    "&job_mode=1",
                    "&require_tool=git",
                    "&require_tool=cmake",
                    "&worker=next-worker",
                    "&preferred_workers=next-worker",
                ] {
                    assert!(
                        request.contains(parameter),
                        "missing {parameter}: {request}"
                    );
                }
                assert!(
                    request.contains(&format!("&local_wrapper_id={}", server_writer.wrapper_id()))
                );
                let encoded_toolchain =
                    urlencoding_encode(&serde_json::to_string(&server_toolchain).unwrap());
                assert!(request.contains(&format!("&toolchain={encoded_toolchain}")));
                assert!(!request.contains("&wait=1"));
                serde_json::to_string(&SelectionResponse {
                    reason: SelectionReason::SelectionError("job_cancelled_before_start".into()),
                    ..retry_unassigned_response()
                })
                .unwrap()
            };
            output
                .write_all(format!("HTTP/1.0 200 OK\r\n\r\n{body}").as_bytes())
                .await
                .unwrap();
            output.shutdown().await.unwrap();
        }
    };
    let client = async {
        try_retry_on_bigger_worker(
            socket.to_str().unwrap(),
            "job-project",
            3,
            12,
            "git status",
            Some(&toolchain),
            RequiredRuntime::Rust,
            CommandPriority::Normal,
            &[WorkerId::new("previous-worker")],
            &[WorkerId::new("next-worker")],
            true,
            &["git".into(), "cmake".into()],
            &writer,
            true,
            &HookReporter::new(OutputVisibility::None),
        )
        .await
    };
    let (response, ()) = timeout(Duration::from_secs(3), async {
        tokio::join!(client, server)
    })
    .await
    .unwrap();
    let response = response.unwrap().unwrap();
    assert!(selection_cancelled_before_start(&response.0));
    assert_eq!(response.1, WorkerId::new("next-worker"));
    assert_eq!(read_retry_lease(&writer).phase, "selection_pending");
}

#[tokio::test]
async fn queued_selection_lost_or_malformed_response_never_reaches_recovery() {
    let _guard = test_guard!();
    for wire_response in [
        "", // The daemon consumed the request but its result/receipt was lost.
        "HTTP/1.0 200 OK\r\n\r\nnot-json",
        "HTTP/1.0 200 OK\r\n\r\n{}",
        "HTTP/1.0 503 Unavailable\r\n\r\n{}",
        "HTTP/1.0 200 OK\r\n", // Truncated HTTP headers.
    ] {
        let retained = tempfile::tempdir().unwrap().keep();
        let socket = retained.join("daemon.sock");
        let listener = UnixListener::bind(&socket).unwrap();
        let resumes_lost_reply = wire_response.is_empty();
        let server = async move {
            let mut requests = Vec::new();
            // A lost original reply now permits exactly one identity-preserving
            // resume. Model an older daemon rejecting that endpoint promptly;
            // all complete invalid replies still allow no resume at all.
            for reply in std::iter::once(wire_response)
                .chain(resumes_lost_reply.then_some("HTTP/1.0 404 Not Found\r\n\r\n{}"))
            {
                let (stream, _) = listener.accept().await.unwrap();
                let (reader, mut writer) = stream.into_split();
                let mut reader = TokioBufReader::new(reader);
                let mut request = String::new();
                reader.read_line(&mut request).await.unwrap();
                writer.write_all(reply.as_bytes()).await.unwrap();
                writer.shutdown().await.unwrap();
                requests.push(request);
            }
            requests
        };
        let lease = queued_selection_test_lease(retained.join("lease.json"));
        let wrapper = lease.wrapper_id();
        let client = async {
            query_daemon(
                socket.to_str().unwrap(),
                "queued",
                2,
                0,
                "cargo build",
                None,
                RequiredRuntime::None,
                CommandPriority::Normal,
                0,
                Some(std::process::id()),
                Some(&wrapper),
                true,
                &[],
                false,
                &[],
            )
            .await
        };
        let (result, requests) = timeout(Duration::from_secs(2), async {
            tokio::join!(client, server)
        })
        .await
        .unwrap();
        let error = result.unwrap_err();
        assert_eq!(requests.len(), if resumes_lost_reply { 2 } else { 1 });
        let request = &requests[0];
        assert!(request.contains("&wait=1"));
        assert!(request.contains(&format!("local_wrapper_id={wrapper}")));
        if resumes_lost_reply {
            let query = request.strip_prefix("GET /select-worker?").unwrap();
            assert_eq!(
                requests[1],
                format!("GET /select-worker/resume-queued?{query}"),
                "resume changes only the endpoint, never identity or constraints"
            );
        }
        assert!(
            error
                .downcast_ref::<daemon_ipc::SelectionOutcomeUnconfirmed>()
                .is_some()
        );

        // This is the gate used by both initial selection and the sole recovery
        // query. Neither a transport error nor an outer context may bypass it.
        let error = selection_error_for_recovery(error.context("outer caller context"), &lease)
            .unwrap_err();
        assert!(
            error
                .downcast_ref::<daemon_ipc::SelectionOutcomeUnconfirmed>()
                .is_some()
        );
        let persisted: DurableJobLease =
            serde_json::from_slice(&std::fs::read(&lease.path).unwrap()).unwrap();
        assert_eq!(persisted.phase, "selection_unconfirmed");
        assert_eq!(persisted.identity.local_wrapper_id, wrapper);
        assert!(!persisted.terminal_acknowledged);
        assert!(persisted.exit_code.is_none());
        assert!(persisted.identity.remote_build_id.is_none());
    }
}

#[tokio::test]
async fn queued_selection_preconnect_failure_preserves_recovery() {
    let _guard = test_guard!();
    let tmp = tempfile::TempDir::new().unwrap();
    let absent = tmp.path().join("missing.sock");
    let refused = tmp.path().join("refused.sock");
    drop(UnixListener::bind(&refused).unwrap());
    for socket in [absent, refused] {
        let lease = queued_selection_test_lease(tmp.path().join("lease.json"));
        let wrapper = lease.wrapper_id();
        let error = query_daemon(
            socket.to_str().unwrap(),
            "queued",
            2,
            0,
            "cargo build",
            None,
            RequiredRuntime::None,
            CommandPriority::Normal,
            0,
            Some(std::process::id()),
            Some(&wrapper),
            true,
            &[],
            false,
            &[],
        )
        .await
        .unwrap_err();
        assert!(
            error
                .downcast_ref::<daemon_ipc::SelectionOutcomeUnconfirmed>()
                .is_none()
        );
        let _ = selection_error_for_recovery(error, &lease).unwrap();
        assert_eq!(lease.snapshot().phase, "admission");
    }
}

#[tokio::test]
async fn test_daemon_query_protocol() {
    // Create a mock daemon socket
    let socket_path = format!("/tmp/rch_test_daemon_{}.sock", std::process::id());

    // Clean up any existing socket
    let _ = std::fs::remove_file(&socket_path);

    let listener = UnixListener::bind(&socket_path).expect("Failed to create test socket");

    // Spawn mock daemon handler
    let socket_path_clone = socket_path.clone();
    let daemon_handle = tokio::spawn(async move {
        let (stream, _) = listener
            .accept()
            .await
            .expect("Failed to accept connection");
        let (reader, mut writer) = stream.into_split();
        let mut buf_reader = TokioBufReader::new(reader);

        // Read the request line
        let mut request_line = String::new();
        buf_reader
            .read_line(&mut request_line)
            .await
            .expect("Failed to read request");

        // Verify request format
        assert!(request_line.starts_with("GET /select-worker"));
        assert!(request_line.contains("project="));
        assert!(request_line.contains("cores="));
        assert!(request_line.contains("command=cargo%20build"));
        assert!(request_line.contains("priority=normal"));

        // Send mock response
        let response = SelectionResponse {
            worker: Some(SelectedWorker {
                id: rch_common::WorkerId::new("mock-worker"),
                host: "mock.host.local".to_string(),
                user: "mockuser".to_string(),
                identity_file: "~/.ssh/mock_key".to_string(),
                slots_available: 16,
                speed_score: 95.0,
                declared_os: None,
            }),
            reason: SelectionReason::Success,
            build_id: None,
            diagnostics: None,
        };
        let body = serde_json::to_string(&response).unwrap();
        let http_response = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
            body.len(),
            body
        );
        writer
            .write_all(http_response.as_bytes())
            .await
            .expect("Failed to write response");
        writer.flush().await.expect("Failed to flush response");
    });

    // Give daemon time to start listening
    tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;

    // Query the mock daemon
    let result = query_daemon(
        &socket_path,
        "test-project",
        4,
        0,
        "cargo build",
        None,
        RequiredRuntime::None,
        CommandPriority::Normal,
        100,
        None,
        None,
        false,
        &[],
        false,
        &[],
    )
    .await;

    // Clean up
    daemon_handle.await.expect("Daemon task panicked");
    let _ = std::fs::remove_file(&socket_path_clone);

    // Verify result
    let response = result.expect("Query should succeed");
    let worker = response.worker.expect("Should have worker");
    assert_eq!(worker.id.as_str(), "mock-worker");
    assert_eq!(worker.host, "mock.host.local");
    assert_eq!(worker.slots_available, 16);
}

#[tokio::test]
async fn test_daemon_query_sends_preferred_workers() {
    let socket_path = format!("/tmp/rch_test_daemon_preferred_{}.sock", std::process::id());
    let _ = std::fs::remove_file(&socket_path);

    let listener = UnixListener::bind(&socket_path).expect("Failed to create test socket");

    let socket_path_clone = socket_path.clone();
    let daemon_handle = tokio::spawn(async move {
        let (stream, _) = listener
            .accept()
            .await
            .expect("Failed to accept connection");
        let (reader, mut writer) = stream.into_split();
        let mut buf_reader = TokioBufReader::new(reader);

        let mut request_line = String::new();
        buf_reader
            .read_line(&mut request_line)
            .await
            .expect("Failed to read request");

        assert!(request_line.contains("worker=ts2"));
        assert!(request_line.contains("worker=vmi1264463"));
        assert!(request_line.contains("preferred_workers=ts2%2Cvmi1264463"));

        let response = SelectionResponse {
            worker: Some(SelectedWorker {
                id: rch_common::WorkerId::new("ts2"),
                host: "mock.host.local".to_string(),
                user: "mockuser".to_string(),
                identity_file: "~/.ssh/mock_key".to_string(),
                slots_available: 16,
                speed_score: 95.0,
                declared_os: None,
            }),
            reason: SelectionReason::Success,
            build_id: None,
            diagnostics: None,
        };
        let body = serde_json::to_string(&response).unwrap();
        let http_response = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
            body.len(),
            body
        );
        writer
            .write_all(http_response.as_bytes())
            .await
            .expect("Failed to write response");
        writer.flush().await.expect("Failed to flush response");
    });

    tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;

    let preferred = vec![
        rch_common::WorkerId::new("ts2"),
        rch_common::WorkerId::new("vmi1264463"),
    ];
    let result = query_daemon(
        &socket_path,
        "test-project",
        4,
        0,
        "cargo build",
        None,
        RequiredRuntime::None,
        CommandPriority::Normal,
        100,
        None,
        None,
        false,
        &preferred,
        false,
        &[],
    )
    .await;

    daemon_handle.await.expect("Daemon task panicked");
    let _ = std::fs::remove_file(&socket_path_clone);

    let response = result.expect("Query should succeed");
    let worker = response.worker.expect("Should have worker");
    assert_eq!(worker.id.as_str(), "ts2");
}

#[tokio::test]
async fn test_daemon_query_releases_worker_outside_requested_set() {
    let socket_path = format!(
        "/tmp/rch_test_daemon_unrequested_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );
    let _ = std::fs::remove_file(&socket_path);
    let listener = UnixListener::bind(&socket_path).expect("bind mock daemon socket");
    let socket_path_clone = socket_path.clone();

    let daemon_handle = tokio::spawn(async move {
        {
            let (stream, _) = listener.accept().await.expect("accept selection request");
            let (reader, mut writer) = stream.into_split();
            let mut reader = TokioBufReader::new(reader);
            let mut request_line = String::new();
            reader
                .read_line(&mut request_line)
                .await
                .expect("read selection request");
            assert!(request_line.contains("worker=requested"));

            let response = SelectionResponse {
                worker: Some(SelectedWorker {
                    id: WorkerId::new("unrequested"),
                    host: "mock.host.local".to_string(),
                    user: "mockuser".to_string(),
                    identity_file: "~/.ssh/mock_key".to_string(),
                    slots_available: 6,
                    speed_score: 90.0,
                    declared_os: None,
                }),
                reason: SelectionReason::Success,
                build_id: Some(42),
                diagnostics: None,
            };
            let body = serde_json::to_string(&response).unwrap();
            let http_response = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
                body.len(),
                body
            );
            writer
                .write_all(http_response.as_bytes())
                .await
                .expect("write selection response");
            writer.shutdown().await.expect("close selection response");
        }

        let (stream, _) =
            tokio::time::timeout(tokio::time::Duration::from_secs(2), listener.accept())
                .await
                .expect("client did not release unrequested worker")
                .expect("accept release request");
        let (reader, mut writer) = stream.into_split();
        let mut reader = TokioBufReader::new(reader);
        let mut release_line = String::new();
        reader
            .read_line(&mut release_line)
            .await
            .expect("read release request");
        assert!(release_line.starts_with("POST /release-worker?"));
        assert!(release_line.contains("worker=unrequested"));
        assert!(release_line.contains("slots=2"));
        assert!(release_line.contains("build_id=42"));
        assert!(release_line.contains("exit_code=1"));
        writer
            .write_all(b"HTTP/1.0 200 OK\r\n\r\n{}\n")
            .await
            .expect("ack release");
        writer.flush().await.expect("flush release ack");
    });

    let response = query_daemon(
        &socket_path,
        "test-project",
        2,
        0,
        "cargo build",
        None,
        RequiredRuntime::None,
        CommandPriority::Normal,
        0,
        Some(1234),
        None,
        false,
        &[WorkerId::new("requested")],
        false,
        &[],
    )
    .await
    .expect("query should return a structured refusal");

    daemon_handle.await.expect("mock daemon task panicked");
    let _ = std::fs::remove_file(&socket_path_clone);
    assert!(response.worker.is_none());
    assert_eq!(response.reason, SelectionReason::NoMatchingWorkers);
    assert_eq!(response.build_id, None);
}

#[tokio::test]
async fn test_daemon_query_surfaces_unacknowledged_unrequested_worker_release() {
    let socket_path = format!(
        "/tmp/rch_test_daemon_unrequested_release_failure_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );
    let _ = std::fs::remove_file(&socket_path);
    let listener = UnixListener::bind(&socket_path).expect("bind mock daemon socket");
    let socket_path_clone = socket_path.clone();

    let daemon_handle = tokio::spawn(async move {
        {
            let (stream, _) = listener.accept().await.expect("accept selection request");
            let (reader, mut writer) = stream.into_split();
            let mut reader = TokioBufReader::new(reader);
            let mut request_line = String::new();
            reader
                .read_line(&mut request_line)
                .await
                .expect("read selection request");

            let response = SelectionResponse {
                worker: Some(SelectedWorker {
                    id: WorkerId::new("unrequested"),
                    host: "mock.host.local".to_string(),
                    user: "mockuser".to_string(),
                    identity_file: "~/.ssh/mock_key".to_string(),
                    slots_available: 6,
                    speed_score: 90.0,
                    declared_os: None,
                }),
                reason: SelectionReason::Success,
                build_id: Some(43),
                diagnostics: None,
            };
            let body = serde_json::to_string(&response).unwrap();
            let http_response = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
                body.len(),
                body
            );
            writer
                .write_all(http_response.as_bytes())
                .await
                .expect("write selection response");
            writer.shutdown().await.expect("close selection response");
        }

        let (stream, _) =
            tokio::time::timeout(tokio::time::Duration::from_secs(2), listener.accept())
                .await
                .expect("client did not attempt release")
                .expect("accept release request");
        let (reader, mut writer) = stream.into_split();
        let mut reader = TokioBufReader::new(reader);
        let mut release_line = String::new();
        reader
            .read_line(&mut release_line)
            .await
            .expect("read release request");
        assert!(release_line.contains("worker=unrequested"));
        assert!(release_line.contains("build_id=43"));
        writer
            .write_all(b"HTTP/1.0 500 Internal Server Error\r\n\r\n{}\n")
            .await
            .expect("reject release");
        writer.flush().await.expect("flush release rejection");
    });

    let error = query_daemon(
        &socket_path,
        "test-project",
        2,
        0,
        "cargo build",
        None,
        RequiredRuntime::None,
        CommandPriority::Normal,
        0,
        Some(1234),
        None,
        false,
        &[WorkerId::new("requested")],
        false,
        &[],
    )
    .await
    .expect_err("an unacknowledged release must not look like a safe ordinary refusal (9ec9b32f)");

    daemon_handle.await.expect("mock daemon task panicked");
    let _ = std::fs::remove_file(&socket_path_clone);
    // The daemon may still hold the reservation, so the hook must take its
    // durable stop path: neither retry selection nor build locally.
    assert!(
        error
            .downcast_ref::<daemon_ipc::SelectionOutcomeUnconfirmed>()
            .is_some()
    );
    let message = format!("{error:#}");
    assert!(
        message.contains("release was not acknowledged"),
        "{message}"
    );
    assert!(message.contains("build 43"), "{message}");
}

#[tokio::test]
async fn test_daemon_query_wait_parameters() {
    let socket_path = format!("/tmp/rch_test_wait_{}.sock", std::process::id());
    let _ = std::fs::remove_file(&socket_path);

    let listener = UnixListener::bind(&socket_path).expect("Failed to create test socket");
    let expected_wait_timeout_secs = daemon_response_timeout_for(true, None, None)
        .as_secs()
        .saturating_sub(1)
        .max(1);

    let socket_path_clone = socket_path.clone();
    let daemon_handle = tokio::spawn(async move {
        let (stream, _) = listener
            .accept()
            .await
            .expect("Failed to accept connection");
        let (reader, mut writer) = stream.into_split();
        let mut buf_reader = TokioBufReader::new(reader);

        let mut request_line = String::new();
        buf_reader
            .read_line(&mut request_line)
            .await
            .expect("Failed to read request");

        assert!(request_line.starts_with("GET /select-worker"));
        assert!(request_line.contains("wait=1"));
        assert!(request_line.contains(&format!("wait_timeout_secs={expected_wait_timeout_secs}")));

        let response = SelectionResponse {
            worker: Some(SelectedWorker {
                id: rch_common::WorkerId::new("mock-worker"),
                host: "mock.host.local".to_string(),
                user: "mockuser".to_string(),
                identity_file: "~/.ssh/mock_key".to_string(),
                slots_available: 16,
                speed_score: 95.0,
                declared_os: None,
            }),
            reason: SelectionReason::Success,
            build_id: None,
            diagnostics: None,
        };
        let body = serde_json::to_string(&response).unwrap();
        let http_response = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
            body.len(),
            body
        );
        writer
            .write_all(http_response.as_bytes())
            .await
            .expect("Failed to write response");
        writer.flush().await.expect("Failed to flush response");
    });

    tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;

    let result = query_daemon(
        &socket_path,
        "test-project",
        4,
        0,
        "cargo build",
        None,
        RequiredRuntime::None,
        CommandPriority::Normal,
        100,
        None,
        None,
        true,
        &[],
        false,
        &[],
    )
    .await;

    daemon_handle.await.expect("Daemon task panicked");
    let _ = std::fs::remove_file(&socket_path_clone);

    let response = result.expect("Query should succeed");
    let worker = response.worker.expect("Should have worker");
    assert_eq!(worker.id.as_str(), "mock-worker");
}

#[tokio::test]
async fn test_daemon_query_url_encoding() {
    // Verify special characters in project name are encoded
    let socket_path = format!("/tmp/rch_test_url_{}.sock", std::process::id());
    let _ = std::fs::remove_file(&socket_path);

    let listener = UnixListener::bind(&socket_path).expect("Failed to create test socket");

    let socket_path_clone = socket_path.clone();
    let daemon_handle = tokio::spawn(async move {
        let (stream, _) = listener
            .accept()
            .await
            .expect("Failed to accept connection");
        let (reader, mut writer) = stream.into_split();
        let mut buf_reader = TokioBufReader::new(reader);

        // Read the request line
        let mut request_line = String::new();
        buf_reader.read_line(&mut request_line).await.expect("Read");

        // The project name "my project/test" should be URL encoded
        assert!(request_line.contains("my%20project%2Ftest"));

        // Send minimal response
        let response = SelectionResponse {
            worker: Some(SelectedWorker {
                id: rch_common::WorkerId::new("w1"),
                host: "h".to_string(),
                user: "u".to_string(),
                identity_file: "i".to_string(),
                slots_available: 1,
                speed_score: 1.0,
                declared_os: None,
            }),
            reason: SelectionReason::Success,
            build_id: None,
            diagnostics: None,
        };
        let body = serde_json::to_string(&response).unwrap();
        let http = format!("HTTP/1.1 200 OK\r\n\r\n{}", body);
        writer.write_all(http.as_bytes()).await.expect("Write");
    });

    tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;

    let result = query_daemon(
        &socket_path,
        "my project/test",
        2,
        0,
        "cargo build --release",
        None,
        RequiredRuntime::None,
        CommandPriority::Normal,
        150, // 150µs classification time
        None,
        None,
        false,
        &[],
        false,
        &[],
    )
    .await;
    daemon_handle.await.expect("Daemon task");
    let _ = std::fs::remove_file(&socket_path_clone);

    assert!(result.is_ok());
}

// =========================================================================
// Fail-open behavior tests
// =========================================================================

#[tokio::test]
async fn test_fail_open_on_invalid_json() {
    let _lock = test_lock().lock().await;
    // Disable mock mode to test real fail-open behavior
    mock::set_mock_enabled_override(Some(false));

    let mut config = rch_common::RchConfig::default();
    config.general.socket_path = "/tmp/rch-test-no-daemon.sock".to_string();
    let _ = std::fs::remove_file(&config.general.socket_path);
    let _config_guard = ConfigOverrideGuard::set(config);

    // If hook input is invalid JSON, should allow (fail-open)
    // This tests the run_hook behavior implicitly through process_hook
    // We can't easily test run_hook directly as it reads stdin

    // But we can verify that process_hook with valid input returns Allow
    // when no daemon is available (which is the fail-open case)
    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build".to_string(),
            description: None,
        },
        session_id: None,
    };

    // With no daemon running, should fail-open to allow
    let output = process_hook(input).await;
    mock::clear_mock_overrides();
    assert!(output.is_allow());
}

#[tokio::test]
async fn test_fail_open_on_config_error() {
    let _lock = test_lock().lock().await;
    // Disable mock mode to test real fail-open behavior
    mock::set_mock_enabled_override(Some(false));

    // If config is missing or invalid, should allow
    // This is tested implicitly by process_hook when config can't load
    // The current implementation falls back to allow
    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build --release".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    mock::clear_mock_overrides();
    // Should allow because daemon isn't running (fail-open)
    assert!(output.is_allow());
}

#[tokio::test]
#[serial(mock_global)]
async fn test_process_hook_remote_success_mocked() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_hook_success_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );
    mock::clear_global_invocations();

    let response = SelectionResponse {
        worker: Some(SelectedWorker {
            id: rch_common::WorkerId::new("mock-worker"),
            host: "mock.host.local".to_string(),
            user: "mockuser".to_string(),
            identity_file: "~/.ssh/mock_key".to_string(),
            slots_available: 8,
            speed_score: 90.0,
            declared_os: None,
        }),
        reason: SelectionReason::Success,
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output: HookOutput = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Hook should return AllowWithModifiedCommand delegating to `rch exec`
    // The actual remote compilation happens when `rch exec` runs, not in the hook
    assert!(output.is_allow());
    let cmd = delegated_command(&output);
    assert!(
        cmd.starts_with("rch exec -- "),
        "Modified command should delegate to rch exec: {}",
        cmd
    );
    assert!(
        cmd.contains("cargo build"),
        "Modified command should contain original command: {}",
        cmd
    );

    // No rsync/SSH should be invoked during the hook - that happens in run_exec
    let rsync_logs = mock::global_rsync_invocations_snapshot();
    let ssh_logs = mock::global_ssh_invocations_snapshot();
    assert!(
        rsync_logs.is_empty(),
        "Hook should not invoke rsync directly"
    );
    assert!(ssh_logs.is_empty(), "Hook should not invoke SSH directly");
}

#[tokio::test]
#[serial(mock_global)]
async fn test_force_local_allows_even_when_remote_available() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_hook_force_local_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );
    mock::clear_global_invocations();

    let mut config = rch_common::RchConfig::default();
    config.general.socket_path = socket_path.to_string();
    config.general.force_local = true;
    crate::config::set_test_config_override(Some(config));

    let response = SelectionResponse {
        worker: Some(SelectedWorker {
            id: rch_common::WorkerId::new("mock-worker"),
            host: "mock.host.local".to_string(),
            user: "mockuser".to_string(),
            identity_file: "~/.ssh/mock_key".to_string(),
            slots_available: 8,
            speed_score: 90.0,
            declared_os: None,
        }),
        reason: SelectionReason::Success,
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    assert!(output.is_allow());

    let rsync_logs = mock::global_rsync_invocations_snapshot();
    let ssh_logs = mock::global_ssh_invocations_snapshot();
    assert!(rsync_logs.is_empty());
    assert!(ssh_logs.is_empty());
}

#[tokio::test]
#[serial(mock_global)]
async fn test_force_remote_bypasses_confidence_threshold() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_hook_force_remote_threshold_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );
    mock::clear_global_invocations();

    let classification = classify_command("cargo build");
    assert!(classification.is_compilation);
    let high_threshold = (classification.confidence + 0.01).min(1.0);

    let mut config = rch_common::RchConfig::default();
    config.general.socket_path = socket_path.to_string();
    config.general.force_remote = true;
    config.compilation.confidence_threshold = high_threshold;
    crate::config::set_test_config_override(Some(config));

    let response = SelectionResponse {
        worker: Some(SelectedWorker {
            id: rch_common::WorkerId::new("mock-worker"),
            host: "mock.host.local".to_string(),
            user: "mockuser".to_string(),
            identity_file: "~/.ssh/mock_key".to_string(),
            slots_available: 8,
            speed_score: 90.0,
            declared_os: None,
        }),
        reason: SelectionReason::Success,
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // force_remote should result in transparent interception (AllowWithModifiedCommand)
    // with delegation to `rch exec`
    assert!(output.is_allow());
    let cmd = delegated_command(&output);
    assert!(
        cmd.starts_with("rch exec -- "),
        "Should delegate to rch exec: {}",
        cmd
    );

    // No rsync/SSH should be invoked during the hook - that happens in run_exec
    let rsync_logs = mock::global_rsync_invocations_snapshot();
    let ssh_logs = mock::global_ssh_invocations_snapshot();
    assert!(
        rsync_logs.is_empty(),
        "Hook should not invoke rsync directly"
    );
    assert!(ssh_logs.is_empty(), "Hook should not invoke SSH directly");
}

#[tokio::test]
#[serial(mock_global)]
async fn test_process_hook_delegates_to_rch_exec() {
    // Test that process_hook always delegates to `rch exec` without doing
    // any remote operations itself. Sync failures (if any) would happen
    // in run_exec, not in process_hook.
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_hook_delegate_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    // Even with sync_failure mock config, the hook should succeed
    // because it doesn't do sync - it just delegates to rch exec
    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::sync_failure(),
    );
    mock::clear_global_invocations();

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Hook should return AllowWithModifiedCommand delegating to rch exec
    assert!(output.is_allow());
    let cmd = delegated_command(&output);
    assert!(
        cmd.starts_with("rch exec -- "),
        "Should delegate to rch exec: {}",
        cmd
    );

    // No rsync/SSH should be invoked during the hook
    let rsync_logs = mock::global_rsync_invocations_snapshot();
    let ssh_logs = mock::global_ssh_invocations_snapshot();
    assert!(
        rsync_logs.is_empty(),
        "Hook should not invoke rsync directly"
    );
    assert!(ssh_logs.is_empty(), "Hook should not invoke SSH directly");
}

#[tokio::test]
#[serial(mock_global)]
async fn test_process_hook_delegates_env_prefixed_cargo_command() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_hook_delegate_env_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::sync_failure(),
    );
    mock::clear_global_invocations();

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "env RUSTFLAGS=\"-C linker=cc\" cargo build --bin frankenctl".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    let cmd = delegated_command(&output);
    assert!(
        cmd.starts_with("rch exec -- env "),
        "env wrapper must remain an argv prefix in delegated command: {cmd}"
    );
    let tokens = shell_words::split(
        cmd.strip_prefix("rch exec -- ")
            .expect("delegated command prefix"),
    )
    .expect("delegated command should parse as shell words");
    assert_eq!(
        tokens,
        vec![
            "env".to_string(),
            "RUSTFLAGS=-C linker=cc".to_string(),
            "cargo".to_string(),
            "build".to_string(),
            "--bin".to_string(),
            "frankenctl".to_string(),
        ]
    );

    assert!(mock::global_rsync_invocations_snapshot().is_empty());
    assert!(mock::global_ssh_invocations_snapshot().is_empty());
}

#[tokio::test]
#[serial(mock_global)]
async fn test_process_hook_remote_nonzero_exit_uses_transparent_interception() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_hook_exit_nonzero_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig {
            default_exit_code: 2,
            ..MockConfig::default()
        },
        MockRsyncConfig::success(),
    );
    mock::clear_global_invocations();

    let response = SelectionResponse {
        worker: Some(SelectedWorker {
            id: rch_common::WorkerId::new("mock-worker"),
            host: "mock.host.local".to_string(),
            user: "mockuser".to_string(),
            identity_file: "~/.ssh/mock_key".to_string(),
            slots_available: 8,
            speed_score: 90.0,
            declared_os: None,
        }),
        reason: SelectionReason::Success,
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Remote failure should still use transparent interception (AllowWithModifiedCommand)
    // with "exit <code>" to preserve the exit code for the agent
    assert!(output.is_allow());
    assert!(
        matches!(output, HookOutput::AllowWithModifiedCommand(_)),
        "Expected AllowWithModifiedCommand for remote execution with non-zero exit"
    );
}

#[test]
fn test_transfer_config_defaults() {
    let _guard = test_guard!();
    // Verify TransferConfig has sensible defaults
    let config = TransferConfig::default();
    assert!(!config.exclude_patterns.is_empty());
    assert!(config.exclude_patterns.iter().any(|p| p.contains("target")));
}

#[test]
fn test_worker_config_from_selected_worker() {
    let _guard = test_guard!();
    // Test the conversion preserves all fields correctly
    let worker = SelectedWorker {
        id: rch_common::WorkerId::new("worker-alpha"),
        host: "alpha.example.com".to_string(),
        user: "deploy".to_string(),
        identity_file: "/keys/deploy.pem".to_string(),
        slots_available: 32,
        speed_score: 88.8,
        declared_os: None,
    };

    let config = selected_worker_to_config(&worker);

    assert_eq!(config.id.as_str(), "worker-alpha");
    assert_eq!(config.host, "alpha.example.com");
    assert_eq!(config.user, "deploy");
    assert_eq!(config.identity_file, "/keys/deploy.pem");
    assert_eq!(config.total_slots, 32);
    assert_eq!(config.priority, 100); // Default priority
    assert!(config.tags.is_empty()); // Default empty tags
}

// =========================================================================
// Local fallback scenario tests (remote_compilation_helper-od4)
// =========================================================================

#[tokio::test]
async fn test_fallback_no_workers_configured() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_no_workers_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );

    // Daemon returns no workers configured
    let response = SelectionResponse {
        worker: None,
        reason: SelectionReason::NoWorkersConfigured,
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;
    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Should fall back to local execution
    assert!(output.is_allow());
}

#[tokio::test]
async fn test_fallback_all_workers_unreachable() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_unreachable_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );

    // Daemon returns all workers unreachable
    let response = SelectionResponse {
        worker: None,
        reason: SelectionReason::AllWorkersUnreachable,
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;
    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build --release".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Should fall back to local execution
    assert!(output.is_allow());
}

#[tokio::test]
async fn test_fallback_all_workers_busy() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_busy_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );

    // Daemon returns all workers busy
    let response = SelectionResponse {
        worker: None,
        reason: SelectionReason::AllWorkersBusy,
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;
    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo test".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Should fall back to local execution
    assert!(output.is_allow());
}

#[tokio::test]
async fn test_fallback_all_circuits_open() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_circuits_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );

    // Daemon returns all circuits open (circuit breaker tripped)
    let response = SelectionResponse {
        worker: None,
        reason: SelectionReason::AllCircuitsOpen,
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;
    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo check".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Should fall back to local execution
    assert!(output.is_allow());
}

#[tokio::test]
async fn test_fallback_selection_error() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_sel_err_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );

    // Daemon returns a selection error
    let response = SelectionResponse {
        worker: None,
        reason: SelectionReason::SelectionError("Internal error".to_string()),
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;
    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Should fall back to local execution
    assert!(output.is_allow());
}

#[tokio::test]
async fn test_fallback_daemon_error_response() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_daemon_err_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );

    // Spawn a daemon that returns HTTP 500 error
    let _ = std::fs::remove_file(&socket_path);
    let listener = UnixListener::bind(&socket_path).expect("bind");

    tokio::spawn(async move {
        let (stream, _) = listener.accept().await.expect("accept");
        let (reader, mut writer) = stream.into_split();
        let mut buf_reader = TokioBufReader::new(reader);

        let mut request_line = String::new();
        buf_reader.read_line(&mut request_line).await.expect("read");

        // Return HTTP 500 error
        let http =
            "HTTP/1.1 500 Internal Server Error\r\n\r\n Расположение: {\"error\": \"internal\"}";
        writer.write_all(http.as_bytes()).await.expect("write");
    });

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Should fall back to local execution (fail-open)
    assert!(output.is_allow());
}

#[tokio::test]
async fn test_fallback_daemon_malformed_json() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_malformed_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );

    // Spawn a daemon that returns malformed JSON
    let _ = std::fs::remove_file(&socket_path);
    let listener = UnixListener::bind(&socket_path).expect("bind");

    tokio::spawn(async move {
        let (stream, _) = listener.accept().await.expect("accept");
        let (reader, mut writer) = stream.into_split();
        let mut buf_reader = TokioBufReader::new(reader);

        let mut request_line = String::new();
        buf_reader.read_line(&mut request_line).await.expect("read");

        // Return malformed JSON
        let http = "HTTP/1.1 200 OK\r\n\r\n{invalid json}";
        writer.write_all(http.as_bytes()).await.expect("write");
    });

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Should fall back to local execution (fail-open on parse error)
    assert!(output.is_allow());
}

#[tokio::test]
async fn test_fallback_daemon_connection_reset() {
    let _lock = test_lock().lock().await;
    // ubs:ignore — unique test socket filename, not an authentication token.
    let socket_path = format!(
        "/tmp/rch_test_reset_{}_{}.sock",
        std::process::id(), // ubs:ignore — test filename collision avoidance only.
        std::time::SystemTime::now() // ubs:ignore — test filename collision avoidance only.
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );

    // Spawn a daemon that immediately closes connection
    let _ = std::fs::remove_file(&socket_path);
    let listener = UnixListener::bind(&socket_path).expect("bind");

    tokio::spawn(async move {
        let (stream, _) = listener.accept().await.expect("accept");
        // Immediately drop the stream to simulate connection reset
        drop(stream);
    });

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Should fall back to local execution (fail-open on connection error)
    assert!(output.is_allow());
}

// =========================================================================
// Exit code handling tests (bead remote_compilation_helper-zerp)
// =========================================================================

#[test]
fn test_is_signal_killed() {
    let _guard = test_guard!();
    // Normal exit codes should not be signal-killed
    assert!(is_signal_killed(0).is_none());
    assert!(is_signal_killed(1).is_none());
    assert!(is_signal_killed(101).is_none());
    assert!(is_signal_killed(128).is_none()); // 128 is exactly at boundary

    // Signal kills (128 + signal)
    assert_eq!(is_signal_killed(129), Some(1)); // SIGHUP
    assert_eq!(is_signal_killed(130), Some(2)); // SIGINT
    assert_eq!(is_signal_killed(137), Some(9)); // SIGKILL
    assert_eq!(is_signal_killed(139), Some(11)); // SIGSEGV
    assert_eq!(is_signal_killed(143), Some(15)); // SIGTERM
}

#[test]
fn test_signal_name() {
    let _guard = test_guard!();
    assert_eq!(signal_name(1), "SIGHUP");
    assert_eq!(signal_name(2), "SIGINT");
    // bd-68hon: 4/7 used to log as UNKNOWN, hiding CPU-capability
    // faults behind "killed by UNKNOWN (exit 132)".
    assert_eq!(signal_name(4), "SIGILL");
    assert_eq!(signal_name(7), "SIGBUS");
    assert_eq!(signal_name(9), "SIGKILL");
    assert_eq!(signal_name(11), "SIGSEGV");
    assert_eq!(signal_name(15), "SIGTERM");
    assert_eq!(signal_name(99), "UNKNOWN");
}

#[test]
fn test_sigill_classifies_as_cpu_capability_fault_not_oom() {
    let _guard = test_guard!();
    // bd-68hon: exit 132 (128+4) is a WORKER capability fault — the
    // quarantine-and-retry-anywhere arm — never the OOM
    // retry-on-bigger heuristic. SIGKILL/SIGSEGV stay in the generic
    // signal arm.
    use super::remote_result::is_cpu_capability_signal;
    assert_eq!(is_signal_killed(132), Some(4));
    assert!(is_cpu_capability_signal(4));
    assert!(
        !is_cpu_capability_signal(9),
        "OOM is not a capability fault"
    );
    assert!(!is_cpu_capability_signal(11));
    assert!(
        !is_cpu_capability_signal(7),
        "SIGBUS is named but not auto-quarantined"
    );
}

#[test]
fn test_exit_code_constants() {
    let _guard = test_guard!();
    // Verify exit code constants match cargo's documented behavior
    assert_eq!(EXIT_SUCCESS, 0);
    assert_eq!(EXIT_BUILD_ERROR, 1);
    assert_eq!(EXIT_TEST_FAILURES, 101);
    assert_eq!(EXIT_SIGNAL_BASE, 128);
}

#[test]
fn test_remote_pipeline_failure_policy_ssh_timeout_fails_closed() {
    let _guard = test_guard!();
    let error = anyhow::anyhow!("SSH command timed out after 1800s");

    assert_eq!(
        classify_remote_pipeline_failure(&error),
        RemotePipelineFailurePolicy::FailClosedNoLocalFallback
    );
}

#[test]
fn test_remote_pipeline_failure_policy_wrapped_ssh_timeout_fails_closed() {
    let _guard = test_guard!();
    let error =
        anyhow::anyhow!("SSH command timed out after 1800s").context("remote execution failed");

    assert_eq!(
        classify_remote_pipeline_failure(&error),
        RemotePipelineFailurePolicy::FailClosedNoLocalFallback
    );
}

#[test]
fn test_remote_pipeline_failure_policy_non_timeout_allows_existing_fallback() {
    let _guard = test_guard!();
    let error = anyhow::anyhow!("rsync failed before remote execution");

    assert_eq!(
        classify_remote_pipeline_failure(&error),
        RemotePipelineFailurePolicy::AllowLocalFallback
    );
}

#[test]
fn test_unacknowledged_release_is_a_typed_no_replay_error() {
    let _guard = test_guard!();
    let error = release_unconfirmed_error(&WorkerId::new("worker-a"), 42);

    assert!(is_remote_execution_unconfirmed(&error));
    assert_eq!(
        classify_remote_pipeline_failure(&error),
        RemotePipelineFailurePolicy::FailClosedNoLocalFallback
    );
    let message = format!("{error:#}");
    assert!(message.contains("build 42"));
    assert!(message.contains("worker-a"));
    assert!(message.contains("must not be replayed"));
}

#[test]
fn test_unconfirmed_remote_execution_retains_ownership_and_never_falls_back() {
    let _guard = test_guard!();
    for error in [
        anyhow::Error::new(crate::transfer::RemoteExecutionUnconfirmed),
        anyhow::anyhow!("source authority holder exited")
            .context(crate::transfer::RemoteExecutionUnconfirmed)
            .context("remote pipeline failed"),
        anyhow::anyhow!("missing durable completion receipt")
            .context(crate::transfer::RemoteExecutionUnconfirmed),
        anyhow::Error::new(TransferError::TransferSkipped {
            reason: "transfer budget".to_owned(),
        })
        .context(crate::transfer::RemoteExecutionUnconfirmed),
    ] {
        assert!(is_remote_execution_unconfirmed(&error));
        assert_eq!(
            classify_remote_pipeline_failure(&error),
            RemotePipelineFailurePolicy::FailClosedNoLocalFallback
        );
        let summary = remote_pipeline_failure_summary(&WorkerId::new("worker-a"), &error);
        assert!(summary.contains("ownership retained for recovery"));
        assert!(!summary.contains("SSH command timed out"));
    }
    let setup = anyhow::Error::new(crate::transfer::RemoteProcessSetupUnavailable)
        .context("verified pre-workload refusal");
    assert!(!is_remote_execution_unconfirmed(&setup));
    assert_eq!(
        classify_remote_pipeline_failure(&setup),
        RemotePipelineFailurePolicy::AllowLocalFallback,
        "verified setup refusal can release ownership and run locally"
    );
}

#[test]
fn test_source_sync_stall_is_not_misclassified_as_ssh_timeout() {
    // Issue #59: the stall must route into the worker-failover retry arm, so
    // it must never match the E104 fail-closed classifier, and the typed
    // error must stay downcastable through added context.
    let _guard = test_guard!();
    let error: anyhow::Error = crate::transfer::SourceSyncStalled {
        worker_id: "hz4".to_string(),
        phase: "source_sync",
        silence: std::time::Duration::from_secs(120),
        detail: "sync_to_remote_streaming: no rsync output for 120s (wall-clock cap 3600s)"
            .to_string(),
    }
    .into();
    let error = error.context("remote execution failed");

    assert_eq!(
        classify_remote_pipeline_failure(&error),
        RemotePipelineFailurePolicy::AllowLocalFallback,
        "a sync stall fails over to another worker; it must not fail closed"
    );
    let stall = crate::transfer::find_source_sync_stall(&error)
        .expect("typed stall must survive context wrapping for the failover downcast");
    assert_eq!(stall.worker_id, "hz4");
    assert_eq!(stall.phase, "source_sync");
    assert_eq!(stall.silence.as_secs(), 120);
}

#[test]
fn test_sync_progress_line_marks_heartbeat_progress() {
    // Issue #59: every rsync output segment observed during source sync must
    // bump the build-heartbeat forward-progress counter (with or without the
    // rich progress UI attached), so the daemon sees a live `sync_up` phase.
    let _guard = test_guard!();
    // Fully qualified: this test module imports tokio's Mutex, but the
    // heartbeat snapshot lives behind std::sync::Mutex.
    let state = std::sync::Arc::new(std::sync::Mutex::new(
        super::progress_reporting::BuildHeartbeatSnapshot::new(),
    ));
    let before = state.lock().unwrap().progress_counter();

    super::transfer_orchestration::sync_progress_line(None, Some(&state), "  1,234,567  42%");
    super::transfer_orchestration::sync_progress_line(None, Some(&state), "  2,345,678  71%");

    let after = state.lock().unwrap().progress_counter();
    assert_eq!(
        after,
        before + 2,
        "each sync output segment must count as heartbeat forward progress"
    );

    // No heartbeat state attached: must be a no-op, not a panic.
    super::transfer_orchestration::sync_progress_line(None, None, "stats line");
}

#[test]
fn test_is_toolchain_failure_basic() {
    let _guard = test_guard!();
    // Should detect toolchain issues
    assert!(is_toolchain_failure(
        "error: toolchain 'nightly-2025-01-01' is not installed",
        1
    ));
    assert!(is_toolchain_failure("rustup: command not found", 127));
    assert!(is_toolchain_failure(
        "error: no default toolchain configured",
        1
    ));
    assert!(is_toolchain_failure(
        "error: toolchain 'nightly-2025-01-01' does not have the binary `cargo`",
        1
    ));

    // Should not flag normal failures
    assert!(!is_toolchain_failure(
        "error[E0425]: cannot find value `x`",
        1
    ));
    assert!(!is_toolchain_failure(
        "test result: FAILED. 1 passed; 2 failed",
        101
    ));

    // Success should never be a toolchain failure
    assert!(!is_toolchain_failure("anything", 0));
}

#[test]
fn test_is_toolchain_failure_ignores_rustup_toolchain_paths_in_normal_failures() {
    let _guard = test_guard!();
    let stderr = r#"error: could not compile `serde` (lib)
Caused by:
  process didn't exit successfully: `/home/ubuntu/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/bin/rustc --crate-name serde ...` (signal: 9, SIGKILL: kill)
"#;

    assert!(
        !is_toolchain_failure(stderr, 137),
        "SIGKILL/OOM stderr mentioning .rustup/toolchains paths must not trigger local fallback"
    );

    let compile_error = r#"error[E0425]: cannot find value `x` in this scope
note: the compiler executable is /home/ubuntu/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/bin/rustc
"#;

    assert!(
        !is_toolchain_failure(compile_error, EXIT_BUILD_ERROR),
        "ordinary compile errors mentioning the rustc toolchain path must not trigger local fallback"
    );
}

#[test]
fn test_detect_worker_system_dependency_failure_from_pkg_config_output() {
    let _guard = test_guard!();
    let stderr = r#"thread 'main' panicked at build.rs:42:14:
called `Result::unwrap()` on an `Err` value:
pkg-config exited with status code 1
> PKG_CONFIG_ALLOW_SYSTEM_LIBS=1 pkg-config --libs --cflags x11 'x11 >= 1.4.99.1'

The system library `x11` required by crate `x11` was not found.
The file `x11.pc` needs to be installed and the PKG_CONFIG_PATH environment variable must contain its parent directory.
"#;

    let failure = detect_worker_system_dependency_failure(stderr, EXIT_BUILD_ERROR)
        .expect("pkg-config/system dependency failure should be detected");

    assert_eq!(failure.system_library.as_deref(), Some("x11"));
    assert_eq!(failure.crate_name.as_deref(), Some("x11"));
    assert_eq!(failure.pkg_config_file.as_deref(), Some("x11.pc"));
    assert_eq!(failure.summary(), "missing worker system package x11.pc");
    assert!(failure.remediation().contains("x11.pc"));
}

#[test]
fn remote_disk_exhaustion_requires_a_failed_execution_and_covers_quota_errors() {
    for stderr in [
        "error: failed to write: No space left on device (os error 28)",
        "ld: output failed: ENOSPC",
        "rustup: Disk quota exceeded",
        "error[E0308]: mismatched types\nerror: write failed: no space left on device",
    ] {
        assert!(remote_failure_is_disk_full(stderr, 101), "{stderr}");
        assert!(remote_failure_is_worker_fault(stderr, 101), "{stderr}");
        assert!(!remote_failure_is_disk_full(stderr, 0), "{stderr}");
    }
    for stderr in [
        "error[E0308]: mismatched types",
        "test result: FAILED. 3 passed; 1 failed",
        "error: Permission denied (os error 13)",
        "",
    ] {
        assert!(!remote_failure_is_disk_full(stderr, 101), "{stderr}");
    }
}

#[test]
fn source_upload_disk_release_requires_the_selected_worker_and_confirmed_ownership() {
    let worker = WorkerId::new("upload-worker");
    let error = anyhow::anyhow!("source receiver failed")
        .context(crate::transfer::RemoteUploadDiskFull {
            worker_id: worker.to_string(),
            roots: vec!["/source-volume/project".into()],
        })
        .context("source preparation failed before remote command execution");
    let result = Err(error);
    let (worker_fault, disk_fault, roots) = remote_release_faults(&result, &worker);
    assert!(worker_fault && disk_fault);
    assert_eq!(roots, ["/source-volume/project"]);
    assert_eq!(
        remote_release_faults(&result, &WorkerId::new("other-worker")),
        (false, false, &[] as &[String])
    );
    let result = result.map_err(|error| error.context(crate::transfer::RemoteExecutionUnconfirmed));
    assert_eq!(
        classify_remote_pipeline_failure(result.as_ref().unwrap_err()),
        RemotePipelineFailurePolicy::FailClosedNoLocalFallback
    );
    assert_eq!(
        remote_release_faults(&result, &worker),
        (false, false, &[] as &[String])
    );
    assert!(is_remote_execution_unconfirmed(
        result.as_ref().unwrap_err()
    ));
}

#[test]
fn source_upload_disk_release_never_infers_worker_pressure_from_untyped_transfer_errors() {
    let worker = WorkerId::new("upload-worker");
    let result = Err(TransferError::SyncFailed {
        reason: "rsync artifact retrieval failed".into(),
        exit_code: Some(23),
        stderr: "rsync: [receiver] write failed on target/app: No space left on device (28)".into(),
    }
    .into());
    assert_eq!(
        remote_release_faults(&result, &worker),
        (false, false, &[] as &[String])
    );
    // Existing remote-command evidence still follows its actual exit status.
    for exit_code in [0, 101] {
        let result = Ok(remote_result::RemoteExecutionResult {
            deadline_triggered: false,
            exit_code,
            stderr: "No space left on device".into(),
            duration_ms: 10,
            timing: Default::default(),
            result_dirs: Vec::new(),
            disk_roots: vec!["/build-volume/target".into()],
            cargo_stdout: None,
        });
        let (worker_fault, disk_fault, roots) = remote_release_faults(&result, &worker);
        assert_eq!(worker_fault, exit_code != 0);
        assert_eq!(disk_fault, exit_code != 0);
        assert_eq!(roots, ["/build-volume/target"]);
    }
}

#[test]
fn test_remote_failure_is_worker_fault_separates_worker_breakage_from_project_errors() {
    let _guard = test_guard!();
    // Review of GH #81: only these failures withhold the daemon's cache
    // warmth; the project's own compile/test failures must still warm.
    let worker_faults = [
        (
            "error: toolchain 'nightly-2026-01-01-x86_64-unknown-linux-gnu' is not installed",
            1,
        ),
        (
            "The system library `openssl` required by crate `openssl-sys` was not found.\n\
             The file `openssl.pc` needs to be installed and the PKG_CONFIG_PATH environment variable must contain its parent directory.",
            101,
        ),
        ("", 132),
        (
            "error: failed to run custom build command for `ring v0.17.8`\n\
             process didn't exit successfully: `/t/build-script-build` (signal: 4, SIGILL: illegal instruction)",
            101,
        ),
        (
            "error: failed to write /data/projects/p/target/debug/deps/libx.rlib: No space left on device (os error 28)",
            101,
        ),
    ];
    for (stderr, exit_code) in worker_faults {
        assert!(
            remote_failure_is_worker_fault(stderr, exit_code),
            "{exit_code}: {stderr}"
        );
    }

    let project_failures = [
        (
            "error[E0308]: mismatched types\nerror: could not compile `poolrepro`",
            101,
        ),
        ("test result: FAILED. 3 passed; 1 failed", 101),
        ("", 130),
        ("", 137),
    ];
    for (stderr, exit_code) in project_failures {
        assert!(
            !remote_failure_is_worker_fault(stderr, exit_code),
            "{exit_code}: {stderr}"
        );
    }
    // A zero exit is never a fault, whatever it printed.
    assert!(!remote_failure_is_worker_fault(
        "No space left on device",
        0
    ));
}

#[test]
fn test_detect_worker_system_dependency_failure_ignores_normal_compile_errors() {
    let _guard = test_guard!();
    let stderr = r#"error[E0425]: cannot find value `oops` in this scope
 --> src/main.rs:4:5
  |
4 |     oops();
  |     ^^^^ not found in this scope
"#;

    assert!(
        detect_worker_system_dependency_failure(stderr, EXIT_BUILD_ERROR).is_none(),
        "ordinary compile errors must not be misclassified as worker env failures"
    );
}

// =========================================================================
// Cargo test integration tests (bead remote_compilation_helper-iyv1)
// =========================================================================

#[test]
fn test_wrap_command_with_telemetry_handles_comments() {
    let _guard = test_guard!();
    let worker_id = rch_common::WorkerId::new("worker1");
    let command = "echo hello # my comment";
    let wrapped = wrap_command_with_telemetry(command, &worker_id);

    // Ensure newline separation exists
    assert!(wrapped.contains(&format!("{}\nstatus=$?", command)));

    // Ensure status capture isn't commented out (it should be on a new line)
    let lines: Vec<&str> = wrapped.lines().collect();
    assert!(lines.iter().any(|l| l.starts_with("status=$?")));

    // Basic sanity check on structure
    assert!(wrapped.contains("rch-telemetry collect"));
    assert!(wrapped.contains("exit $status"));
}

#[test]
fn test_add_cargo_isolation_uses_durable_per_worker_cargo_home() {
    let _guard = test_guard!();
    let worker_id = rch_common::WorkerId::new("test-worker");

    // Test cargo build command gets isolation
    let cargo_command = "cargo build --release";
    let isolated = add_cargo_isolation(cargo_command, &worker_id);

    assert!(isolated.starts_with("sh -c "));
    assert!(!isolated.starts_with("CARGO_HOME="));
    // The staging base is resolved on the worker (no hardcoded /tmp) and the
    // basename uses the durable rch-cargo-cache- prefix (NOT the per-job
    // rch-cargo-home- prefix that orphan cleanup matches).
    assert!(
        !isolated.contains("/tmp/rch-cargo-cache-"),
        "must not hardcode /tmp: {isolated}"
    );
    assert!(isolated.contains("RCH_CH_BASE="));
    assert!(isolated.contains("/data/tmp"));
    assert!(isolated.contains("mkdir -p \"${RCH_CH_BASE}/rch-cargo-cache-test-worker\""));
    assert!(isolated.contains("CARGO_HOME=\"${RCH_CH_BASE}/rch-cargo-cache-test-worker\""));
    assert!(!isolated.contains("rch-cargo-home-"));
    assert!(isolated.contains("cargo build --release"));
    // Git-dependency fetches go through the git CLI when the worker has git.
    assert!(isolated.contains("CARGO_NET_GIT_FETCH_WITH_CLI=true"));
    assert!(isolated.contains("command -v git"));
    // Issue #42: the cache dir is durable across jobs — the wrapper must not
    // delete it after the build.
    assert!(!isolated.contains("rm "));

    // The same worker always maps to the same cache dir (that IS the reuse).
    let again = add_cargo_isolation(cargo_command, &worker_id);
    assert_eq!(isolated, again);
}

#[test]
fn test_sanitize_cargo_home_token_collapses_unsafe_chars() {
    // Path-safe tokens pass through unchanged.
    assert_eq!(sanitize_cargo_home_token("worker-1_2"), "worker-1_2");
    // Spaces, slashes and other shell-meaningful chars collapse to '-'.
    assert_eq!(sanitize_cargo_home_token("a b/c"), "a-b-c");
    // Leading/trailing unsafe chars are trimmed, not left as dangling '-'.
    assert_eq!(sanitize_cargo_home_token("  weird!! "), "weird");
    // An entirely-unsafe (or empty) token falls back to a stable default.
    assert_eq!(sanitize_cargo_home_token("***"), "worker");
    assert_eq!(sanitize_cargo_home_token(""), "worker");
}

// =========================================================================
// Issue #19 Fix 3: pooled remote target-dir REUSE
// =========================================================================

#[test]
fn test_pooled_target_dir_same_dimensions_reuse_same_name() {
    // (a) The whole point: identical (project, toolchain, triple, profile,
    // features) yields the SAME remote dir name across calls, so the warm
    // remote incremental cache is reused instead of cold-recompiling.
    let _guard = test_guard!();
    let worker = rch_common::WorkerId::new("ts2");
    let root = Path::new("/data/projects/acme");
    let tc = ToolchainInfo::new("nightly", Some("2025-11-01".to_string()), "x");

    let a = remote_cargo_pooled_target_dir_name(&worker, root, Some(&tc), "cargo build");
    let b = remote_cargo_pooled_target_dir_name(&worker, root, Some(&tc), "cargo build");
    assert_eq!(a, b, "same dimensions must reuse the same pooled dir");

    // Feature SET (not order/dups) determines the key.
    let f1 = remote_cargo_pooled_target_dir_name(
        &worker,
        root,
        Some(&tc),
        "cargo build --features serde,tokio",
    );
    let f2 = remote_cargo_pooled_target_dir_name(
        &worker,
        root,
        Some(&tc),
        "cargo build --features tokio --features serde",
    );
    assert_eq!(f1, f2, "feature set is order/dup-insensitive");
}

#[test]
fn test_pooled_target_dir_each_dimension_change_invalidates() {
    // (b) Changing ANY cache dimension yields a DIFFERENT name, so an
    // incompatible build never reuses a contaminated pool.
    let _guard = test_guard!();
    let worker = rch_common::WorkerId::new("ts2");
    let root = Path::new("/data/projects/acme");
    let tc = ToolchainInfo::new("nightly", Some("2025-11-01".to_string()), "x");
    let base = remote_cargo_pooled_target_dir_name(&worker, root, Some(&tc), "cargo build");

    // Profile (--release).
    assert_ne!(
        base,
        remote_cargo_pooled_target_dir_name(&worker, root, Some(&tc), "cargo build --release"),
        "profile change must invalidate"
    );
    // Target triple.
    assert_ne!(
        base,
        remote_cargo_pooled_target_dir_name(
            &worker,
            root,
            Some(&tc),
            "cargo build --target wasm32-unknown-unknown"
        ),
        "triple change must invalidate"
    );
    // Toolchain.
    let tc2 = ToolchainInfo::new("nightly", Some("2026-01-01".to_string()), "x");
    assert_ne!(
        base,
        remote_cargo_pooled_target_dir_name(&worker, root, Some(&tc2), "cargo build"),
        "toolchain change must invalidate"
    );
    // Features.
    assert_ne!(
        base,
        remote_cargo_pooled_target_dir_name(
            &worker,
            root,
            Some(&tc),
            "cargo build --features serde"
        ),
        "feature change must invalidate"
    );
    assert_ne!(
        base,
        remote_cargo_pooled_target_dir_name(&worker, root, Some(&tc), "cargo build --all-features"),
        "--all-features must invalidate"
    );
    // Project root.
    assert_ne!(
        base,
        remote_cargo_pooled_target_dir_name(
            &worker,
            Path::new("/data/projects/other"),
            Some(&tc),
            "cargo build"
        ),
        "project change must invalidate (no cross-project contamination)"
    );
}

#[test]
fn test_pooled_target_dir_name_shape_is_single_segment_and_reapable() {
    // (d) The name has no `/` (so `with_remote_cargo_target_dir_name` accepts
    // it) and keeps the `.rch-target-…-pool-…` shape the reaper recognizes.
    let _guard = test_guard!();
    let worker = rch_common::WorkerId::new("ts2");
    let root = Path::new("/data/projects/acme");
    let tc = ToolchainInfo::new("nightly", Some("2025-11-01".to_string()), "x");
    let name = remote_cargo_pooled_target_dir_name(&worker, root, Some(&tc), "cargo build");

    assert!(
        !name.contains('/'),
        "pooled name must be a single segment: {name}"
    );
    assert!(
        name.starts_with(".rch-target-"),
        "must keep the reaper-recognized prefix: {name}"
    );
    assert!(
        name.contains("-pool-"),
        "must carry the -pool- marker the reaper globs match: {name}"
    );
    assert!(
        rch_common::stale_target_reap::is_safe_reap_token(&name),
        "pooled name must be reap-token-safe: {name}"
    );
}

#[test]
fn test_target_reuse_opt_out_restores_unique_per_job_name() {
    // (c) The opt-out predicate is honored; under opt-out the legacy
    // unique-per-job name is used (distinct per call, distinct from pooled).
    let _guard = test_guard!();
    // Predicate: truthy values disable reuse; falsy/unset keep it on.
    assert!(target_reuse_disabled_from_value(Some("1".to_string())));
    assert!(target_reuse_disabled_from_value(Some("true".to_string())));
    assert!(target_reuse_disabled_from_value(Some("YES".to_string())));
    assert!(!target_reuse_disabled_from_value(None));
    assert!(!target_reuse_disabled_from_value(Some("0".to_string())));
    assert!(!target_reuse_disabled_from_value(Some("false".to_string())));
    assert!(!target_reuse_disabled_from_value(Some(String::new())));

    // The fallback path (unique-per-job) is non-pooled and unique per call.
    let worker = rch_common::WorkerId::new("ts2");
    let root = Path::new("/data/projects/acme");
    let tc = ToolchainInfo::new("nightly", Some("2025-11-01".to_string()), "x");
    let pooled = remote_cargo_pooled_target_dir_name(&worker, root, Some(&tc), "cargo build");
    let unique_a = remote_cargo_target_dir_name(Some(7), &worker);
    let unique_b = remote_cargo_target_dir_name(Some(7), &worker);
    assert_ne!(unique_a, unique_b, "opt-out name is unique per invocation");
    assert_ne!(
        pooled, unique_a,
        "opt-out name differs from the pooled name"
    );
    assert!(
        !unique_a.contains("-pool-"),
        "opt-out name is not a pool dir"
    );
}

#[test]
fn test_feature_and_triple_parsing_from_command() {
    let _guard = test_guard!();
    // --features list (comma-separated), the `=` form, and `-F`. The command
    // is a whitespace-tokenized string, so a single `--features` value is a
    // comma list (`a,b`); a space-separated `--features a b` lists `a` and
    // takes `b` as the next positional only if it follows the flag directly,
    // so we use the comma form (cargo's own canonical multi-feature syntax).
    assert_eq!(
        feature_set_for_command("cargo build --features a,b --features=c,d -F e"),
        vec!["a", "b", "c", "d", "e"]
    );
    assert!(
        feature_set_for_command("cargo build --all-features")
            .iter()
            .any(|f| f == "__rch_all_features")
    );
    assert!(
        feature_set_for_command("cargo build --no-default-features")
            .iter()
            .any(|f| f == "__rch_no_default_features")
    );

    // Triple: explicit wins, else host default (stable, non-empty).
    assert_eq!(
        target_triple_for_command("cargo build --target wasm32-unknown-unknown"),
        "wasm32-unknown-unknown"
    );
    assert_eq!(
        target_triple_for_command("cargo build --target=aarch64-apple-darwin"),
        "aarch64-apple-darwin"
    );
    let host = target_triple_for_command("cargo build");
    assert!(!host.is_empty(), "host triple fallback must be non-empty");
    assert_eq!(
        host,
        target_triple_for_command("cargo build"),
        "host triple fallback must be stable"
    );
}

#[test]
fn test_zigbuild_requires_the_zig_runtime_not_bare_rust() {
    let _guard = test_guard!();
    // A zig cross-build must NOT be gated as an ordinary Rust build: worker
    // selection would then admit any rustc-capable worker, and a worker without
    // `cargo-zigbuild` fails with `error: no such command: 'zigbuild'`, which
    // `is_toolchain_failure` does not recognize — so the nonzero exit reaches
    // the user verbatim instead of falling open to local.
    assert_eq!(
        required_runtime_for_kind(Some(CompilationKind::CargoZigbuild)),
        RequiredRuntime::Zig
    );
    // The ordinary cargo kinds keep the plain Rust gate.
    for kind in [
        CompilationKind::CargoBuild,
        CompilationKind::CargoTest,
        CompilationKind::CargoCheck,
        CompilationKind::Rustc,
    ] {
        assert_eq!(
            required_runtime_for_kind(Some(kind)),
            RequiredRuntime::Rust,
            "{kind:?} must stay on the Rust runtime gate"
        );
    }
}

#[test]
fn test_kind_produces_transferable_artifacts() {
    let _guard = test_guard!();
    // Build/doc/rustc + C/C++/build-system kinds produce required artifacts.
    for kind in [
        CompilationKind::CargoBuild,
        CompilationKind::CargoDoc,
        CompilationKind::Rustc,
        CompilationKind::Gcc,
        CompilationKind::Make,
        CompilationKind::CmakeBuild,
        CompilationKind::Ninja,
    ] {
        assert!(
            kind_produces_transferable_artifacts(Some(kind)),
            "{kind:?} must be artifact-producing"
        );
    }
    // Test/diagnostic kinds stream their results; no required artifact.
    for kind in [
        CompilationKind::CargoTest,
        CompilationKind::CargoNextest,
        CompilationKind::CargoBench,
        CompilationKind::CargoCheck,
        CompilationKind::CargoClippy,
        CompilationKind::BunTest,
        CompilationKind::BunTypecheck,
    ] {
        assert!(
            !kind_produces_transferable_artifacts(Some(kind)),
            "{kind:?} must NOT be treated as artifact-producing"
        );
    }
    assert!(!kind_produces_transferable_artifacts(None));
}

#[test]
fn test_job_admission_is_never_classifier_produced() {
    let _guard = test_guard!();
    // bd-bu3fb regression guard: `CompilationKind::Job` exists ONLY for the
    // explicit `rch exec --job` admission flag. The classifier (and therefore
    // the PreToolUse hook, which only ever delegates what classify_command
    // intercepts) must never produce it — otherwise every non-compilation
    // command an agent runs could be silently shipped to a remote worker.
    let commands = [
        // Ordinary non-compilation commands.
        "ls -la",
        "git status",
        "git push origin main",
        "pytest -x -q",
        "python3 script.py",
        "echo hello > out.txt",
        "curl https://example.com",
        "grep -rn TODO src/",
        "rm build/output.o",
        // Bun package management / execution: explicitly local per AGENTS.md.
        "bun install",
        "bun add left-pad",
        "bun remove left-pad",
        "bun run dev",
        "bun build ./index.ts",
        "bun x prettier .",
        "bunx prettier .",
        "bun test --watch",
        // Nix interactive/mutating forms: local by design.
        "nix develop",
        "nix run .#foo",
        "nix repl",
        "nix profile list",
        "nix flake update",
        "nix store gc",
        "nix-env -iA nixpkgs.hello",
        // Package management / watch / piped / backgrounded patterns.
        "cargo install rch",
        "cargo clean",
        "cargo build --watch",
        "make test | tee log.txt",
        "cmake --build build &",
        "bash -lc \"cargo test && cargo test\"",
        // Even genuine compilations must classify as their OWN kind, never Job.
        "cargo build --release",
        "cargo test --workspace",
        "go test ./...",
        "tsc --noEmit",
        "nix build .#default",
    ];
    for cmd in commands {
        let classification = classify_command(cmd);
        assert_ne!(
            classification.kind,
            Some(CompilationKind::Job),
            "classifier produced job admission for `{cmd}` — the hook would \
             auto-delegate a command it did not intercept"
        );
    }
}

#[test]
fn test_job_kind_pipeline_contract() {
    let _guard = test_guard!();
    // A job carries no runtime gate: any worker may take it.
    assert_eq!(
        required_runtime_for_kind(Some(CompilationKind::Job)),
        RequiredRuntime::None
    );
    // Jobs have no artifact contract in this phase: nothing is synced back and
    // a sync-back miss can never fail the invocation.
    assert!(get_artifact_patterns(Some(CompilationKind::Job), None).is_empty());
    assert!(get_project_artifact_patterns(Some(CompilationKind::Job), None, false).is_empty());
    assert!(get_project_artifact_patterns(Some(CompilationKind::Job), None, true).is_empty());
    assert!(get_custom_target_artifact_patterns(Some(CompilationKind::Job), None).is_empty());
    assert!(!kind_produces_transferable_artifacts(Some(
        CompilationKind::Job
    )));
    // And it is not mistaken for a test kind (cache affinity / record_build).
    assert!(!CompilationKind::Job.is_test_command());
}

#[test]
fn test_validate_job_result_dirs_accepts_relative_paths_and_dedupes() {
    let _guard = test_guard!();
    let validated = validate_job_result_dirs(vec![
        PathBuf::from("results/shard-a"),
        PathBuf::from("./fuzz/corpus"),
        // Duplicate (after `./` normalization) must collapse, preserving the
        // first occurrence's position.
        PathBuf::from("results/shard-a"),
    ])
    .expect("valid result dirs");
    assert_eq!(
        validated,
        vec![
            PathBuf::from("results/shard-a"),
            PathBuf::from("fuzz/corpus"),
        ],
        "result dirs must normalize `.` segments and dedupe"
    );
}

#[test]
fn test_validate_job_result_dirs_rejects_unsafe_paths() {
    let _guard = test_guard!();
    let unsafe_inputs = [
        PathBuf::from("../escape"),
        PathBuf::from("results/../../escape"),
        PathBuf::from("/absolute/path"),
        PathBuf::from(r"back\slash"),
        PathBuf::from("results/café"),
        PathBuf::new(),
    ];
    for input in unsafe_inputs {
        assert!(
            validate_job_result_dirs(vec![input.clone()]).is_err(),
            "unsafe result dir {:?} must be rejected before any transfer",
            input
        );
    }
}

#[test]
fn test_add_cargo_isolation_skips_non_cargo_commands() {
    let _guard = test_guard!();
    let worker_id = rch_common::WorkerId::new("test-worker");

    // Test non-cargo command is unchanged
    let non_cargo_command = "echo hello world";
    let isolated = add_cargo_isolation(non_cargo_command, &worker_id);

    assert_eq!(isolated, non_cargo_command);
    assert!(!isolated.contains("CARGO_HOME"));
}

#[test]
fn test_add_cargo_isolation_handles_complex_cargo_commands() {
    let _guard = test_guard!();
    let worker_id = rch_common::WorkerId::new("worker-123");

    // Test complex cargo command with environment variables and arguments
    let complex_command =
        "cd /some/path && RUSTFLAGS=\"-C target-cpu=native\" cargo test --release --features=foo";
    let isolated = add_cargo_isolation(complex_command, &worker_id);

    assert!(isolated.starts_with("sh -c "));
    assert!(
        !isolated.contains("/tmp/rch-cargo-cache-"),
        "must not hardcode /tmp: {isolated}"
    );
    assert!(isolated.contains("mkdir -p \"${RCH_CH_BASE}/rch-cargo-cache-worker-123\""));
    assert!(isolated.contains("CARGO_HOME=\"${RCH_CH_BASE}/rch-cargo-cache-worker-123\""));
    assert!(isolated.contains(
        "cd /some/path && RUSTFLAGS=\"-C target-cpu=native\" cargo test --release --features=foo"
    ));
    // The durable cache must never be deleted by the job wrapper (issue #42).
    assert!(!isolated.contains("rch-cargo-cache-worker-123/ "));
    assert!(!isolated.contains("rm "));
}

#[test]
fn test_add_cargo_isolation_survives_timeout_prefix_and_preserves_status() {
    let _guard = test_guard!();
    let worker_id = rch_common::WorkerId::new("timeout-worker");
    let isolated = add_cargo_isolation("printf cargo >/dev/null; exit 42", &worker_id);
    let status = std::process::Command::new("sh") // ubs:ignore — executes the fixed isolation-wrapper regression command above.
        .arg("-c")
        .arg(format!(
            "timeout --foreground --preserve-status 5 {}",
            isolated
        ))
        .status()
        .expect("timeout-wrapped isolated command should execute");

    assert_eq!(
        status.code(),
        Some(42),
        "timeout must execute the shell wrapper and preserve the command status"
    );
}

#[test]
fn test_add_cargo_isolation_repairs_dangling_registry_link() {
    // bd-hiu2v: a cache whose `registry` link points at a reclaimed
    // ~/.cargo/registry made every crates.io fetch fail with EEXIST.
    let _guard = test_guard!();
    let base = tempfile::tempdir().unwrap();
    let base_path = base.path().canonicalize().unwrap();
    let worker_id = rch_common::WorkerId::new("dangling-worker");
    let cache = base_path.join("rch-cargo-cache-dangling-worker");
    std::fs::create_dir_all(&cache).unwrap();
    let reclaimed = base_path.join("reclaimed-account-registry");
    std::os::unix::fs::symlink(&reclaimed, cache.join("registry")).unwrap();
    assert!(!cache.join("registry").exists(), "fixture link must dangle");

    let isolated = add_cargo_isolation(
        "printf cargo >/dev/null; test -d \"$CARGO_HOME/registry\" && touch \"$CARGO_HOME/registry/ok\"",
        &worker_id,
    );
    let status = std::process::Command::new("sh") // ubs:ignore — executes the fixed isolation wrapper above.
        .arg("-c")
        .arg(&isolated)
        .env("TMPDIR", &base_path)
        // Under `rch exec` the test inherits the worker's own cache base;
        // clear it so the wrapper resolves the fixture base from TMPDIR.
        .env_remove(rch_common::RCH_CARGO_HOME_BASE_VAR)
        .status()
        .expect("isolated command should execute");

    assert!(
        status.success(),
        "dangling registry link was not repaired: {status:?}"
    );
    assert!(
        std::fs::symlink_metadata(cache.join("registry"))
            .unwrap()
            .file_type()
            .is_symlink(),
        "the operator's link is kept, not replaced"
    );
    assert!(
        reclaimed.join("ok").exists(),
        "writes land in the recreated link target"
    );
}

#[test]
fn test_remote_cargo_target_dir_name_is_unique_and_path_safe() {
    let _guard = test_guard!();
    let worker_id = rch_common::WorkerId::new("worker/with spaces");
    let first = remote_cargo_target_dir_name(Some(42), &worker_id);
    let second = remote_cargo_target_dir_name(Some(42), &worker_id);

    assert!(first.starts_with(".rch-target-worker-with-spaces-job-42-"));
    assert!(!first.contains('/'));
    assert!(!first.contains(' '));
    assert_ne!(first, second);
}

#[test]
fn test_parse_stale_target_reap_idle_hours() {
    // Default when unset or unparseable.
    assert_eq!(parse_stale_target_reap_idle_hours(None), 12);
    assert_eq!(
        parse_stale_target_reap_idle_hours(Some("not-a-number".into())),
        12
    );
    assert_eq!(parse_stale_target_reap_idle_hours(Some(String::new())), 12);
    // Honors a valid override (with surrounding whitespace).
    assert_eq!(parse_stale_target_reap_idle_hours(Some("24".into())), 24);
    assert_eq!(parse_stale_target_reap_idle_hours(Some("  6 ".into())), 6);
    // Floors at 1h so a misconfiguration can never reap a live cache.
    assert_eq!(parse_stale_target_reap_idle_hours(Some("0".into())), 1);
}

#[test]
fn test_resolve_forwarded_cargo_target_dir_reads_env_without_allowlist() {
    let _guard = test_guard!();
    let reporter = HookReporter::new(OutputVisibility::Verbose);
    let resolved = resolve_forwarded_cargo_target_dir_with_lookup(
        Some(CompilationKind::CargoBuild),
        Path::new("/tmp/rch"),
        &reporter,
        |_| Some("/tmp/rch-target-no-allowlist".to_string()),
        None,
    );

    assert_eq!(
        resolved,
        Some(PathBuf::from("/tmp/rch-target-no-allowlist"))
    );
}

#[test]
fn test_resolve_forwarded_cargo_target_dir_defaults_for_cargo() {
    let _guard = test_guard!();
    let reporter = HookReporter::new(OutputVisibility::Verbose);
    let resolved = resolve_forwarded_cargo_target_dir_with_lookup(
        Some(CompilationKind::CargoBuild),
        Path::new("/data/projects/remote_compilation_helper"),
        &reporter,
        |_| None,
        None,
    );

    assert_eq!(
        resolved,
        Some(PathBuf::from(
            "/data/projects/remote_compilation_helper/target"
        ))
    );
}

#[test]
fn test_resolve_forwarded_cargo_target_dir_ignores_non_cargo() {
    let _guard = test_guard!();
    let reporter = HookReporter::new(OutputVisibility::Verbose);
    let resolved = resolve_forwarded_cargo_target_dir_with_lookup(
        Some(CompilationKind::BunTest),
        Path::new("/data/projects/remote_compilation_helper"),
        &reporter,
        |_| Some("/tmp/should-not-forward".to_string()),
        None,
    );

    assert!(resolved.is_none());
}

#[test]
fn test_resolve_forwarded_cargo_target_dir_resolves_relative_path() {
    let _guard = test_guard!();
    let reporter = HookReporter::new(OutputVisibility::Verbose);
    let resolved = resolve_forwarded_cargo_target_dir_with_lookup(
        Some(CompilationKind::CargoBuild),
        Path::new("/data/projects/remote_compilation_helper"),
        &reporter,
        |_| Some("tmp/custom-target".to_string()),
        None,
    );

    assert_eq!(
        resolved,
        Some(PathBuf::from(
            "/data/projects/remote_compilation_helper/tmp/custom-target"
        ))
    );
}

#[test]
fn test_resolve_forwarded_cargo_target_dir_extracts_env_wrapper_assignment() {
    let _guard = test_guard!();
    let reporter = HookReporter::new(OutputVisibility::Verbose);
    let command_tokens = vec![
        "env".to_string(),
        "-u".to_string(),
        "RUST_LOG".to_string(),
        "RUST_BACKTRACE=1".to_string(),
        "CARGO_TARGET_DIR=/data/projects/custom-target".to_string(),
        "cargo".to_string(),
        "check".to_string(),
    ];
    let resolved = resolve_forwarded_cargo_target_dir_with_lookup(
        Some(CompilationKind::CargoBuild),
        Path::new("/data/projects/remote_compilation_helper"),
        &reporter,
        |_| Some("/tmp/env-should-lose-to-command".to_string()),
        Some(&command_tokens),
    );

    assert_eq!(
        resolved,
        Some(PathBuf::from("/data/projects/custom-target"))
    );
}

#[test]
fn test_resolve_forwarded_cargo_target_dir_extracts_inline_assignment() {
    let _guard = test_guard!();
    let reporter = HookReporter::new(OutputVisibility::Verbose);
    let command_tokens = vec![
        "CARGO_TARGET_DIR=.rch-target-inline".to_string(),
        "cargo".to_string(),
        "build".to_string(),
    ];
    let resolved = resolve_forwarded_cargo_target_dir_with_lookup(
        Some(CompilationKind::CargoBuild),
        Path::new("/data/projects/remote_compilation_helper"),
        &reporter,
        |_| None,
        Some(&command_tokens),
    );

    assert_eq!(
        resolved,
        Some(PathBuf::from(
            "/data/projects/remote_compilation_helper/.rch-target-inline"
        ))
    );
}

#[test]
fn test_resolve_forwarded_cargo_target_dir_extracts_target_dir_flag() {
    let _guard = test_guard!();
    let reporter = HookReporter::new(OutputVisibility::Verbose);
    let command_tokens = vec![
        "cargo".to_string(),
        "build".to_string(),
        "--target-dir".to_string(),
        "/data/tmp/rch-target-flag".to_string(),
        "--release".to_string(),
    ];
    let resolved = resolve_forwarded_cargo_target_dir_with_lookup(
        Some(CompilationKind::CargoBuild),
        Path::new("/data/projects/remote_compilation_helper"),
        &reporter,
        |_| None,
        Some(&command_tokens),
    );

    assert_eq!(resolved, Some(PathBuf::from("/data/tmp/rch-target-flag")));
}

#[test]
fn test_resolve_forwarded_cargo_target_dir_extracts_target_dir_equals_flag() {
    let _guard = test_guard!();
    let reporter = HookReporter::new(OutputVisibility::Verbose);
    let command_tokens = vec![
        "cargo".to_string(),
        "check".to_string(),
        "--target-dir=/data/tmp/rch-target-equals".to_string(),
    ];
    let resolved = resolve_forwarded_cargo_target_dir_with_lookup(
        Some(CompilationKind::CargoCheck),
        Path::new("/data/projects/remote_compilation_helper"),
        &reporter,
        |_| None,
        Some(&command_tokens),
    );

    assert_eq!(resolved, Some(PathBuf::from("/data/tmp/rch-target-equals")));
}

#[test]
fn test_rewrite_cargo_target_dir_command_for_remote_strips_inline_assignment() {
    let _guard = test_guard!();
    let reporter = HookReporter::new(OutputVisibility::Verbose);
    let command_tokens = vec![
        "env".to_string(),
        "-u".to_string(),
        "RUST_LOG".to_string(),
        "RUST_BACKTRACE=1".to_string(),
        "CARGO_TARGET_DIR=/data/projects/custom-target".to_string(),
        "cargo".to_string(),
        "build".to_string(),
        "--release".to_string(),
    ];

    let rewritten = rewrite_cargo_target_dir_command_for_remote(
        "env -u RUST_LOG RUST_BACKTRACE=1 CARGO_TARGET_DIR=/data/projects/custom-target cargo build --release",
        Some(&command_tokens),
        Some(&PathBuf::from("/data/projects/custom-target")),
        &reporter,
    );

    assert_eq!(
        rewritten,
        "env -u RUST_LOG 'RUST_BACKTRACE=1' cargo build --release"
    );
    assert!(!rewritten.contains("CARGO_TARGET_DIR=/data/projects/custom-target"));
}

#[test]
fn test_rewrite_cargo_target_dir_command_for_remote_strips_target_dir_flag() {
    let _guard = test_guard!();
    let reporter = HookReporter::new(OutputVisibility::Verbose);
    let command_tokens = vec![
        "cargo".to_string(),
        "build".to_string(),
        "--target-dir".to_string(),
        "/data/tmp/rch-target-flag".to_string(),
        "--release".to_string(),
    ];

    let rewritten = rewrite_cargo_target_dir_command_for_remote(
        "cargo build --target-dir /data/tmp/rch-target-flag --release",
        Some(&command_tokens),
        Some(&PathBuf::from("/data/tmp/rch-target-flag")),
        &reporter,
    );

    assert_eq!(rewritten, "cargo build --release");
    assert!(!rewritten.contains("--target-dir"));
    assert!(!rewritten.contains("/data/tmp/rch-target-flag"));
}

#[test]
fn test_rewrite_cargo_target_dir_command_for_remote_strips_target_dir_equals_flag() {
    let _guard = test_guard!();
    let reporter = HookReporter::new(OutputVisibility::Verbose);
    let command_tokens = vec![
        "cargo".to_string(),
        "check".to_string(),
        "--target-dir=/data/tmp/rch-target-equals".to_string(),
        "--workspace".to_string(),
    ];

    let rewritten = rewrite_cargo_target_dir_command_for_remote(
        "cargo check --target-dir=/data/tmp/rch-target-equals --workspace",
        Some(&command_tokens),
        Some(&PathBuf::from("/data/tmp/rch-target-equals")),
        &reporter,
    );

    assert_eq!(rewritten, "cargo check --workspace");
    assert!(!rewritten.contains("--target-dir"));
    assert!(!rewritten.contains("/data/tmp/rch-target-equals"));
}

#[test]
fn test_cargo_target_dir_scanner_ignores_args_after_delimiter() {
    let _guard = test_guard!();
    let reporter = HookReporter::new(OutputVisibility::Verbose);
    let command_tokens = vec![
        "cargo".to_string(),
        "test".to_string(),
        "--".to_string(),
        "--target-dir".to_string(),
        "test-filter".to_string(),
    ];
    let resolved = resolve_forwarded_cargo_target_dir_with_lookup(
        Some(CompilationKind::CargoTest),
        Path::new("/data/projects/remote_compilation_helper"),
        &reporter,
        |_| None,
        Some(&command_tokens),
    );
    let rewritten = rewrite_cargo_target_dir_command_for_remote(
        "cargo test -- --target-dir test-filter",
        Some(&command_tokens),
        Some(&PathBuf::from(
            "/data/projects/remote_compilation_helper/target",
        )),
        &reporter,
    );

    assert_eq!(
        resolved,
        Some(PathBuf::from(
            "/data/projects/remote_compilation_helper/target"
        ))
    );
    assert_eq!(rewritten, "cargo test -- --target-dir test-filter");
}

#[test]
fn test_rewrite_cargo_target_dir_command_preserves_args_after_delimiter() {
    let _guard = test_guard!();
    let reporter = HookReporter::new(OutputVisibility::Verbose);
    let command_tokens = vec![
        "cargo".to_string(),
        "test".to_string(),
        "--target-dir".to_string(),
        "/data/tmp/rch-target-flag".to_string(),
        "--".to_string(),
        "--nocapture".to_string(),
    ];

    let rewritten = rewrite_cargo_target_dir_command_for_remote(
        "cargo test --target-dir /data/tmp/rch-target-flag -- --nocapture",
        Some(&command_tokens),
        Some(&PathBuf::from("/data/tmp/rch-target-flag")),
        &reporter,
    );

    assert_eq!(rewritten, "cargo test -- --nocapture");
}

fn env_key_strategy() -> impl Strategy<Value = String> {
    prop::string::string_regex("[A-Z_][A-Z0-9_]{0,16}")
        .expect("valid env key regex")
        .prop_filter("not the target dir key under test", |key| {
            key != "CARGO_TARGET_DIR"
        })
}

fn shell_safe_value_strategy() -> impl Strategy<Value = String> {
    prop::string::string_regex("[A-Za-z0-9_./:+-]{0,40}").expect("valid env value regex")
}

fn relative_target_dir_strategy() -> impl Strategy<Value = String> {
    prop::string::string_regex("[A-Za-z0-9_.-]{1,16}(/[A-Za-z0-9_.-]{1,16}){0,2}")
        .expect("valid relative path regex")
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(256))]

    #[test]
    fn env_prefix_target_dir_parser_round_trips_and_rewrites(
        target_dir in relative_target_dir_strategy(),
        extra_envs in prop::collection::vec((env_key_strategy(), shell_safe_value_strategy()), 0..4),
        cargo_subcommand in prop_oneof![
            Just("build".to_string()),
            Just("check".to_string()),
            Just("test".to_string()),
            Just("clippy".to_string()),
        ],
    ) {
        let _guard = test_guard!();
        let reporter = HookReporter::new(OutputVisibility::Verbose);
        let mut tokens = vec!["env".to_string()];
        for (key, value) in &extra_envs {
            tokens.push(format!("{key}={value}"));
        }
        tokens.push(format!("CARGO_TARGET_DIR={target_dir}"));
        tokens.push("cargo".to_string());
        tokens.push(cargo_subcommand);
        tokens.push("--release".to_string());

        let command = join_exec_command(&tokens);
        let parsed = parse_command_tokens(&command, &reporter).expect("joined command should parse");
        prop_assert_eq!(&parsed, &tokens);
        prop_assert_eq!(
            extract_cargo_target_dir_from_command_tokens(&parsed),
            Some(target_dir.clone())
        );

        let invocation_cwd = Path::new("/tmp/rch-proptest-project");
        let resolved = resolve_forwarded_cargo_target_dir_with_lookup(
            Some(CompilationKind::CargoBuild),
            invocation_cwd,
            &reporter,
            |_| Some("/tmp/ambient-target".to_string()),
            Some(&parsed),
        );
        let expected_resolved = Some(invocation_cwd.join(&target_dir));
        prop_assert_eq!(resolved.as_ref(), expected_resolved.as_ref());

        let rewritten = rewrite_cargo_target_dir_command_for_remote(
            &command,
            Some(&parsed),
            resolved.as_ref(),
            &reporter,
        );
        prop_assert!(!rewritten.contains("CARGO_TARGET_DIR="));
        let rewritten_tokens = parse_command_tokens(&rewritten, &reporter)
            .expect("rewritten command should remain parseable");
        prop_assert_eq!(rewritten_tokens.first().map(String::as_str), Some("env"));
        for (key, value) in &extra_envs {
            let expected_assignment = format!("{key}={value}");
            prop_assert!(
                rewritten_tokens.contains(&expected_assignment),
                "rewritten command dropped env assignment {expected_assignment:?}"
            );
        }
        prop_assert!(rewritten_tokens.iter().any(|token| token == "cargo"));
    }

    #[test]
    fn env_prefix_helpers_do_not_panic_on_arbitrary_command_bytes(
        bytes in prop::collection::vec(any::<u8>(), 0..192),
    ) {
        let _guard = test_guard!();
        let reporter = HookReporter::new(OutputVisibility::Verbose);
        let command = String::from_utf8_lossy(&bytes).into_owned();

        if let Some(tokens) = parse_command_tokens(&command, &reporter) {
            let _ = extract_cargo_target_dir_from_command_tokens(&tokens);
            let _ = strip_cargo_target_dir_assignments_from_command_tokens(&tokens);
            let _ = strip_cargo_target_dir_flags_from_command_tokens(&tokens);

            let rewritten = rewrite_cargo_target_dir_command_for_remote(
                &command,
                Some(&tokens),
                Some(&PathBuf::from("/tmp/rch-proptest-target")),
                &reporter,
            );
            prop_assert!(
                parse_command_tokens(&rewritten, &reporter).is_some(),
                "parsed command rewrote to an unparsable command: {rewritten:?}"
            );
        }
    }
}

#[tokio::test]
async fn test_collect_repo_updater_roots_and_specs_filters_to_git_roots_with_origin() {
    let _guard = test_guard!();
    let temp_dir = tempfile::tempdir().expect("temp dir should be creatable");
    let with_origin = temp_dir.path().join("with_origin");
    let duplicate_origin = temp_dir.path().join("duplicate_origin");
    let without_origin = temp_dir.path().join("without_origin");
    let not_git = temp_dir.path().join("not_git");

    std::fs::create_dir_all(&with_origin).expect("create with_origin");
    std::fs::create_dir_all(&duplicate_origin).expect("create duplicate_origin");
    std::fs::create_dir_all(&without_origin).expect("create without_origin");
    std::fs::create_dir_all(&not_git).expect("create not_git");

    // Make the fixture hermetic. This test needs `not_git` to be genuinely
    // outside any repository, and it has always *assumed* that a temp dir is —
    // but never enforced it. rch rewrites TMPDIR into the project directory, so
    // under rch's own execution the temp dir lands INSIDE this repository's git
    // tree; git-root discovery then correctly walks up, finds the enclosing
    // repo, and `not_git` stops looking like a non-repo. Initialising the temp
    // root gives discovery a boundary to stop at, so the fixture means what it
    // says wherever TMPDIR happens to point. The boundary repo has no origin, so
    // it is filtered by the origin rule and never appears in the expectation.
    let status = std::process::Command::new("git")
        .arg("-C")
        .arg(temp_dir.path())
        .arg("init")
        .arg("-q")
        .status()
        .expect("git init should run for the fixture boundary");
    assert!(
        status.success(),
        "git init should succeed for the fixture boundary at {}",
        temp_dir.path().display()
    );

    for repo in [&with_origin, &duplicate_origin, &without_origin] {
        let status = std::process::Command::new("git")
            .arg("-C")
            .arg(repo)
            .arg("init")
            .arg("-q")
            .status()
            .expect("git init should run");
        assert!(
            status.success(),
            "git init should succeed for {}",
            repo.display()
        );
    }

    let origin_url = "git@github.com:example/repo-with-origin.git";
    for repo in [&with_origin, &duplicate_origin] {
        let status = std::process::Command::new("git")
            .arg("-C")
            .arg(repo)
            .arg("remote")
            .arg("add")
            .arg("origin")
            .arg(origin_url)
            .status()
            .expect("git remote add should run");
        assert!(
            status.success(),
            "git remote add should succeed for {}",
            repo.display()
        );
    }

    let collected = collect_repo_updater_roots_and_specs(&[
        with_origin.clone(),
        without_origin.clone(),
        not_git.clone(),
        duplicate_origin.clone(),
    ])
    .await;

    assert_eq!(
        collected.roots,
        vec![with_origin.clone(), duplicate_origin.clone()]
    );
    assert_eq!(collected.specs, vec![origin_url.to_string()]);
}

#[test]
fn test_auto_tune_repo_updater_contract_autoseeds_allowlist_and_mode() {
    let _guard = test_guard!();
    let mut contract = RepoUpdaterAdapterContract::default();
    let repo_specs = vec!["github.com/example/repo".to_string()];
    let auth_context = RepoUpdaterAuthContext {
        source: RepoUpdaterCredentialSource::SshAgent,
        credential_id: "ssh-agent".to_string(), // ubs:ignore — public credential-source label, not a credential.
        issued_at_unix_ms: 1_700_000_000_000,
        expires_at_unix_ms: 1_700_000_060_000,
        granted_scopes: vec![],
        revoked: false,
        verified_hosts: vec![],
    };
    let reporter = HookReporter::new(OutputVisibility::None);

    auto_tune_repo_updater_contract(
        &mut contract,
        &repo_specs,
        Some(&auth_context),
        false,
        false,
        &reporter,
    );

    assert_eq!(contract.trust_policy.allowlisted_repo_specs, repo_specs);
    assert_eq!(
        contract.auth_policy.mode,
        RepoUpdaterAuthMode::InheritEnvironment
    );
}

#[test]
fn test_hydrate_repo_updater_auth_context_defaults_populates_required_fields() {
    let _guard = test_guard!();
    let contract = RepoUpdaterAdapterContract::default();
    let now_ms = 1_700_000_000_000_i64;
    let mut auth_context = RepoUpdaterAuthContext {
        source: RepoUpdaterCredentialSource::TokenEnv,
        credential_id: String::new(),
        issued_at_unix_ms: 0,
        expires_at_unix_ms: 0,
        granted_scopes: vec![],
        revoked: false,
        verified_hosts: vec![],
    };

    hydrate_repo_updater_auth_context_defaults(&mut auth_context, now_ms, &contract);

    assert_eq!(auth_context.credential_id, "token-env");
    assert!(auth_context.issued_at_unix_ms > 0);
    assert!(auth_context.issued_at_unix_ms <= now_ms);
    assert!(auth_context.expires_at_unix_ms > now_ms);
    assert_eq!(
        auth_context.granted_scopes,
        contract.auth_policy.required_scopes
    );
    assert_eq!(
        auth_context.verified_hosts.len(),
        contract.auth_policy.trusted_host_identities.len()
    );
}

#[test]
fn test_infer_repo_updater_auth_context_returns_none_without_local_auth() {
    let _guard = test_guard!();
    assert!(
        infer_repo_updater_auth_context_with_env_lookup(1_700_000_000_000, |_| false).is_none()
    );
}

#[test]
fn test_infer_repo_updater_auth_context_uses_token_env_when_present() {
    let _guard = test_guard!();
    let auth_context =
        infer_repo_updater_auth_context_with_env_lookup(1_700_000_000_000, |key| key == "GH_TOKEN") // ubs:ignore — compares an environment variable name, never its secret value.
            .expect("token env should infer auth context");
    assert_eq!(auth_context.source, RepoUpdaterCredentialSource::TokenEnv);
    assert_eq!(auth_context.credential_id, "env:GH_TOKEN");
    assert_eq!(auth_context.granted_scopes, vec!["repo:read".to_string()]);
}

#[test]
fn test_repo_updater_command_name_is_stable() {
    let _guard = test_guard!();
    assert_eq!(
        repo_updater_command_name(RepoUpdaterAdapterCommand::SyncApply),
        "sync-apply"
    );
    assert_eq!(
        repo_updater_command_name(RepoUpdaterAdapterCommand::SyncDryRun),
        "sync-dry-run"
    );
    assert_eq!(
        repo_updater_command_name(RepoUpdaterAdapterCommand::StatusNoFetch),
        "status-no-fetch"
    );
}

#[test]
fn test_build_repo_sync_idempotency_key_for_command_distinguishes_commands() {
    let _guard = test_guard!();
    let worker_id = WorkerId::new("worker-a");
    let sync_roots = vec![
        PathBuf::from("/data/projects/repo-a"),
        PathBuf::from("/data/projects/repo-b"),
    ];

    let apply_key = build_repo_sync_idempotency_key_for_command(
        &worker_id,
        &sync_roots,
        RepoUpdaterAdapterCommand::SyncApply,
    );
    let dry_run_key = build_repo_sync_idempotency_key_for_command(
        &worker_id,
        &sync_roots,
        RepoUpdaterAdapterCommand::SyncDryRun,
    );
    let status_key = build_repo_sync_idempotency_key_for_command(
        &worker_id,
        &sync_roots,
        RepoUpdaterAdapterCommand::StatusNoFetch,
    );

    assert_ne!(apply_key, dry_run_key);
    assert_ne!(dry_run_key, status_key);
    assert_ne!(apply_key, status_key);
    assert!(apply_key.starts_with("rch-repo-sync-"));
}

#[test]
fn test_build_remote_dependency_preflight_command_empty_roots() {
    let _guard = test_guard!();
    assert!(build_remote_dependency_preflight_command(&[]).is_none());
}

#[test]
fn test_build_remote_dependency_preflight_command_separates_checks() {
    let _guard = test_guard!();
    let checks = vec![
        DependencyPreflightCheck {
            root: "/data/projects/repo-a".to_string(),
            manifest: "/data/projects/repo-a/Cargo.toml".to_string(),
            required_path: "/data/projects/repo-a/Cargo.toml".to_string(),
            required_kind: "manifest",
            is_primary: true,
        },
        DependencyPreflightCheck {
            root: "/data/projects/repo-b".to_string(),
            manifest: "/data/projects/repo-b/Cargo.toml".to_string(),
            required_path: "/data/projects/repo-b/src/lib.rs".to_string(),
            required_kind: "source_entrypoint",
            is_primary: false,
        },
    ];

    let command =
        build_remote_dependency_preflight_command(&checks).expect("command should be constructed");

    assert!(
        command.contains("for required in "),
        "generated command must batch paths through one bounded shell loop"
    );
    assert!(
        !command.contains("fi if ["),
        "generated command must not concatenate checks without separator"
    );
    assert!(
        command.contains("RCH_DEP_PRESENT:"),
        "generated command must emit structured present marker"
    );
    assert!(
        command.contains("RCH_DEP_MISSING:"),
        "generated command must emit structured missing marker"
    );
}

#[test]
fn test_windows_offload_control_commands_use_stdin_script_transport() {
    let _guard = test_guard!();
    let script = "for required in 'C:/rch/app/Cargo.toml'; do test -f \"$required\"; done";

    let mut windows = make_test_worker_config("worker-windows-control-plane");
    windows.tags.push("os:windows".to_string());
    let (remote_arg, stdin_payload) = offload_remote_command_transport(&windows, script);
    assert_eq!(remote_arg, "sh -s");
    assert_eq!(stdin_payload, Some(script.as_bytes()));

    let posix = make_test_worker_config("worker-posix-control-plane");
    let (remote_arg, stdin_payload) = offload_remote_command_transport(&posix, script);
    assert_eq!(remote_arg, script);
    assert!(stdin_payload.is_none());
}

#[test]
fn test_build_remote_dependency_preflight_command_covers_large_workspaces() {
    let _guard = test_guard!();
    let checks = (0..2119)
        .map(|idx| DependencyPreflightCheck {
            root: "/data/projects/big".to_string(),
            manifest: "/data/projects/big/Cargo.toml".to_string(),
            required_path: format!("/data/projects/big/tests/case_{idx}.rs"),
            required_kind: "source_entrypoint",
            is_primary: true,
        })
        .collect::<Vec<_>>();

    let command = build_remote_dependency_preflight_command(&checks).unwrap();
    for check in &checks {
        assert!(command.contains(&check.required_path));
    }
}

#[test]
fn test_dependency_preflight_timeout_retains_total_probe_budget() {
    for (paths, seconds) in [(0, 20), (1, 20), (128, 20), (129, 40), (2119, 340)] {
        assert_eq!(
            dependency_preflight_timeout(paths),
            Duration::from_secs(seconds)
        );
    }
    assert!(dependency_preflight_timeout(usize::MAX) >= Duration::from_secs(340));
}

#[test]
fn test_synced_dependency_preflight_checks_use_remote_paths() {
    let _guard = test_guard!();
    let temp_dir = tempfile::tempdir().expect("temp dir");
    let package_root = temp_dir.path().join("package");
    std::fs::create_dir_all(package_root.join("src")).expect("create package src");
    std::fs::write(
        package_root.join("Cargo.toml"),
        r#"[package]
name = "package"
version = "0.1.0"
edition = "2024"
"#,
    )
    .expect("write manifest");
    std::fs::write(package_root.join("src/lib.rs"), "pub fn package() {}\n").expect("write lib");

    let root_outcomes = vec![
        (
            SyncClosurePlanEntry {
                local_root: package_root,
                remote_root: "/data/projects/frankenterm".to_string(),
                project_id: "frankenterm".to_string(),
                root_hash: "hash-primary".to_string(),
                is_primary: true,
                mode: SyncClosureMode::Full,
            },
            SyncRootOutcome::Synced,
        ),
        (
            SyncClosurePlanEntry {
                local_root: PathBuf::from("/Users/jemanuel/projects/frankentui"),
                remote_root: "/data/projects/frankentui".to_string(),
                project_id: "frankentui".to_string(),
                root_hash: "hash-dep".to_string(),
                is_primary: false,
                mode: SyncClosureMode::Full,
            },
            SyncRootOutcome::Failed {
                error: "no sync".to_string(),
            },
        ),
    ];

    let synced = synced_dependency_preflight_checks(&root_outcomes);
    let required_paths = synced
        .iter()
        .map(|check| check.required_path.as_str())
        .collect::<Vec<_>>();
    assert!(required_paths.contains(&"/data/projects/frankenterm/Cargo.toml"));
    assert!(required_paths.contains(&"/data/projects/frankenterm/src/lib.rs"));
    assert!(
        !required_paths
            .iter()
            .any(|path| path.starts_with("/data/projects/frankentui")),
        "failed roots must not be probed as freshly synced"
    );
}

#[test]
fn test_parse_dependency_preflight_probe_output_extracts_markers() {
    let _guard = test_guard!();
    let stdout = "\
RCH_DEP_PRESENT:/data/projects/a/Cargo.toml
noise
RCH_DEP_MISSING:/data/projects/b/Cargo.toml
RCH_DEP_PRESENT:/data/projects/c/Cargo.toml
";

    let (present, missing) = parse_dependency_preflight_probe_output(stdout);

    assert_eq!(present.len(), 2);
    assert_eq!(missing.len(), 1);
    assert!(present.contains("/data/projects/a/Cargo.toml"));
    assert!(present.contains("/data/projects/c/Cargo.toml"));
    assert!(missing.contains("/data/projects/b/Cargo.toml"));
}

#[test]
fn test_dependency_preflight_error_codes_match_public_catalog() {
    let _guard = test_guard!();
    assert_eq!(
        DEPENDENCY_PREFLIGHT_CODE_MISSING,
        ErrorCode::DependencyPreflightMissing.code_string().as_str()
    );
    assert_eq!(
        DEPENDENCY_PREFLIGHT_CODE_STALE,
        ErrorCode::DependencyPreflightStale.code_string().as_str()
    );
    assert_eq!(
        DEPENDENCY_PREFLIGHT_CODE_UNKNOWN,
        ErrorCode::DependencyPreflightUnknown.code_string().as_str()
    );
    assert_eq!(
        DEPENDENCY_PREFLIGHT_CODE_POLICY,
        ErrorCode::DependencyPreflightPolicyViolation
            .code_string()
            .as_str()
    );
    assert_eq!(
        DEPENDENCY_PREFLIGHT_CODE_TIMEOUT,
        ErrorCode::DependencyPreflightTimeout.code_string().as_str()
    );
    assert_ne!(
        DEPENDENCY_PREFLIGHT_CODE_MISSING,
        ErrorCode::CancelSlotLeak.code_string().as_str(),
        "dependency preflight must not reuse the cancellation slot-leak code"
    );
}

fn make_sync_entry(root: &str, is_primary: bool) -> SyncClosurePlanEntry {
    SyncClosurePlanEntry {
        local_root: PathBuf::from(root),
        remote_root: root.to_string(),
        project_id: format!("id-{}", root.replace('/', "_")),
        root_hash: format!("hash-{}", root.replace('/', "_")),
        is_primary,
        mode: SyncClosureMode::Full,
    }
}

fn make_test_worker_config(id: &str) -> WorkerConfig {
    WorkerConfig {
        id: WorkerId::new(id),
        host: "worker.host".to_string(),
        user: "ubuntu".to_string(),
        identity_file: "~/.ssh/id_ed25519".to_string(),
        total_slots: 8,
        priority: 100,
        tags: Vec::new(),
        tools: Vec::new(),
    }
}

fn make_fail_open_plan(
    fail_open_reason: Option<&str>,
    issues: Vec<rch_common::DependencyPlanIssue>,
) -> DependencyClosurePlan {
    DependencyClosurePlan {
        state: rch_common::DependencyClosurePlanState::FailOpen,
        entry_manifest_path: PathBuf::from("/data/projects/example/Cargo.toml"),
        workspace_root: Some(PathBuf::from("/data/projects/example")),
        canonical_roots: Vec::new(),
        sync_order: Vec::new(),
        fail_open: true,
        fail_open_reason: fail_open_reason.map(ToString::to_string),
        issues,
    }
}

#[test]
fn test_classify_dependency_runtime_fail_open_policy_violation() {
    let _guard = test_guard!();
    let plan = make_fail_open_plan(
        Some("resolver produced path policy violation"),
        vec![rch_common::DependencyPlanIssue {
            code: "path-policy-violation".to_string(),
            message: "dependency path escapes canonical root".to_string(),
            risk: rch_common::DependencyRiskClass::High,
            diagnostics: vec!["dependency_path=/tmp/off-policy".to_string()],
        }],
    );

    let decision = classify_dependency_runtime_fail_open(&plan);
    assert_eq!(decision.reason_code, DEPENDENCY_PREFLIGHT_CODE_POLICY);
    assert_eq!(
        decision.remediation,
        DEPENDENCY_PREFLIGHT_REMEDIATION_POLICY
    );
}

#[test]
fn test_classify_dependency_runtime_fail_open_materialization_failure() {
    let _guard = test_guard!();
    let plan = make_fail_open_plan(
        Some("materialization closure produced missing path dependency"),
        vec![rch_common::DependencyPlanIssue {
            code: "materialization-closure-unavailable".to_string(),
            message: "inactive optional path dependency is missing".to_string(),
            risk: rch_common::DependencyRiskClass::Critical,
            diagnostics: vec!["dependency_name=optional_dep".to_string()],
        }],
    );

    let decision = classify_dependency_runtime_fail_open(&plan);
    assert_eq!(
        decision.reason_code,
        DEPENDENCY_PREFLIGHT_CODE_MATERIALIZATION
    );
    assert_eq!(
        decision.remediation,
        DEPENDENCY_PREFLIGHT_REMEDIATION_MATERIALIZATION
    );
}

#[test]
fn test_classify_dependency_runtime_fail_open_timeout_signal() {
    let _guard = test_guard!();
    let plan = make_fail_open_plan(
        Some("cargo metadata timed out after 10s"),
        vec![rch_common::DependencyPlanIssue {
            code: "metadata-invocation-failure".to_string(),
            message: "metadata invocation timed out".to_string(),
            risk: rch_common::DependencyRiskClass::Critical,
            diagnostics: vec!["timeout=10s".to_string()],
        }],
    );

    let decision = classify_dependency_runtime_fail_open(&plan);
    assert_eq!(decision.reason_code, DEPENDENCY_PREFLIGHT_CODE_TIMEOUT);
    assert_eq!(
        decision.remediation,
        DEPENDENCY_PREFLIGHT_REMEDIATION_TIMEOUT
    );
}

#[test]
fn test_classify_dependency_runtime_fail_open_defaults_unknown() {
    let _guard = test_guard!();
    let plan = make_fail_open_plan(
        Some("resolver returned unverifiable graph ordering"),
        vec![rch_common::DependencyPlanIssue {
            code: "non-deterministic-order".to_string(),
            message: "graph order could not be proven".to_string(),
            risk: rch_common::DependencyRiskClass::Critical,
            diagnostics: vec!["planner_state=fail_open".to_string()],
        }],
    );

    let decision = classify_dependency_runtime_fail_open(&plan);
    assert_eq!(decision.reason_code, DEPENDENCY_PREFLIGHT_CODE_UNKNOWN);
    assert_eq!(
        decision.remediation,
        DEPENDENCY_PREFLIGHT_REMEDIATION_UNKNOWN
    );
}

#[test]
fn test_build_dependency_runtime_fail_open_report_uses_status_mapping() {
    let _guard = test_guard!();
    let worker = make_test_worker_config("worker-runtime-report");
    let project_root = PathBuf::from("/data/projects/runtime-policy");
    let decision = DependencyRuntimeFailOpenDecision {
        reason_code: DEPENDENCY_PREFLIGHT_CODE_POLICY,
        remediation: DEPENDENCY_PREFLIGHT_REMEDIATION_POLICY,
        detail: "policy violation detail".to_string(),
    };

    let report = build_dependency_runtime_fail_open_report(&worker, &project_root, &decision);
    assert!(!report.verified);
    assert_eq!(report.reason_code, Some(DEPENDENCY_PREFLIGHT_CODE_POLICY));
    assert_eq!(
        report.remediation,
        Some(DEPENDENCY_PREFLIGHT_REMEDIATION_POLICY)
    );
    assert_eq!(report.evidence.len(), 1);
    assert_eq!(
        report.evidence[0].status,
        DependencyPreflightStatus::PolicyViolation
    );
}

#[test]
fn test_build_dependency_runtime_fail_open_report_maps_materialization_failure() {
    let _guard = test_guard!();
    let worker = make_test_worker_config("worker-runtime-materialization");
    let project_root = PathBuf::from("/data/projects/runtime-materialization");
    let decision = DependencyRuntimeFailOpenDecision {
        reason_code: DEPENDENCY_PREFLIGHT_CODE_MATERIALIZATION,
        remediation: DEPENDENCY_PREFLIGHT_REMEDIATION_MATERIALIZATION,
        detail: "optional path root unavailable".to_string(),
    };

    let report = build_dependency_runtime_fail_open_report(&worker, &project_root, &decision);
    assert!(!report.verified);
    assert_eq!(
        report.reason_code,
        Some(DEPENDENCY_PREFLIGHT_CODE_MATERIALIZATION)
    );
    assert_eq!(
        report.evidence[0].status,
        DependencyPreflightStatus::MaterializationUnavailable
    );
}

#[test]
fn test_should_force_local_fallback_for_unsafe_runtime_fail_open() {
    let _guard = test_guard!();
    assert!(should_force_local_fallback_for_runtime_fail_open(
        DEPENDENCY_PREFLIGHT_CODE_POLICY
    ));
    assert!(should_force_local_fallback_for_runtime_fail_open(
        DEPENDENCY_PREFLIGHT_CODE_MATERIALIZATION
    ));
    assert!(!should_force_local_fallback_for_runtime_fail_open(
        DEPENDENCY_PREFLIGHT_CODE_UNKNOWN
    ));
    assert!(!should_force_local_fallback_for_runtime_fail_open(
        DEPENDENCY_PREFLIGHT_CODE_TIMEOUT
    ));
}

#[test]
fn test_e2e_dependency_preflight_verified_success_path() {
    let _guard = test_guard!();
    let worker = make_test_worker_config("worker-success");
    let entry = make_sync_entry("/data/projects/repo-success", true);
    let manifest = entry
        .local_root
        .join("Cargo.toml")
        .to_string_lossy()
        .to_string();
    let outcomes = vec![(entry, SyncRootOutcome::Synced)];
    let present = std::collections::BTreeSet::from([manifest]);
    let missing = std::collections::BTreeSet::new();

    let report = build_dependency_preflight_report(&worker, &outcomes, &present, &missing, None);

    assert!(report.verified, "all-present manifests should verify");
    assert!(report.reason_code.is_none());
    assert!(report.remediation.is_none());
    assert_eq!(report.evidence.len(), 1);
    assert_eq!(
        report.evidence[0].status,
        DependencyPreflightStatus::Present,
        "evidence must mark synced+present roots as present"
    );
}

#[test]
fn test_build_dependency_preflight_report_uses_remote_manifest_paths() {
    let _guard = test_guard!();
    let worker = make_test_worker_config("worker-remote-paths");
    let entry = SyncClosurePlanEntry {
        local_root: PathBuf::from("/Users/jemanuel/projects/repo-success"),
        remote_root: "/data/projects/repo-success".to_string(),
        project_id: "id-remote-paths".to_string(),
        root_hash: "hash-remote-paths".to_string(),
        is_primary: true,
        mode: SyncClosureMode::Full,
    };
    let outcomes = vec![(entry, SyncRootOutcome::Synced)];
    let present =
        std::collections::BTreeSet::from([String::from("/data/projects/repo-success/Cargo.toml")]);
    let missing = std::collections::BTreeSet::new();

    let report = build_dependency_preflight_report(&worker, &outcomes, &present, &missing, None);

    assert!(report.verified, "remote manifest markers should verify");
    assert_eq!(report.evidence.len(), 1);
    assert_eq!(
        report.evidence[0].root, "/data/projects/repo-success",
        "evidence should report the remote synced root"
    );
    assert_eq!(
        report.evidence[0].manifest, "/data/projects/repo-success/Cargo.toml",
        "manifest matching must use remote paths from the probe"
    );
    assert_eq!(
        report.evidence[0].status,
        DependencyPreflightStatus::Present
    );
}

#[test]
fn test_build_dependency_preflight_report_missing_stale_and_unknown_paths() {
    let _guard = test_guard!();
    let worker = make_test_worker_config("worker-mixed");
    // Use is_primary: true so the missing status triggers blocking.
    let synced_missing = make_sync_entry("/data/projects/repo-missing", true);
    let skipped_stale = make_sync_entry("/data/projects/repo-stale", false);
    let failed_unknown = make_sync_entry("/data/projects/repo-unknown", false);
    let missing_manifest = synced_missing
        .local_root
        .join("Cargo.toml")
        .to_string_lossy()
        .to_string();
    let outcomes = vec![
        (synced_missing, SyncRootOutcome::Synced),
        (
            skipped_stale,
            SyncRootOutcome::Skipped {
                reason: "transfer skipped by estimator".to_string(),
            },
        ),
        (
            failed_unknown,
            SyncRootOutcome::Failed {
                error: "rsync timeout".to_string(),
            },
        ),
    ];
    let present = std::collections::BTreeSet::new();
    let missing = std::collections::BTreeSet::from([missing_manifest]);

    let report = build_dependency_preflight_report(
        &worker,
        &outcomes,
        &present,
        &missing,
        Some("probe returned missing markers"),
    );

    assert!(
        !report.verified,
        "missing primary root evidence must block remote execution"
    );
    assert_eq!(
        report.reason_code,
        Some(DEPENDENCY_PREFLIGHT_CODE_MISSING),
        "missing primary should dominate failure reason"
    );
    assert_eq!(
        report.remediation,
        Some(DEPENDENCY_PREFLIGHT_REMEDIATION_MISSING)
    );
    assert!(
        report
            .evidence
            .iter()
            .any(|item| item.status == DependencyPreflightStatus::Missing)
    );
    assert!(
        report
            .evidence
            .iter()
            .any(|item| item.status == DependencyPreflightStatus::Stale)
    );
    assert!(
        report
            .evidence
            .iter()
            .any(|item| item.status == DependencyPreflightStatus::Unknown)
    );
}

#[test]
fn test_e2e_dependency_preflight_stale_fallback_path_maps_reason_code() {
    let _guard = test_guard!();
    let worker = make_test_worker_config("worker-stale");
    // Use is_primary: true so stale status triggers blocking.
    let stale_entry = make_sync_entry("/data/projects/repo-stale-only", true);
    let outcomes = vec![(
        stale_entry,
        SyncRootOutcome::Skipped {
            reason: "bandwidth guard skip".to_string(),
        },
    )];
    let present = std::collections::BTreeSet::new();
    let missing = std::collections::BTreeSet::new();

    let report = build_dependency_preflight_report(&worker, &outcomes, &present, &missing, None);

    assert!(!report.verified);
    assert_eq!(report.reason_code, Some(DEPENDENCY_PREFLIGHT_CODE_STALE));
    assert_eq!(
        report.remediation,
        Some(DEPENDENCY_PREFLIGHT_REMEDIATION_STALE)
    );
}

#[test]
fn test_e2e_dependency_preflight_missing_fallback_path_maps_reason_code() {
    let _guard = test_guard!();
    let worker = make_test_worker_config("worker-missing");
    // Use is_primary: true so missing status triggers blocking.
    let entry = make_sync_entry("/data/projects/repo-missing-only", true);
    let manifest = entry
        .local_root
        .join("Cargo.toml")
        .to_string_lossy()
        .to_string();
    let outcomes = vec![(entry, SyncRootOutcome::Synced)];
    let present = std::collections::BTreeSet::new();
    let missing = std::collections::BTreeSet::from([manifest]);

    let report = build_dependency_preflight_report(&worker, &outcomes, &present, &missing, None);

    assert!(!report.verified);
    assert_eq!(report.reason_code, Some(DEPENDENCY_PREFLIGHT_CODE_MISSING));
    assert_eq!(
        report.remediation,
        Some(DEPENDENCY_PREFLIGHT_REMEDIATION_MISSING)
    );
}

#[test]
fn test_cargo_package_source_entrypoints_include_auto_discovered_targets() {
    let _guard = test_guard!();
    let temp_dir = tempfile::tempdir().expect("temp dir");
    let package_root = temp_dir.path().join("auto-targets");
    for dir in [
        "src",
        "src/bin/nested",
        "examples/demo",
        "tests/integration",
        "benches/speed",
    ] {
        std::fs::create_dir_all(package_root.join(dir)).expect("create target dir");
    }
    std::fs::write(
        package_root.join("Cargo.toml"),
        r#"[package]
name = "auto-targets"
version = "0.1.0"
edition = "2024"
"#,
    )
    .expect("write manifest");
    for path in [
        "src/lib.rs",
        "src/main.rs",
        "src/bin/tool.rs",
        "src/bin/nested/main.rs",
        "examples/example.rs",
        "examples/demo/main.rs",
        "tests/integration.rs",
        "tests/integration/main.rs",
        "benches/speed.rs",
        "benches/speed/main.rs",
    ] {
        std::fs::write(package_root.join(path), "fn main() {}\n").expect("write entrypoint");
    }

    let entrypoints = cargo_package_source_entrypoints(&package_root);

    for path in [
        "src/lib.rs",
        "src/main.rs",
        "src/bin/tool.rs",
        "src/bin/nested/main.rs",
        "examples/example.rs",
        "examples/demo/main.rs",
        "tests/integration.rs",
        "tests/integration/main.rs",
        "benches/speed.rs",
        "benches/speed/main.rs",
    ] {
        assert!(
            entrypoints.contains(&PathBuf::from(path)),
            "missing auto-discovered entrypoint {path}"
        );
    }
}

#[test]
fn test_cargo_package_source_entrypoints_respect_auto_discovery_flags() {
    let _guard = test_guard!();
    let temp_dir = tempfile::tempdir().expect("temp dir");
    let package_root = temp_dir.path().join("manual-targets");
    for dir in ["src/bin", "examples", "tests", "benches", "custom"] {
        std::fs::create_dir_all(package_root.join(dir)).expect("create target dir");
    }
    std::fs::write(
        package_root.join("Cargo.toml"),
        r#"[package]
name = "manual-targets"
version = "0.1.0"
edition = "2024"
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false

[lib]
path = "custom/lib.rs"

[[bin]]
path = "custom/bin.rs"
"#,
    )
    .expect("write manifest");
    for path in [
        "src/lib.rs",
        "src/main.rs",
        "src/bin/tool.rs",
        "examples/example.rs",
        "tests/integration.rs",
        "benches/speed.rs",
        "custom/lib.rs",
        "custom/bin.rs",
    ] {
        std::fs::write(package_root.join(path), "fn main() {}\n").expect("write entrypoint");
    }

    let entrypoints = cargo_package_source_entrypoints(&package_root);

    assert_eq!(
        entrypoints,
        vec![
            PathBuf::from("custom/bin.rs"),
            PathBuf::from("custom/lib.rs")
        ]
    );
}

#[test]
fn test_workspace_member_source_entrypoints_include_all_targets_and_exclusions() {
    let _guard = test_guard!();
    let temp_dir = tempfile::tempdir().expect("temp dir");
    let workspace_root = temp_dir.path().join("workspace");

    for dir in [
        "crates/core/src",
        "crates/core/benches",
        "crates/core/examples",
        "crates/atlas-types/src",
        "crates/skipped/src",
        "tools/cli/src",
    ] {
        std::fs::create_dir_all(workspace_root.join(dir)).expect("create workspace dir");
    }
    std::fs::write(
        workspace_root.join("Cargo.toml"),
        r#"[workspace]
members = ["crates/*", "tools/cli"]
exclude = ["crates/skipped"]
"#,
    )
    .expect("write workspace manifest");
    for (manifest, name) in [
        ("crates/core/Cargo.toml", "core"),
        ("crates/atlas-types/Cargo.toml", "atlas-types"),
        ("crates/skipped/Cargo.toml", "skipped"),
        ("tools/cli/Cargo.toml", "cli"),
    ] {
        std::fs::write(
            workspace_root.join(manifest),
            format!(
                r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2024"
"#
            ),
        )
        .expect("write member manifest");
    }
    for path in [
        "crates/core/src/lib.rs",
        "crates/core/benches/interval_tree_bench.rs",
        "crates/core/examples/atlas_packing_attestation.rs",
        "crates/atlas-types/src/lib.rs",
        "crates/skipped/src/lib.rs",
        "tools/cli/src/lib.rs",
    ] {
        std::fs::write(workspace_root.join(path), "pub fn marker() {}\n")
            .expect("write member entrypoint");
    }

    let entrypoints = cargo_workspace_member_source_entrypoints(&workspace_root);

    for path in [
        "crates/core/Cargo.toml",
        "crates/core/src/lib.rs",
        "crates/core/benches/interval_tree_bench.rs",
        "crates/core/examples/atlas_packing_attestation.rs",
        "crates/atlas-types/Cargo.toml",
        "crates/atlas-types/src/lib.rs",
        "tools/cli/Cargo.toml",
        "tools/cli/src/lib.rs",
    ] {
        assert!(
            entrypoints.contains(&PathBuf::from(path)),
            "missing workspace member entrypoint {path}"
        );
    }
    assert!(
        !entrypoints
            .iter()
            .any(|path| path.starts_with("crates/skipped")),
        "workspace exclude entries must not be preflighted"
    );
}

#[test]
fn test_dependency_preflight_checks_expand_virtual_workspace_all_targets() {
    let _guard = test_guard!();
    let temp_dir = tempfile::tempdir().expect("temp dir");
    let workspace_root = temp_dir.path().join("frankenterm");

    for dir in [
        "crates/frankenterm-core/src",
        "crates/frankenterm-core/benches",
        "crates/frankenterm-core/examples",
        "crates/frankenterm-core-atlas-pack-types/src",
        "crates/frankenterm-core-connectors/src",
        "crates/skipped/src",
    ] {
        std::fs::create_dir_all(workspace_root.join(dir)).expect("create workspace dir");
    }
    std::fs::write(
        workspace_root.join("Cargo.toml"),
        r#"[workspace]
members = ["crates/frankenterm-core", "crates/frankenterm-core-*", "crates/skipped"]
exclude = ["crates/skipped"]
"#,
    )
    .expect("write workspace manifest");
    for (manifest, name) in [
        ("crates/frankenterm-core/Cargo.toml", "frankenterm-core"),
        (
            "crates/frankenterm-core-atlas-pack-types/Cargo.toml",
            "frankenterm-core-atlas-pack-types",
        ),
        (
            "crates/frankenterm-core-connectors/Cargo.toml",
            "frankenterm-core-connectors",
        ),
        ("crates/skipped/Cargo.toml", "skipped"),
    ] {
        std::fs::write(
            workspace_root.join(manifest),
            format!(
                r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2024"
"#
            ),
        )
        .expect("write member manifest");
    }
    for path in [
        "crates/frankenterm-core/src/lib.rs",
        "crates/frankenterm-core/benches/interval_tree_bench.rs",
        "crates/frankenterm-core/examples/atlas_packing_attestation.rs",
        "crates/frankenterm-core-atlas-pack-types/src/lib.rs",
        "crates/frankenterm-core-connectors/src/lib.rs",
        "crates/skipped/src/lib.rs",
    ] {
        std::fs::write(workspace_root.join(path), "pub fn marker() {}\n")
            .expect("write member entrypoint");
    }
    let entry = SyncClosurePlanEntry {
        local_root: workspace_root,
        remote_root: "/data/projects/frankenterm".to_string(),
        project_id: "frankenterm".to_string(),
        root_hash: "frankenterm-hash".to_string(),
        is_primary: true,
        mode: SyncClosureMode::Full,
    };

    let checks = dependency_preflight_checks_for_entry(&entry);
    let required_paths = checks
        .iter()
        .map(|check| check.required_path.as_str())
        .collect::<std::collections::BTreeSet<_>>();

    for path in [
        "/data/projects/frankenterm/Cargo.toml",
        "/data/projects/frankenterm/crates/frankenterm-core/Cargo.toml",
        "/data/projects/frankenterm/crates/frankenterm-core/src/lib.rs",
        "/data/projects/frankenterm/crates/frankenterm-core/benches/interval_tree_bench.rs",
        "/data/projects/frankenterm/crates/frankenterm-core/examples/atlas_packing_attestation.rs",
        "/data/projects/frankenterm/crates/frankenterm-core-atlas-pack-types/src/lib.rs",
        "/data/projects/frankenterm/crates/frankenterm-core-connectors/src/lib.rs",
    ] {
        assert!(
            required_paths.contains(path),
            "missing dependency preflight check for {path}"
        );
    }
    assert!(
        !required_paths
            .iter()
            .any(|path| path.contains("/crates/skipped/")),
        "workspace excluded members must not be preflighted"
    );
}

#[test]
fn test_dependency_preflight_blocks_missing_source_entrypoint() {
    let _guard = test_guard!();
    let worker = make_test_worker_config("worker-missing-source");
    let temp_dir = tempfile::tempdir().expect("temp dir");
    let package_root = temp_dir.path().join("member");
    std::fs::create_dir_all(package_root.join("src")).expect("create src");
    std::fs::write(
        package_root.join("Cargo.toml"),
        r#"[package]
name = "member"
version = "0.1.0"
edition = "2024"
"#,
    )
    .expect("write manifest");
    std::fs::write(package_root.join("src/lib.rs"), "pub fn member() {}\n").expect("write lib");
    let entry = SyncClosurePlanEntry {
        local_root: package_root,
        remote_root: "/data/projects/app/crates/member".to_string(),
        project_id: "member".to_string(),
        root_hash: "member-hash".to_string(),
        is_primary: false,
        mode: SyncClosureMode::Full,
    };
    let outcomes = vec![(entry, SyncRootOutcome::Synced)];
    let present = std::collections::BTreeSet::from([String::from(
        "/data/projects/app/crates/member/Cargo.toml",
    )]);
    let missing = std::collections::BTreeSet::from([String::from(
        "/data/projects/app/crates/member/src/lib.rs",
    )]);

    let report = build_dependency_preflight_report(&worker, &outcomes, &present, &missing, None);

    assert!(
        !report.verified,
        "a synced root with a missing package source entrypoint must not reach Cargo"
    );
    assert_eq!(report.reason_code, Some(DEPENDENCY_PREFLIGHT_CODE_MISSING));
    assert!(report.evidence.iter().any(|item| {
        item.required_kind == "source_entrypoint"
            && item.required_path == "/data/projects/app/crates/member/src/lib.rs"
            && item.status == DependencyPreflightStatus::Missing
    }));
    let failure = DependencyPreflightFailure::from_report(report);
    let summary = failure.evidence_summary();
    assert!(
        summary.contains("/data/projects/app/crates/member/src/lib.rs"),
        "summary should expose the missing path, got {summary}"
    );
    assert!(
        summary.contains("missing source_entrypoint"),
        "summary should expose the failure class and path kind, got {summary}"
    );
}

#[test]
fn test_dependency_preflight_probe_failure_compacts_unknown_source_entrypoints() {
    let _guard = test_guard!();
    let worker = make_test_worker_config("worker-probe-reset");
    let temp_dir = tempfile::tempdir().expect("temp dir");
    let package_root = temp_dir.path().join("large-member");
    std::fs::create_dir_all(package_root.join("src")).expect("create src");
    std::fs::create_dir_all(package_root.join("tests")).expect("create tests");
    std::fs::write(
        package_root.join("Cargo.toml"),
        r#"[package]
name = "large-member"
version = "0.1.0"
edition = "2024"
"#,
    )
    .expect("write manifest");
    std::fs::write(package_root.join("src/lib.rs"), "pub fn member() {}\n").expect("write lib");
    for idx in 0..150 {
        std::fs::write(
            package_root.join("tests").join(format!("case_{idx}.rs")),
            "#[test]\nfn case() {}\n",
        )
        .expect("write test entrypoint");
    }
    let entry = SyncClosurePlanEntry {
        local_root: package_root,
        remote_root: "/data/projects/app/crates/large-member".to_string(),
        project_id: "large-member".to_string(),
        root_hash: "large-member-hash".to_string(),
        is_primary: false,
        mode: SyncClosureMode::Full,
    };
    let outcomes = vec![(entry, SyncRootOutcome::Synced)];
    let present = std::collections::BTreeSet::new();
    let missing = std::collections::BTreeSet::new();

    let report = build_dependency_preflight_report(
        &worker,
        &outcomes,
        &present,
        &missing,
        Some("probe exited with status Some(255); connection reset"),
    );

    assert!(!report.verified);
    assert_eq!(report.reason_code, Some(DEPENDENCY_PREFLIGHT_CODE_UNKNOWN));
    let unknown_source_entrypoints = report
        .evidence
        .iter()
        .filter(|item| {
            item.status == DependencyPreflightStatus::Unknown
                && item.required_kind == "source_entrypoint"
        })
        .collect::<Vec<_>>();
    assert_eq!(
        unknown_source_entrypoints.len(),
        1,
        "transport failures should keep one sample per root/kind instead of duplicating every source entrypoint"
    );
    assert!(
        unknown_source_entrypoints[0]
            .detail
            .contains("additional unreported paths"),
        "unknown sample should explain why the report is compacted"
    );
    assert!(
        report.evidence.len() < 10,
        "large all-unknown reports should be compact, got {} evidence rows",
        report.evidence.len()
    );
}

#[tokio::test]
async fn test_verify_remote_dependency_manifests_blocks_stale_outcomes_deterministically() {
    let _guard = test_guard!();
    // Disable mock mode so verify_remote_dependency_manifests reaches
    // the preflight report logic instead of short-circuiting.
    mock::set_thread_mock_override(Some(false));
    let worker = make_test_worker_config("worker-stale-verify");
    // Use is_primary: true so stale status triggers blocking.
    let outcomes = vec![(
        make_sync_entry("/data/projects/repo-stale-verify", true),
        SyncRootOutcome::Skipped {
            reason: "transfer budget skip".to_string(),
        },
    )];
    let reporter = HookReporter::new(OutputVisibility::Verbose);

    let err = verify_remote_dependency_manifests(&worker, &outcomes, &reporter, None)
        .await
        .expect_err("stale dependency evidence should block remote execution");
    let preflight = err
        .downcast_ref::<DependencyPreflightFailure>()
        .expect("error should preserve DependencyPreflightFailure type");
    assert_eq!(preflight.reason_code, DEPENDENCY_PREFLIGHT_CODE_STALE);
    assert_eq!(
        preflight.remediation,
        format!(
            "{} To explicitly refresh this worker's RCH-managed source cache, run `rch sync --worker worker-stale-verify --force`, then rerun the Cargo command.",
            DEPENDENCY_PREFLIGHT_REMEDIATION_STALE
        )
    );
    mock::set_thread_mock_override(None);
}

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

    for (exact_dependency_closure_sync, source_content_receipt, expected_checksum) in [
        (false, false, false),
        (true, false, true),
        (false, true, true),
        (true, true, true),
    ] {
        let pipeline = TransferPipeline::new(
            PathBuf::from("/tmp/exact-closure-root"),
            "exact-closure-root".to_string(),
            "abc123".to_string(),
            TransferConfig::default(),
        );
        let configured = apply_source_sync_integrity_policy(
            pipeline,
            exact_dependency_closure_sync,
            source_content_receipt,
        );
        let (_, _, _, checksum_transfer) = configured.source_content_filter_policy();

        assert_eq!(
            checksum_transfer, expected_checksum,
            "exact Cargo closure and receipt syncs must compare source bytes"
        );
    }
}

#[test]
fn test_non_primary_missing_deps_block_preflight() {
    let _guard = test_guard!();
    let worker = make_test_worker_config("worker-non-primary");
    let primary = make_sync_entry("/data/projects/main-project", true);
    let dep = make_sync_entry("/data/projects/sibling-dep", false);
    let primary_manifest = primary
        .local_root
        .join("Cargo.toml")
        .to_string_lossy()
        .to_string();
    let dep_manifest = dep
        .local_root
        .join("Cargo.toml")
        .to_string_lossy()
        .to_string();

    let outcomes = vec![
        (primary, SyncRootOutcome::Synced),
        (dep, SyncRootOutcome::Synced),
    ];
    let present = std::collections::BTreeSet::from([primary_manifest]);
    let missing = std::collections::BTreeSet::from([dep_manifest]);

    let report = build_dependency_preflight_report(&worker, &outcomes, &present, &missing, None);

    assert!(
        !report.verified,
        "non-primary missing dep must block preflight to avoid stale sibling builds"
    );
    assert_eq!(report.reason_code, Some(DEPENDENCY_PREFLIGHT_CODE_MISSING));
}

#[test]
fn test_non_primary_stale_deps_block_preflight() {
    let _guard = test_guard!();
    let worker = make_test_worker_config("worker-non-primary-stale");
    let primary = make_sync_entry("/data/projects/main-project", true);
    let dep = make_sync_entry("/data/projects/sibling-dep-stale", false);
    let primary_manifest = primary
        .local_root
        .join("Cargo.toml")
        .to_string_lossy()
        .to_string();

    let outcomes = vec![
        (primary, SyncRootOutcome::Synced),
        (
            dep,
            SyncRootOutcome::Skipped {
                reason: "estimator skip".to_string(),
            },
        ),
    ];
    let present = std::collections::BTreeSet::from([primary_manifest]);
    let missing = std::collections::BTreeSet::new();

    let report = build_dependency_preflight_report(&worker, &outcomes, &present, &missing, None);

    assert!(
        !report.verified,
        "non-primary stale dep must block preflight to avoid stale sibling builds"
    );
    assert_eq!(report.reason_code, Some(DEPENDENCY_PREFLIGHT_CODE_STALE));
}

#[test]
fn test_build_sync_closure_plan_deterministic_under_permutation() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("project");
    let dep_a = temp_dir.path().join("dep_a");
    let dep_b = temp_dir.path().join("dep_b");
    std::fs::create_dir_all(&project_root).expect("create project root");
    std::fs::create_dir_all(&dep_a).expect("create dep_a");
    std::fs::create_dir_all(&dep_b).expect("create dep_b");

    let project_hash = "1234abcd";
    let plan_a = build_sync_closure_plan(
        &[dep_b.clone(), project_root.clone(), dep_a.clone()],
        &project_root,
        project_hash,
        &policy,
    );
    let plan_b = build_sync_closure_plan(
        &[dep_a.clone(), dep_b.clone(), project_root.clone()],
        &project_root,
        project_hash,
        &policy,
    );

    assert_eq!(plan_a, plan_b, "sync closure plan should be deterministic");
    assert!(
        plan_a
            .iter()
            .any(|entry| entry.is_primary && entry.root_hash == project_hash),
        "primary root must retain the closure hash"
    );
}

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

    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("project");
    let dep = temp_dir.path().join("dep");
    let dep_alias = temp_dir.path().join("dep_alias");
    std::fs::create_dir_all(&project_root).expect("create project root");
    std::fs::create_dir_all(&dep).expect("create dep root");
    symlink(&dep, &dep_alias).expect("create dep alias symlink");

    let dep_canonical = std::fs::canonicalize(&dep).expect("canonicalize dep");
    let plan = build_sync_closure_plan(
        &[dep_alias.clone(), dep.clone(), project_root.clone()],
        &project_root,
        "beefcafe",
        &policy,
    );

    let dep_entries = plan
        .iter()
        .filter(|entry| {
            std::fs::canonicalize(&entry.local_root)
                .map(|canonical| canonical == dep_canonical)
                .unwrap_or(false)
        })
        .count();
    assert_eq!(dep_entries, 1, "alias/canonical roots should deduplicate");
}

#[test]
fn test_build_sync_closure_plan_adds_workspace_metadata_for_member_roots() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("project");
    let dep_workspace_root = temp_dir.path().join("dep_workspace");
    let dep_member_root = dep_workspace_root.join("crates/member");

    std::fs::create_dir_all(&project_root).expect("create project root");
    std::fs::create_dir_all(&dep_member_root).expect("create member root");
    std::fs::write(
        dep_workspace_root.join("Cargo.toml"),
        r#"[workspace]
members = ["crates/member"]
"#,
    )
    .expect("write workspace manifest");
    std::fs::write(
        dep_member_root.join("Cargo.toml"),
        r#"[package]
name = "member"
version = "0.1.0"
edition = "2024"
"#,
    )
    .expect("write member manifest");

    let plan = build_sync_closure_plan(
        &[dep_member_root.clone(), project_root.clone()],
        &project_root,
        "workspace_hash",
        &policy,
    );

    assert!(
        plan.iter().any(|entry| entry.local_root == dep_member_root
            && entry.mode == SyncClosureMode::Full
            && !entry.is_primary),
        "workspace member root should remain a full sync root"
    );
    assert!(
        plan.iter()
            .any(|entry| entry.local_root == dep_workspace_root
                && entry.mode == SyncClosureMode::WorkspaceMetadata
                && !entry.is_primary),
        "workspace member roots should add a thin workspace metadata sync"
    );
    assert!(
        !plan
            .iter()
            .any(|entry| entry.local_root == dep_workspace_root
                && entry.mode == SyncClosureMode::Full),
        "workspace root should not become a full sync root unless it was explicitly requested"
    );
}

#[test]
fn test_build_sync_closure_plan_collapses_intra_workspace_members() {
    let _guard = test_guard!();
    // rch#33: building AT a workspace root, its members arrive as separate sync
    // roots physically inside the primary Full root. They are already covered by
    // the primary sync, so their redundant per-member Full entries must collapse
    // to a single planned root (restoring #8, without regressing the foreign-
    // workspace metadata path exercised by the sibling test above).
    let (temp_dir, policy) = topology_tempdir();
    let workspace_root = temp_dir.path().join("workspace");
    let alpha = workspace_root.join("crates/alpha");
    let beta = workspace_root.join("crates/beta");
    let gamma = workspace_root.join("crates/gamma");
    for dir in [&alpha, &beta, &gamma] {
        std::fs::create_dir_all(dir).expect("create member dir");
    }

    let plan = build_sync_closure_plan(
        &[
            workspace_root.clone(),
            alpha.clone(),
            beta.clone(),
            gamma.clone(),
        ],
        &workspace_root,
        "ws_hash",
        &policy,
    );

    assert_eq!(
        plan.len(),
        1,
        "intra-workspace members must collapse to the single workspace root, got {:?}",
        plan.iter()
            .map(|e| e.local_root.clone())
            .collect::<Vec<_>>()
    );
    let primary = &plan[0];
    assert!(primary.is_primary, "the sole root must be the primary");
    assert_eq!(primary.local_root, workspace_root);
    assert_eq!(primary.mode, SyncClosureMode::Full);
}

#[test]
fn test_build_dependency_runtime_plan_keeps_workspace_member_roots() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("project");
    let dep_workspace_root = temp_dir.path().join("dep_workspace");
    let dep_member_root = dep_workspace_root.join("crates/member");

    std::fs::create_dir_all(project_root.join("src")).expect("create project src");
    std::fs::create_dir_all(dep_member_root.join("src")).expect("create member src");
    std::fs::write(
        project_root.join("Cargo.toml"),
        r#"[package]
name = "project"
version = "0.1.0"
edition = "2024"

[dependencies]
member = { path = "../dep_workspace/crates/member" }
"#,
    )
    .expect("write project manifest");
    std::fs::write(project_root.join("src/lib.rs"), "pub fn project() {}\n")
        .expect("write project lib");
    std::fs::write(
        dep_workspace_root.join("Cargo.toml"),
        r#"[workspace]
members = ["crates/member"]
"#,
    )
    .expect("write workspace manifest");
    std::fs::write(
        dep_member_root.join("Cargo.toml"),
        r#"[package]
name = "member"
version = "0.1.0"
edition = "2024"
"#,
    )
    .expect("write member manifest");
    std::fs::write(dep_member_root.join("src/lib.rs"), "pub fn member() {}\n")
        .expect("write member lib");

    let project_root = std::fs::canonicalize(&project_root).expect("canonicalize project");
    let dep_workspace_root =
        std::fs::canonicalize(&dep_workspace_root).expect("canonicalize workspace");
    let dep_member_root = std::fs::canonicalize(&dep_member_root).expect("canonicalize member");
    let reporter = HookReporter::new(OutputVisibility::None);

    let plan = build_dependency_runtime_plan(
        &project_root,
        Some(CompilationKind::CargoCheck),
        &reporter,
        &policy,
    );

    assert!(
        plan.fail_open_decision.is_none(),
        "dependency runtime planning should stay on the ready path"
    );
    assert!(
        plan.sync_roots.contains(&dep_member_root),
        "workspace member root must stay in the runtime sync roots"
    );
    assert!(
        !plan.sync_roots.contains(&dep_workspace_root),
        "workspace root should be added later as metadata-only sync, not full runtime root"
    );
    assert!(
        plan.sync_roots.contains(&project_root),
        "primary project root must remain in the sync roots"
    );
}

#[tokio::test]
#[serial(mock_global)]
async fn registered_preflight_rejection_sends_heartbeat_and_stops_guard() {
    let _lock = test_lock().lock().await;
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let retained = temp_dir._dir.keep();
    let socket = retained.join("heartbeat.sock");
    let listener = UnixListener::bind(&socket).expect("bind heartbeat receiver");
    let socket_path = socket.to_string_lossy().into_owned();
    let (received_tx, mut received_rx) = tokio::sync::mpsc::unbounded_channel();
    let receiver = tokio::spawn(async move {
        loop {
            let (stream, _) = listener.accept().await.expect("accept heartbeat");
            let (reader, mut writer) = stream.into_split();
            let mut reader = TokioBufReader::new(reader);
            let mut request = String::new();
            if reader.read_line(&mut request).await.expect("read route") == 0 {
                // Dropping the guard can cancel its background send after
                // connect but before writing. EOF is not a heartbeat.
                continue;
            }
            assert_eq!(request, "POST /build-heartbeat\n");
            let mut body = String::new();
            if reader.read_line(&mut body).await.expect("read heartbeat") == 0 {
                continue;
            }
            let heartbeat: BuildHeartbeatRequest = serde_json::from_str(&body).unwrap();
            let response = serde_json::json!({
                "status": "ok",
                "build_id": heartbeat.build_id,
                "worker_id": heartbeat.worker_id,
                "phase": match heartbeat.phase {
                    BuildHeartbeatPhase::SyncUp => "sync_up",
                    BuildHeartbeatPhase::Execute => "execute",
                    BuildHeartbeatPhase::SyncDown => "sync_down",
                    BuildHeartbeatPhase::Finalize => "finalize",
                },
            });
            let response =
                format!("HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n{response}\n");
            received_tx.send(heartbeat).expect("retain heartbeat");
            if let Err(error) = writer.write_all(response.as_bytes()).await {
                // Guard drop may close the peer after its complete request.
                assert!(
                    matches!(
                        error.kind(),
                        std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset
                    ),
                    "unexpected heartbeat acknowledgement error: {error}"
                );
            }
        }
    });
    let worker = SelectedWorker {
        id: WorkerId::new("preflight-worker"),
        host: "unused.invalid".to_string(),
        user: "unused".to_string(),
        identity_file: "unused".to_string(),
        slots_available: 1,
        speed_score: 1.0,
        declared_os: Some("windows".to_string()),
    };
    let reporter = HookReporter::new(OutputVisibility::None);
    let result = Box::pin(execute_remote_compilation(
        &worker,
        "cargo check",
        TransferConfig::default(),
        Vec::new(),
        None,
        &rch_common::CompilationConfig::default(),
        None,
        Some(CompilationKind::CargoCheck),
        &reporter,
        &socket_path,
        ColorMode::Auto,
        Some(71),
        Some("preflight-wrapper"),
        None,
        &policy,
        None,
        true,
        &[],
        &[],
        rch_common::remediation_config::DEFAULT_POOLED_REAPER_POOLED_IDLE_HOURS,
        None,
    ))
    .await;
    assert!(result.unwrap_err().to_string().contains("require the Unix"));
    let heartbeat = received_rx.try_recv().expect("heartbeat before rejection");
    assert_eq!(heartbeat.build_id, 71);
    assert_eq!(heartbeat.worker_id, worker.id);
    assert_eq!(heartbeat.hook_pid, Some(std::process::id()));
    assert_eq!(
        heartbeat.local_wrapper_id.as_deref(),
        Some("preflight-wrapper")
    );
    assert_eq!(heartbeat.phase, BuildHeartbeatPhase::SyncUp);
    assert_eq!(heartbeat.detail.as_deref(), Some("source_validation"));
    assert!(heartbeat.remote_pgid_file.is_none());
    // An immediate interval tick can race the explicit flush. Drain it before
    // waiting past the production interval: an early error must stop the loop.
    tokio::task::yield_now().await;
    while received_rx.try_recv().is_ok() {}
    assert!(
        tokio::time::timeout(Duration::from_secs(6), received_rx.recv())
            .await
            .is_err()
    );

    // While preflight is still working, periodic liveness must not invent
    // forward progress. Exercise the same guard over a real daemon socket.
    let heartbeat_loop = BuildHeartbeatLoop::start(
        &socket_path,
        72,
        &worker.id,
        Some("preflight-wrapper"),
        None,
    );
    heartbeat_loop.update_phase(
        BuildHeartbeatPhase::SyncUp,
        Some("source_validation".to_string()),
    );
    let first = tokio::time::timeout(Duration::from_secs(6), received_rx.recv())
        .await
        .expect("initial interval heartbeat")
        .unwrap();
    let next = tokio::time::timeout(Duration::from_secs(6), received_rx.recv())
        .await
        .expect("periodic preflight heartbeat")
        .unwrap();
    assert_eq!(first.build_id, 72);
    assert_eq!(next.build_id, first.build_id);
    assert_eq!(next.progress_counter, first.progress_counter);
    assert_eq!(next.detail.as_deref(), Some("source_validation"));
    assert!(next.remote_pgid_file.is_none());
    drop(heartbeat_loop);
    receiver.abort();
    assert!(receiver.await.unwrap_err().is_cancelled());
}

#[tokio::test]
#[serial(mock_global)]
async fn test_execute_remote_compilation_syncs_custom_cargo_target_dir_artifacts() {
    let _lock = test_lock().lock().await;
    let _guard = test_guard!();

    let socket_path = format!(
        "/tmp/rch_test_custom_target_artifacts_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("clock should be after epoch")
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );
    mock::clear_global_invocations();

    // `execute_remote_compilation` reads the current project root from
    // `std::env::current_dir()` and normalizes it through the supplied
    // topology policy. Pin the cwd to a tempdir and build a policy that
    // recognises it so the test runs anywhere (including CI runners with
    // no `/data/projects`).
    let (temp_dir, policy) = topology_tempdir();
    let project_dir = temp_dir.path().join("remote_compilation_helper");
    std::fs::create_dir_all(&project_dir).expect("create project dir");
    let custom_target_dir_path = project_dir.join(".rch-test-target-cache");
    let custom_target_dir = custom_target_dir_path.to_string_lossy().to_string();

    let prev_cwd = std::env::current_dir().ok();
    std::env::set_current_dir(&project_dir).expect("cd into project dir");

    let worker = SelectedWorker {
        id: rch_common::WorkerId::new("mock-worker"),
        host: "mock.host.local".to_string(),
        user: "mockuser".to_string(),
        identity_file: "~/.ssh/mock_key".to_string(),
        slots_available: 8,
        speed_score: 90.0,
        declared_os: None,
    };

    let reporter = HookReporter::new(OutputVisibility::None);
    let result = Box::pin(execute_remote_compilation(
        &worker,
        "cargo build",
        TransferConfig::default(),
        Vec::new(),
        Some(PathBuf::from(&custom_target_dir)),
        &rch_common::CompilationConfig::default(),
        None,
        Some(CompilationKind::CargoBuild),
        &reporter,
        &socket_path,
        ColorMode::Auto,
        None,
        None,
        None,
        &policy,
        None,
        false,
        &[],
        &[],
        rch_common::remediation_config::DEFAULT_POOLED_REAPER_POOLED_IDLE_HOURS,
        None,
    ))
    .await;

    // Restore cwd before any assertion so a failure doesn't poison other tests.
    if let Some(prev) = prev_cwd {
        let _ = std::env::set_current_dir(prev);
    }

    let execution = result.expect("remote execution should succeed in mock mode");
    assert_eq!(execution.exit_code, 0);

    let rsync_logs = mock::global_rsync_invocations_snapshot();
    let custom_target_artifact_sync = rsync_logs
        .iter()
        .find(|entry| {
            entry.phase == mock::Phase::Artifacts
                && entry.destination == custom_target_dir
                && entry.source.contains(".rch-target")
        })
        .expect(
            "expected artifact retrieval into custom CARGO_TARGET_DIR from worker .rch-target path",
        );
    assert!(
        custom_target_artifact_sync
            .source
            .contains(".rch-target-mock-worker-"),
        "expected per-job remote target dir, got {}",
        custom_target_artifact_sync.source
    );
    assert!(
        !custom_target_artifact_sync.source.contains("/.rch-target/"),
        "custom target sync must not use the shared .rch-target dir: {}",
        custom_target_artifact_sync.source
    );

    let ssh_logs = mock::global_ssh_invocations_snapshot();
    let execute_command = ssh_logs
        .iter()
        .find(|entry| entry.phase == mock::Phase::Execute)
        .and_then(|entry| entry.command.as_deref())
        .expect("execute command should be recorded");
    assert!(
        execute_command.contains("CARGO_TARGET_DIR=")
            && execute_command.contains(".rch-target-mock-worker-"),
        "expected remote Cargo execution to force per-job worker CARGO_TARGET_DIR, got {execute_command}"
    );
}

#[tokio::test]
#[serial(mock_global)]
async fn test_terminal_source_sync_failure_never_launches_remote_cargo() {
    let _lock = test_lock().lock().await;
    let _guard = test_guard!();
    let socket_path = format!(
        "/tmp/rch_test_pre_cargo_sync_failure_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("clock should be after epoch")
            .as_nanos()
    );
    let rsync_config = MockRsyncConfig {
        fail_sync_attempts: 3,
        ..MockRsyncConfig::success()
    };
    let _overrides = TestOverridesGuard::set(&socket_path, MockConfig::default(), rsync_config);
    mock::clear_global_invocations();

    let (temp_dir, policy) = topology_tempdir();
    let project_dir = temp_dir.path().join("remote_compilation_helper");
    std::fs::create_dir_all(&project_dir).expect("create project dir");
    let prev_cwd = std::env::current_dir().ok();
    std::env::set_current_dir(&project_dir).expect("cd into project dir");
    let worker = SelectedWorker {
        id: rch_common::WorkerId::new("mock-worker"),
        host: "mock.host.local".to_string(),
        user: "mockuser".to_string(),
        identity_file: "~/.ssh/mock_key".to_string(),
        slots_available: 8,
        speed_score: 90.0,
        declared_os: None,
    };
    let transfer_config = TransferConfig {
        sync_timeout_ms: Some(1_000),
        retry: rch_common::RetryConfig {
            max_attempts: 3,
            base_delay_ms: 0,
            max_delay_ms: 0,
            jitter_factor: 0.0,
            total_timeout_ms: 1,
        },
        ..TransferConfig::default()
    };
    let reporter = HookReporter::new(OutputVisibility::Summary);

    let result = Box::pin(execute_remote_compilation(
        &worker,
        "cargo check",
        transfer_config,
        Vec::new(),
        None,
        &rch_common::CompilationConfig::default(),
        None,
        Some(CompilationKind::CargoCheck),
        &reporter,
        &socket_path,
        ColorMode::Auto,
        None,
        None,
        None,
        &policy,
        None,
        false,
        &[],
        &[],
        rch_common::remediation_config::DEFAULT_POOLED_REAPER_POOLED_IDLE_HOURS,
        None,
    ))
    .await;

    if let Some(prev) = prev_cwd {
        let _ = std::env::set_current_dir(prev);
    }

    let error = result.expect_err("source sync exhaustion must stop before Cargo");
    let history = error
        .downcast_ref::<crate::transfer::TransferAttemptsExhausted>()
        .expect("typed source-transfer history");
    assert_eq!(history.attempts.len(), 3);
    assert_eq!(
        mock::global_rsync_invocations_snapshot()
            .iter()
            .filter(|entry| entry.phase == mock::Phase::Sync)
            .count(),
        3
    );
    assert_eq!(
        mock::global_ssh_invocations_snapshot()
            .iter()
            .filter(|entry| entry.phase == mock::Phase::Execute)
            .count(),
        0,
        "terminal source-transfer failure must launch remote Cargo exactly zero times"
    );
    assert_eq!(
        source_sync_terminal_summary(&history.attempts, false).as_deref(),
        Some(
            "[RCH] source sync failed before remote Cargo execution after 3/3 attempts; remote Cargo was not started: Mock: Sync failed (transient) - Connection timed out"
        )
    );
}

/// Issue #19 Fix 1: a SUCCESSFUL remote compile whose artifacts fail to sync
/// back must NOT report exit 0 for an artifact-producing kind — the local
/// build is incomplete, so the hook returns a non-zero, build-failure-class
/// code. (A test/diagnostic kind, which streams its output and needs no local
/// artifact, still returns the remote exit code on the same failure.)
#[tokio::test]
#[serial(mock_global)]
async fn test_artifact_sync_failure_fails_an_artifact_producing_build() {
    let _lock = test_lock().lock().await;
    let _guard = test_guard!();

    let socket_path = format!(
        "/tmp/rch_test_artifact_fail_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("clock should be after epoch")
            .as_nanos()
    );

    // Mock SSH succeeds (remote compile exit 0) but rsync artifact retrieval
    // ALWAYS fails — exactly the silent-footgun scenario.
    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::artifact_failure(),
    );
    mock::clear_global_invocations();

    let (temp_dir, policy) = topology_tempdir();
    let project_dir = temp_dir.path().join("remote_compilation_helper");
    std::fs::create_dir_all(&project_dir).expect("create project dir");

    let prev_cwd = std::env::current_dir().ok();
    std::env::set_current_dir(&project_dir).expect("cd into project dir");

    let worker = SelectedWorker {
        id: rch_common::WorkerId::new("mock-worker"),
        host: "mock.host.local".to_string(),
        user: "mockuser".to_string(),
        identity_file: "~/.ssh/mock_key".to_string(),
        slots_available: 8,
        speed_score: 90.0,
        declared_os: None,
    };
    let reporter = HookReporter::new(OutputVisibility::None);

    // Artifact-producing kind (cargo build): a failed sync-back is FATAL.
    // Keep both large awaited compilation futures out of this test's state
    // machine; qualification must still run with the default test-thread stack.
    let build = Box::pin(execute_remote_compilation(
        &worker,
        "cargo build",
        TransferConfig::default(),
        Vec::new(),
        None,
        &rch_common::CompilationConfig::default(),
        None,
        Some(CompilationKind::CargoBuild),
        &reporter,
        &socket_path,
        ColorMode::Auto,
        None,
        None,
        None,
        &policy,
        None,
        false,
        &[],
        &[],
        rch_common::remediation_config::DEFAULT_POOLED_REAPER_POOLED_IDLE_HOURS,
        None,
    ))
    .await;

    // Test kind (cargo test): output streamed, no required artifact — the
    // remote exit code (0) is preserved despite the same artifact failure.
    mock::clear_global_invocations();
    let test_run = Box::pin(execute_remote_compilation(
        &worker,
        "cargo test",
        TransferConfig::default(),
        Vec::new(),
        None,
        &rch_common::CompilationConfig::default(),
        None,
        Some(CompilationKind::CargoTest),
        &reporter,
        &socket_path,
        ColorMode::Auto,
        None,
        None,
        None,
        &policy,
        None,
        false,
        &[],
        &[],
        rch_common::remediation_config::DEFAULT_POOLED_REAPER_POOLED_IDLE_HOURS,
        None,
    ))
    .await;

    if let Some(prev) = prev_cwd {
        let _ = std::env::set_current_dir(prev);
    }

    let build = build.expect("remote execution should return Ok in mock mode");
    assert_ne!(
        build.exit_code, 0,
        "a successful compile with a failed artifact sync-back must NOT exit 0"
    );
    assert_eq!(
        build.exit_code, EXIT_ARTIFACT_TRANSFER_FAILED,
        "artifact-transfer failure must surface the build-failure-class exit code"
    );

    let test_run = test_run.expect("remote execution should return Ok in mock mode");
    assert_eq!(
        test_run.exit_code, 0,
        "cargo test streams its output; a missing artifact must not fail it"
    );
}

#[tokio::test]
#[serial(mock_global)]
async fn test_cargo_test_delegates_to_rch_exec() {
    // Test that cargo test commands are delegated to rch exec
    let _lock = test_lock().lock().await;
    let _guard = test_guard!();
    mock::clear_global_invocations();
    crate::config::set_test_config_override(Some(rch_common::RchConfig::default()));

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo test".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    crate::config::set_test_config_override(None);

    // Hook should delegate to rch exec
    assert!(
        output.is_allow(),
        "cargo test should be allowed via delegation"
    );
    let cmd = delegated_command(&output);
    assert_eq!(cmd, "rch exec -- cargo test");

    // No rsync/SSH during hook - that happens in run_exec
    let rsync_logs = mock::global_rsync_invocations_snapshot();
    let ssh_logs = mock::global_ssh_invocations_snapshot();
    assert!(rsync_logs.is_empty(), "Hook should not invoke rsync");
    assert!(ssh_logs.is_empty(), "Hook should not invoke SSH");
}

#[tokio::test]
#[serial(mock_global)]
async fn test_compound_chain_delegates_every_compilation_segment() {
    // Issue #50: `cargo build --release && cargo test` must offload BOTH
    // builds, not only the final segment.
    let _lock = test_lock().lock().await;
    let _guard = test_guard!();
    mock::clear_global_invocations();
    crate::config::set_test_config_override(Some(rch_common::RchConfig::default()));

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build --release && cargo test".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    crate::config::set_test_config_override(None);

    assert!(output.is_allow());
    let cmd = delegated_command(&output);
    assert_eq!(
        cmd,
        "rch exec -- cargo build --release && rch exec -- cargo test"
    );
}

#[tokio::test]
#[serial(mock_global)]
async fn test_hook_leaves_non_allowlisted_tool_local() {
    // Issue #51: a persisted allowlist that predates Go support keeps `go test`
    // local. The hook must not rewrite it (the reason line goes to stderr).
    let _lock = test_lock().lock().await;
    let _guard = test_guard!();
    mock::clear_global_invocations();
    let mut config = rch_common::RchConfig::default();
    config.execution.allowlist = vec!["cargo".to_string()];
    assert_eq!(
        config.execution.missing_builtin_bases().first().copied(),
        Some("rustc"),
        "the allowlist gap must be discoverable from config"
    );
    assert!(config.execution.missing_builtin_bases().contains(&"go"));
    crate::config::set_test_config_override(Some(config));

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "go test ./...".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    crate::config::set_test_config_override(None);

    assert!(output.is_allow());
    assert!(
        !matches!(output, HookOutput::AllowWithModifiedCommand(_)),
        "non-allowlisted command must be allowed unchanged, got {output:?}"
    );
}

#[test]
fn config_local_policy_matches_hook_semantics() {
    // Issue #55: one policy for the hook, `rch exec` and the cargo shim.
    let _guard = test_guard!();
    let mut config = rch_common::RchConfig::default();
    assert_eq!(
        config_local_policy(&config, Some(CompilationKind::CargoBuild)),
        None
    );
    assert_eq!(config_local_policy(&config, None), None);

    config.general.force_local = true;
    assert_eq!(
        config_local_policy(&config, Some(CompilationKind::CargoBuild)),
        Some(ConfigLocalPolicy::ForceLocal)
    );
    // Jobs honor force_local too.
    assert_eq!(
        config_local_policy(&config, Some(CompilationKind::Job)),
        Some(ConfigLocalPolicy::ForceLocal)
    );
    config.general.force_remote = true;
    assert_eq!(
        config_local_policy(&config, Some(CompilationKind::CargoBuild)),
        Some(ConfigLocalPolicy::ConflictingForceFlags)
    );
    config.general.force_local = false;
    config.general.force_remote = false;

    config.general.enabled = false;
    assert_eq!(
        config_local_policy(&config, Some(CompilationKind::CargoBuild)),
        Some(ConfigLocalPolicy::Disabled)
    );
    config.general.enabled = true;

    config.execution.allowlist = vec!["cargo".to_string()];
    assert_eq!(
        config_local_policy(&config, Some(CompilationKind::GoTest)),
        Some(ConfigLocalPolicy::NotAllowlisted("go"))
    );
    assert_eq!(
        config_local_policy(&config, Some(CompilationKind::CargoTest)),
        None
    );
    // Explicit job admission has no allowlist entry and is not gated by it.
    assert_eq!(
        config_local_policy(&config, Some(CompilationKind::Job)),
        None
    );

    // Explicit config outranks a baked RCH_REQUIRE_REMOTE; the allowlist gate
    // does not (under strict remote it refuses instead of running locally).
    assert!(ConfigLocalPolicy::ForceLocal.overrides_require_remote());
    assert!(ConfigLocalPolicy::Disabled.overrides_require_remote());
    assert!(ConfigLocalPolicy::ConflictingForceFlags.overrides_require_remote());
    assert!(!ConfigLocalPolicy::NotAllowlisted("go").overrides_require_remote());

    // Policy refusals are permanent for the invocation, never retryable.
    for policy in [
        ConfigLocalPolicy::ForceLocal,
        ConfigLocalPolicy::Disabled,
        ConfigLocalPolicy::ConflictingForceFlags,
        ConfigLocalPolicy::NotAllowlisted("go"),
    ] {
        assert!(
            !remote_required_refusal_is_retryable(&policy.reason()),
            "{policy:?} must not be retryable"
        );
    }
    assert!(remote_required_refusal_is_retryable("no workers available"));
    assert_eq!(
        ConfigLocalPolicy::NotAllowlisted("nix").reason(),
        "command 'nix' not in execution.allowlist"
    );
}

#[tokio::test]
#[serial(mock_global)]
async fn test_cargo_test_with_args_delegates_correctly() {
    // Test that cargo test with arguments is delegated correctly
    let _lock = test_lock().lock().await;
    let _guard = test_guard!();
    mock::clear_global_invocations();
    crate::config::set_test_config_override(Some(rch_common::RchConfig::default()));

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo test --release -- --nocapture".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    crate::config::set_test_config_override(None);

    // Hook should delegate with all arguments preserved
    assert!(output.is_allow());
    let cmd = delegated_command(&output);
    assert_eq!(cmd, "rch exec -- cargo test --release -- --nocapture");

    // No rsync/SSH during hook
    let rsync_logs = mock::global_rsync_invocations_snapshot();
    let ssh_logs = mock::global_ssh_invocations_snapshot();
    assert!(rsync_logs.is_empty(), "Hook should not invoke rsync");
    assert!(ssh_logs.is_empty(), "Hook should not invoke SSH");
}

#[tokio::test]
#[serial(mock_global)]
async fn test_cargo_test_remote_build_failure() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_cargo_test_build_fail_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    // Configure mock for build failure (exit 1)
    let _overrides = TestOverridesGuard::set(
            &socket_path,
            MockConfig {
                default_exit_code: 1,
                default_stderr: "error[E0425]: cannot find value `undefined_var` in this scope\n  --> src/lib.rs:10:5\n".to_string(),
                ..MockConfig::default()
            },
            MockRsyncConfig::success(),
        );
    mock::clear_global_invocations();

    let response = SelectionResponse {
        worker: Some(SelectedWorker {
            id: rch_common::WorkerId::new("test-worker"),
            host: "test.host.local".to_string(),
            user: "testuser".to_string(),
            identity_file: "~/.ssh/test_key".to_string(),
            slots_available: 8,
            speed_score: 85.0,
            declared_os: None,
        }),
        reason: SelectionReason::Success,
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo test".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Build failure (exit 1) should use transparent interception with exit code
    // Agent sees the error output and gets correct exit code
    assert!(
        output.is_allow(),
        "cargo test build failure should use transparent interception"
    );
    assert!(
        matches!(output, HookOutput::AllowWithModifiedCommand(_)),
        "cargo test build failure should return AllowWithModifiedCommand"
    );
}

#[tokio::test]
#[serial(mock_global)]
async fn test_cargo_test_with_filter() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_cargo_test_filter_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );
    mock::clear_global_invocations();

    let response = SelectionResponse {
        worker: Some(SelectedWorker {
            id: rch_common::WorkerId::new("test-worker"),
            host: "test.host.local".to_string(),
            user: "testuser".to_string(),
            identity_file: "~/.ssh/test_key".to_string(),
            slots_available: 8,
            speed_score: 85.0,
            declared_os: None,
        }),
        reason: SelectionReason::Success,
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    // Test with filter pattern
    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo test specific_test".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Filtered test command should use transparent interception
    assert!(
        output.is_allow(),
        "Filtered cargo test should use transparent interception"
    );
    assert!(
        matches!(output, HookOutput::AllowWithModifiedCommand(_)),
        "Filtered cargo test should return AllowWithModifiedCommand"
    );
}

#[tokio::test]
#[serial(mock_global)]
async fn test_cargo_test_with_test_threads() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_cargo_test_threads_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );
    mock::clear_global_invocations();

    let response = SelectionResponse {
        worker: Some(SelectedWorker {
            id: rch_common::WorkerId::new("test-worker"),
            host: "test.host.local".to_string(),
            user: "testuser".to_string(),
            identity_file: "~/.ssh/test_key".to_string(),
            slots_available: 8,
            speed_score: 85.0,
            declared_os: None,
        }),
        reason: SelectionReason::Success,
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    // Test with --test-threads flag (should parse correctly for slot estimation)
    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo test -- --test-threads=4".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Should use transparent interception regardless of thread count
    assert!(
        output.is_allow(),
        "cargo test with --test-threads should use transparent interception"
    );
    assert!(
        matches!(output, HookOutput::AllowWithModifiedCommand(_)),
        "cargo test with --test-threads should return AllowWithModifiedCommand"
    );
}

#[tokio::test]
#[serial(mock_global)]
async fn test_cargo_test_signal_killed() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_cargo_test_signal_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    // Configure mock for OOM kill (exit 137 = 128 + 9 = SIGKILL)
    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig {
            default_exit_code: 137,
            default_stderr: "Killed\n".to_string(),
            ..MockConfig::default()
        },
        MockRsyncConfig::success(),
    );
    mock::clear_global_invocations();

    let response = SelectionResponse {
        worker: Some(SelectedWorker {
            id: rch_common::WorkerId::new("test-worker"),
            host: "test.host.local".to_string(),
            user: "testuser".to_string(),
            identity_file: "~/.ssh/test_key".to_string(),
            slots_available: 8,
            speed_score: 85.0,
            declared_os: None,
        }),
        reason: SelectionReason::Success,
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo test".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Signal killed (likely OOM) should use transparent interception with exit code
    assert!(
        output.is_allow(),
        "Signal-killed cargo test should use transparent interception"
    );
    assert!(
        matches!(output, HookOutput::AllowWithModifiedCommand(_)),
        "Signal-killed cargo test should return AllowWithModifiedCommand"
    );
}

#[tokio::test]
#[serial(mock_global)]
async fn test_cargo_test_signal_killed_with_toolchain_path_does_not_fallback_local() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_cargo_test_signal_toolchain_path_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let stderr = "error: could not compile `serde` (lib)\nCaused by:\n  process didn't exit successfully: `/home/ubuntu/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/bin/rustc --crate-name serde ...` (signal: 9, SIGKILL: kill)\n";

    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig {
            default_exit_code: 137,
            default_stderr: stderr.to_string(),
            ..MockConfig::default()
        },
        MockRsyncConfig::success(),
    );
    mock::clear_global_invocations();

    let response = SelectionResponse {
        worker: Some(SelectedWorker {
            id: rch_common::WorkerId::new("test-worker"),
            host: "test.host.local".to_string(),
            user: "testuser".to_string(),
            identity_file: "~/.ssh/test_key".to_string(),
            slots_available: 8,
            speed_score: 85.0,
            declared_os: None,
        }),
        reason: SelectionReason::Success,
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo test".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    assert!(
        matches!(output, HookOutput::AllowWithModifiedCommand(_)),
        "signal-killed remote failures that mention .rustup/toolchains must preserve the remote exit code instead of falling back local"
    );
}

#[tokio::test]
#[serial(mock_global)]
async fn test_cargo_test_toolchain_fallback() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_cargo_test_toolchain_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    // Configure mock for toolchain failure - should allow local fallback
    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig {
            default_exit_code: 1,
            default_stderr: "error: toolchain 'nightly-2025-01-15' is not installed\n".to_string(),
            ..MockConfig::default()
        },
        MockRsyncConfig::success(),
    );
    mock::clear_global_invocations();

    let response = SelectionResponse {
        worker: Some(SelectedWorker {
            id: rch_common::WorkerId::new("test-worker"),
            host: "test.host.local".to_string(),
            user: "testuser".to_string(),
            identity_file: "~/.ssh/test_key".to_string(),
            slots_available: 8,
            speed_score: 85.0,
            declared_os: None,
        }),
        reason: SelectionReason::Success,
        build_id: None,
        diagnostics: None,
    };
    spawn_mock_daemon(&socket_path, response).await;

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo test".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Toolchain failure should allow local fallback
    // Local machine might have the toolchain
    assert!(
        output.is_allow(),
        "Toolchain failure should allow local fallback"
    );
}

#[test]
fn test_cargo_test_classification() {
    let _guard = test_guard!();
    // Verify cargo test commands are classified correctly
    let result = classify_command("cargo test");
    assert!(result.is_compilation, "cargo test should be compilation");
    assert_eq!(
        result.kind,
        Some(CompilationKind::CargoTest),
        "Should be CargoTest kind"
    );

    let result = classify_command("cargo test specific_test");
    assert!(result.is_compilation);
    assert_eq!(result.kind, Some(CompilationKind::CargoTest));

    let result = classify_command("cargo test -- --test-threads=4");
    assert!(result.is_compilation);
    assert_eq!(result.kind, Some(CompilationKind::CargoTest));

    let result = classify_command("cargo test --release");
    assert!(result.is_compilation);
    assert_eq!(result.kind, Some(CompilationKind::CargoTest));

    let result = classify_command("cargo test -p mypackage");
    assert!(result.is_compilation);
    assert_eq!(result.kind, Some(CompilationKind::CargoTest));
}

#[test]
fn test_cargo_nextest_classification() {
    let _guard = test_guard!();
    // Verify cargo nextest commands are classified correctly
    let result = classify_command("cargo nextest run");
    assert!(result.is_compilation, "cargo nextest should be compilation");
    assert_eq!(
        result.kind,
        Some(CompilationKind::CargoNextest),
        "Should be CargoNextest kind"
    );

    let result = classify_command("cargo nextest run --no-fail-fast");
    assert!(result.is_compilation);
    assert_eq!(result.kind, Some(CompilationKind::CargoNextest));
}

#[test]
fn test_artifact_patterns_for_test_commands() {
    let _guard = test_guard!();
    // Verify test commands use minimal artifact patterns
    let test_patterns = get_artifact_patterns(Some(CompilationKind::CargoTest), None);
    let check_patterns = get_artifact_patterns(Some(CompilationKind::CargoCheck), None);
    let clippy_patterns = get_artifact_patterns(Some(CompilationKind::CargoClippy), None);
    let build_patterns = get_artifact_patterns(Some(CompilationKind::CargoBuild), None);

    // Test patterns should be smaller (more targeted)
    // They should include coverage/results but not full target/
    assert!(
        !test_patterns.iter().any(|p| p == "target/"),
        "Test artifacts should not include full target/"
    );

    // Build patterns should include full build outputs
    assert!(
        build_patterns.iter().any(|p| p == "target/debug/**"),
        "Build artifacts should include target/debug/**"
    );
    assert!(
        build_patterns.iter().any(|p| p == "target/release/**"),
        "Build artifacts should include target/release/**"
    );
    assert!(
        !test_patterns.iter().any(|p| p == "target/debug/**"),
        "Test artifacts should not include target/debug/**"
    );
    assert!(
        !test_patterns.iter().any(|p| p == "target/release/**"),
        "Test artifacts should not include target/release/**"
    );
    assert!(
        !check_patterns.iter().any(|p| p == "target/debug/**"),
        "Cargo check artifacts should not include target/debug/**"
    );
    assert!(
        !clippy_patterns.iter().any(|p| p == "target/debug/**"),
        "Cargo clippy artifacts should not include target/debug/**"
    );
}

#[test]
fn test_cargo_package_verification_artifacts_are_exact_archives() {
    let _guard = test_guard!();
    for command in [
        "cargo package --workspace --locked",
        "cargo package --workspace --target-dir /data/tmp/package-verification",
        "cargo +nightly publish --dry-run -p asupersync",
        "env CARGO_INCREMENTAL=0 cargo publish -n --workspace",
    ] {
        let kind = classify_command(command).kind;
        assert_eq!(kind, Some(CompilationKind::CargoBuild), "{command}");
        assert_eq!(
            get_artifact_patterns(kind, Some(command)),
            vec![
                "target/package/*.crate".to_string(),
                "target/package/tmp-registry/*.crate".to_string(),
                "target/package/tmp-crate/*.crate".to_string(),
            ],
            "return archives without registry indexes or extracted sources"
        );
        let custom = get_custom_target_artifact_patterns(kind, Some(command));
        assert_eq!(
            expected_output_glob_list(&custom),
            vec![
                "package/*.crate",
                "package/tmp-registry/*.crate",
                "package/tmp-crate/*.crate"
            ]
        );
        assert!(get_project_artifact_patterns(kind, Some(command), true).is_empty());
        for archive in [
            "package/asupersync-0.4.11.crate",
            "package/tmp-registry/asupersync-0.4.11.crate",
            // `cargo publish -p X` leaves its only archive here.
            "package/tmp-crate/asupersync-0.4.11.crate",
        ] {
            assert!(!sync_back_verified_zero_build_outputs(
                &[archive.to_string()],
                Some(1),
                kind,
                true,
            ));
        }
    }
    assert!(
        !get_artifact_patterns(Some(CompilationKind::CargoBuild), Some("cargo build"))
            .iter()
            .any(|pattern| pattern.contains("package/")),
        "ordinary builds must not return stale package archives"
    );
}

#[test]
fn test_cargo_package_verification_rejects_known_empty_archive_sync() {
    let _guard = test_guard!();
    for command in [
        "cargo package --workspace --exclude drop_unwrap_finder --locked --allow-dirty",
        "cargo publish --dry-run --workspace --exclude drop_unwrap_finder --locked --allow-dirty",
        "env 'CARGO_HOME=/data/tmp/rch-cargo-cache-vmi1293453' 'CARGO_INCREMENTAL=0' 'CARGO_PROFILE_DEV_DEBUG=0' cargo publish --dry-run -j2 --locked --allow-dirty -p franken-kernel -p franken-evidence -p franken-decision -p asupersync-macros",
    ] {
        assert!(
            sync_back_verified_zero_package_archives(Some(0), command),
            "successful verification with a proven empty sync must fail: {command}"
        );
        assert!(!sync_back_verified_zero_package_archives(Some(4), command));
        assert!(!sync_back_verified_zero_package_archives(None, command));
    }
    for command in [
        "cargo build --help",
        "cargo package --help",
        "cargo package --list",
        "cargo package --no-verify",
        "cargo publish",
        "cargo publish --dry-run --no-verify",
        "cargo publish -- --dry-run",
    ] {
        assert!(
            !sync_back_verified_zero_package_archives(Some(0), command),
            "the archive guard must remain scoped to verification: {command}"
        );
    }
}

#[test]
fn test_custom_target_artifact_patterns_for_cargo_test_are_skipped() {
    let _guard = test_guard!();
    let patterns = get_custom_target_artifact_patterns(Some(CompilationKind::CargoTest), None);

    assert!(
        patterns.is_empty(),
        "cargo test output is streamed; do not sync a custom target dir after tests"
    );
}

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

    assert!(
        get_custom_target_artifact_patterns(Some(CompilationKind::CargoCheck), None).is_empty(),
        "cargo check output is streamed; do not sync a custom target dir"
    );
    assert!(
        get_custom_target_artifact_patterns(Some(CompilationKind::CargoClippy), None).is_empty(),
        "cargo clippy output is streamed; do not sync a custom target dir"
    );
}

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

    // rch#30: with a forwarded CARGO_TARGET_DIR, the project-root phase must not
    // carry any `target/`-prefixed patterns — those belong exclusively to the
    // custom-target phase. For cargo build/doc/rustc (all-`target/` globs) the
    // filtered list is empty, so the project-root retrieval is skipped entirely.
    for kind in [
        CompilationKind::CargoBuild,
        CompilationKind::CargoDoc,
        CompilationKind::Rustc,
        CompilationKind::CargoZigbuild,
    ] {
        let with_custom = get_project_artifact_patterns(Some(kind), None, true);
        assert!(
            with_custom.is_empty(),
            "{kind:?}: all project-root patterns are target/-prefixed and must drop under a custom target sync, got {with_custom:?}"
        );
        // Without a custom target dir the behavior is unchanged (full patterns).
        assert_eq!(
            get_project_artifact_patterns(Some(kind), None, false),
            get_artifact_patterns(Some(kind), None),
            "{kind:?}: project-root patterns must be unchanged without a custom target sync"
        );
    }
}

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

    // rch#30: non-`target/` project-root artifacts (tarpaulin/junit/cobertura,
    // C/C++ outputs, bun coverage) still land at the project root regardless of
    // CARGO_TARGET_DIR, so they must survive the custom-target-sync filter.
    let test_patterns = get_project_artifact_patterns(Some(CompilationKind::CargoTest), None, true);
    assert!(
        test_patterns.iter().all(|p| !p.starts_with("target/")),
        "no target/-prefixed patterns should remain: {test_patterns:?}"
    );
    for expected in ["tarpaulin-report.html", "cobertura.xml", "junit.xml"] {
        assert!(
            test_patterns.iter().any(|p| p == expected),
            "expected non-target report {expected} to be retained: {test_patterns:?}"
        );
    }

    // C/C++ builds have no target/ patterns at all, so nothing is filtered.
    assert_eq!(
        get_project_artifact_patterns(Some(CompilationKind::Gcc), None, true),
        get_artifact_patterns(Some(CompilationKind::Gcc), None),
        "C/C++ project-root outputs are unaffected by a custom cargo target dir"
    );
}

#[test]
fn test_custom_target_artifact_patterns_for_nextest_are_target_relative() {
    let _guard = test_guard!();
    let patterns = get_custom_target_artifact_patterns(Some(CompilationKind::CargoNextest), None);

    assert!(
        !patterns.iter().any(|p| p == "**"),
        "nextest custom target retrieval must not sync the full target dir"
    );
    assert!(
        !patterns.iter().any(|p| p.starts_with("target/")),
        "custom target retrieval is already rooted at the target dir"
    );
    assert!(
        patterns.iter().any(|p| p == "nextest/**"),
        "nextest custom target retrieval should keep targeted test artifacts"
    );
}

#[test]
fn test_custom_target_artifact_patterns_for_build_commands_capture_outputs_only() {
    let _guard = test_guard!();
    for kind in [
        CompilationKind::CargoBuild,
        CompilationKind::CargoDoc,
        CompilationKind::Rustc,
    ] {
        let patterns = get_custom_target_artifact_patterns(Some(kind), None);

        // No longer the firehose: must NOT sync the entire per-job target dir.
        assert!(
            !patterns.iter().any(|p| p == "**"),
            "{kind:?}: build sync-back must not pull the whole target dir"
        );
        // The sync root IS the remote target dir, so patterns are already
        // rooted there — never re-prefixed with `target/`.
        assert!(
            !patterns.iter().any(|p| p.starts_with("target/")),
            "{kind:?}: custom-target patterns must be target-dir-relative: {patterns:?}"
        );

        // Build OUTPUTS are retained: final binaries/libs under `<profile>/`
        // (and the crate's own artifacts under `<profile>/deps`, which
        // `debug/**`/`release/**` cover). The final binary lives directly
        // under `<profile>/`, so the profile globs MUST be present.
        assert!(
            patterns.iter().any(|p| p == "debug/**"),
            "{kind:?}: must retain debug profile outputs (incl. the binary): {patterns:?}"
        );
        assert!(
            patterns.iter().any(|p| p == "release/**"),
            "{kind:?}: must retain release profile outputs (incl. the binary): {patterns:?}"
        );
        // Explicit `--target <triple>` outputs live one level deeper; the
        // sync-back must include them (hfdt-elh1t) and must exclude their
        // nested cache trees.
        assert!(
            patterns.iter().any(|p| p == "*/release/**"),
            "{kind:?}: must retain triple-nested release outputs: {patterns:?}"
        );
        assert!(
            patterns.iter().any(|p| p == "- */release/incremental/"),
            "{kind:?}: must exclude triple-nested release cache trees: {patterns:?}"
        );

        // Cache trees are EXCLUDED via `- <pat>` rules (emitted as rsync
        // `--exclude` before the includes).
        for needle in ["incremental/", ".fingerprint/", "build/", "*.d"] {
            assert!(
                patterns
                    .iter()
                    .any(|p| p.starts_with("- ") && p.contains(needle)),
                "{kind:?}: must exclude cargo cache tree {needle:?}: {patterns:?}"
            );
        }
    }
}

#[test]
fn test_custom_profile_output_dir_extraction() {
    // bd-mpbav: only CUSTOM profiles yield an output dir — cargo maps the
    // built-ins onto the already-covered dirs (dev/test → debug,
    // release/bench → release; verified against cargo 1.93).
    assert_eq!(
        cargo_custom_profile_output_dir("cargo build --profile release-perf"),
        Some("release-perf".to_string())
    );
    assert_eq!(
        cargo_custom_profile_output_dir("cargo build --profile=thin-lto"),
        Some("thin-lto".to_string())
    );
    assert_eq!(
        cargo_custom_profile_output_dir(
            "cargo build --package mycrate --profile release-perf --example app"
        ),
        Some("release-perf".to_string())
    );
    // Built-in profile names and the plain flags: nothing new to cover.
    assert_eq!(cargo_custom_profile_output_dir("cargo build"), None);
    assert_eq!(
        cargo_custom_profile_output_dir("cargo build --release"),
        None
    );
    assert_eq!(cargo_custom_profile_output_dir("cargo build -r"), None);
    assert_eq!(
        cargo_custom_profile_output_dir("cargo build --profile dev"),
        None
    );
    assert_eq!(
        cargo_custom_profile_output_dir("cargo build --profile test"),
        None
    );
    assert_eq!(
        cargo_custom_profile_output_dir("cargo build --profile release"),
        None
    );
    assert_eq!(
        cargo_custom_profile_output_dir("cargo build --profile bench"),
        None
    );
    // After `--` the args belong to the test binary, not cargo.
    assert_eq!(
        cargo_custom_profile_output_dir("cargo test -- --profile release-perf"),
        None
    );
    // Path-like or glob-like values never become rsync patterns.
    assert_eq!(
        cargo_custom_profile_output_dir("cargo build --profile ../../etc"),
        None
    );
    assert_eq!(
        cargo_custom_profile_output_dir("cargo build --profile 'a*b'"),
        None
    );
    // A trailing `--profile` with no value is malformed, not a profile.
    assert_eq!(
        cargo_custom_profile_output_dir("cargo build --profile"),
        None
    );
}

#[test]
fn test_custom_profile_globs_in_default_root_patterns() {
    // bd-mpbav layer A: `--profile release-perf` must add its output globs to
    // the default-root (project-root) pattern set for the build/doc kinds —
    // including the triple-aware form for `--target <triple>` builds.
    let plain = get_artifact_patterns(Some(CompilationKind::CargoBuild), None);
    let custom = get_artifact_patterns(
        Some(CompilationKind::CargoBuild),
        Some("cargo build --profile release-perf"),
    );
    assert_eq!(custom.len(), plain.len() + 2, "exactly two new globs");
    assert!(
        custom.iter().any(|p| p == "target/release-perf/**"),
        "custom profile output glob missing: {custom:?}"
    );
    assert!(
        custom.iter().any(|p| p == "target/*/release-perf/**"),
        "custom profile triple-aware glob missing: {custom:?}"
    );
    // The built-in coverage is unchanged.
    for needle in [
        "target/debug/**",
        "target/release/**",
        "target/*/release/**",
    ] {
        assert!(
            custom.iter().any(|p| p == needle),
            "built-in glob {needle} must be retained: {custom:?}"
        );
    }

    // Built-in profiles and plain flags add NOTHING (no duplicate globs).
    for command in [
        "cargo build",
        "cargo build --release",
        "cargo build -r",
        "cargo build --profile dev",
        "cargo build --profile test",
        "cargo build --profile release",
        "cargo build --profile bench",
    ] {
        assert_eq!(
            get_artifact_patterns(Some(CompilationKind::CargoBuild), Some(command)),
            plain,
            "{command}: built-in profile output dirs are already covered; expected no new globs"
        );
    }

    // Zigbuild with a custom profile: both plain and triple-aware forms.
    let zig = get_artifact_patterns(
        Some(CompilationKind::CargoZigbuild),
        Some("cargo zigbuild --profile release-perf --target aarch64-unknown-linux-gnu"),
    );
    assert!(zig.iter().any(|p| p == "target/release-perf/**"), "{zig:?}");
    assert!(
        zig.iter().any(|p| p == "target/*/release-perf/**"),
        "{zig:?}"
    );

    // Test/diagnostic kinds keep their narrow streaming allowlist: no profile
    // globs even when a profile is named.
    let test_patterns = get_artifact_patterns(
        Some(CompilationKind::CargoTest),
        Some("cargo test --profile release-perf"),
    );
    assert!(
        !test_patterns.iter().any(|p| p.contains("release-perf")),
        "streaming kinds must not gain target globs: {test_patterns:?}"
    );
}

#[test]
fn test_custom_profile_globs_in_custom_target_patterns() {
    // bd-mpbav layer A, custom-CARGO_TARGET_DIR variant: the profile's output
    // globs are rebased onto the target-dir sync root and its cache trees get
    // BOTH the plain and the triple-nested exclude forms.
    let patterns = get_custom_target_artifact_patterns(
        Some(CompilationKind::CargoBuild),
        Some("cargo build --profile release-perf"),
    );
    let (excludes, includes): (Vec<&String>, Vec<&String>) =
        patterns.iter().partition(|p| p.starts_with("- "));

    assert!(
        includes.iter().any(|p| p.as_str() == "release-perf/**"),
        "rebased profile include missing: {patterns:?}"
    );
    assert!(
        includes.iter().any(|p| p.as_str() == "*/release-perf/**"),
        "rebased triple-aware profile include missing: {patterns:?}"
    );
    for exclude in [
        "- release-perf/incremental/",
        "- release-perf/.fingerprint/",
        "- release-perf/build/",
        "- */release-perf/incremental/",
        "- */release-perf/.fingerprint/",
        "- */release-perf/build/",
    ] {
        assert!(
            excludes.iter().any(|p| p.as_str() == exclude),
            "profile cache exclude {exclude} missing: {patterns:?}"
        );
    }
    // Excludes must be emitted BEFORE the includes (rsync first-match-wins).
    let first_include = patterns
        .iter()
        .position(|p| !p.starts_with("- "))
        .expect("at least one include");
    let last_exclude = patterns
        .iter()
        .rposition(|p| p.starts_with("- "))
        .expect("at least one exclude");
    assert!(
        last_exclude < first_include,
        "all excludes must precede the includes: {patterns:?}"
    );

    // Built-in profile names: identical to the no-flag pattern set.
    assert_eq!(
        get_custom_target_artifact_patterns(
            Some(CompilationKind::CargoBuild),
            Some("cargo build --profile bench")
        ),
        get_custom_target_artifact_patterns(Some(CompilationKind::CargoBuild), None),
        "--profile bench maps to target/release/ — no extra patterns"
    );
}

#[test]
fn test_sync_back_zero_output_detection() {
    // bd-mpbav layer B: classify a retrieved-file manifest from a SUCCESSFUL
    // sync-back. The observed bug signature: only loose target-root metadata
    // came back while the real binary stayed on the worker.
    let metadata_only = vec![".rustc_info.json".to_string(), "CACHEDIR.TAG".to_string()];
    let with_binary = vec![
        ".rustc_info.json".to_string(),
        "CACHEDIR.TAG".to_string(),
        "release-perf/examples/fmd_perf_harness".to_string(),
    ];
    let kind = Some(CompilationKind::CargoBuild);

    // The complete manifest with ONLY non-output files is the hazard.
    assert!(
        sync_back_verified_zero_build_outputs(&metadata_only, Some(2), kind, true),
        "metadata-only manifest must be classified as a zero-output failure"
    );
    // A manifest containing a real output binary is a success.
    assert!(
        !sync_back_verified_zero_build_outputs(&with_binary, Some(3), kind, true),
        "a manifest containing the output binary must NOT fail"
    );
    // Up-to-date no-op rebuild: outputs present as verified-up-to-date (`.f`)
    // manifest entries — must NOT fail.
    assert!(
        !sync_back_verified_zero_build_outputs(
            &[
                ".rustc_info.json".to_string(),
                "release-perf/examples/fmd_perf_harness".to_string()
            ],
            Some(2),
            kind,
            true
        ),
        "up-to-date outputs in the manifest must NOT fail"
    );
    // Cache trees do not count as outputs: a manifest of only cache state
    // still fires.
    assert!(
        sync_back_verified_zero_build_outputs(
            &["debug/incremental/session.bin".to_string()],
            Some(1),
            kind,
            true
        ),
        "cache-only manifest must be classified as a zero-output failure"
    );

    // Fail-open guards: no firing without POSITIVE proof.
    // Unknown matched count (stats unparseable) proves nothing.
    assert!(!sync_back_verified_zero_build_outputs(
        &metadata_only,
        None,
        kind,
        true
    ));
    // Zero matched files at all (e.g. `cargo build --help` produced nothing).
    assert!(!sync_back_verified_zero_build_outputs(
        &[],
        Some(0),
        kind,
        true
    ));
    // Incomplete manifest (fewer entries than rsync matched): outputs may
    // exist unlisted (e.g. a worker rsync that does not itemize up-to-date
    // files) — never fire on incomplete evidence.
    assert!(!sync_back_verified_zero_build_outputs(
        &metadata_only,
        Some(4),
        kind,
        true
    ));
    // Kinds without an enumerable output contract never fire (their zero-output
    // runs can be legitimate: direct rustc writes outside target/, C/C++ has
    // -fsyntax-only-style forms).
    for non_enumerable in [
        CompilationKind::Rustc,
        CompilationKind::Gcc,
        CompilationKind::Make,
        CompilationKind::CargoTest,
    ] {
        assert!(
            !sync_back_verified_zero_build_outputs(
                &metadata_only,
                Some(2),
                Some(non_enumerable),
                true
            ),
            "{non_enumerable:?} has no enumerable output contract"
        );
    }
    assert!(!sync_back_verified_zero_build_outputs(
        &metadata_only,
        Some(2),
        None,
        true
    ));

    // Project-root basis: paths are target/-prefixed; the same metadata-only
    // manifest (with the prefix) fires, and cache trees under target/ do not
    // rescue it.
    let root_metadata_only = vec![
        "target/.rustc_info.json".to_string(),
        "target/CACHEDIR.TAG".to_string(),
    ];
    assert!(sync_back_verified_zero_build_outputs(
        &root_metadata_only,
        Some(2),
        kind,
        false
    ));
    assert!(!sync_back_verified_zero_build_outputs(
        &[
            "target/.rustc_info.json".to_string(),
            "target/debug/my_app".to_string()
        ],
        Some(2),
        kind,
        false
    ));
    assert!(sync_back_verified_zero_build_outputs(
        &[
            "target/.rustc_info.json".to_string(),
            "target/debug/incremental/foo.bin".to_string()
        ],
        Some(2),
        kind,
        false
    ));
}

#[test]
fn test_custom_target_patterns_match_a_binary_but_not_cache() {
    // Verify against a realistic remote target layout that the output globs
    // match the final binary under `<profile>/` while the exclude rules drop
    // the cache trees. Mirrors how the rsync filter chain evaluates them:
    // an explicit `- <pat>` exclude wins over a later `debug/**` include.
    let _guard = test_guard!();
    let patterns = get_custom_target_artifact_patterns(Some(CompilationKind::CargoBuild), None);

    let (excludes, includes): (Vec<&String>, Vec<&String>) =
        patterns.iter().partition(|p| p.starts_with("- "));
    let exclude_payloads: Vec<&str> = excludes
        .iter()
        .map(|p| p.trim_start_matches("- "))
        .collect();

    // Helper mirroring rsync first-match-wins: an exclude rule that matches
    // the path wins (the excludes are emitted before the includes); otherwise
    // an include glob decides. Directory excludes (`<dir>/`, `*/<dir>/`) match
    // any path containing that segment; `*.d` matches by suffix.
    let excluded = |path: &str| -> bool {
        exclude_payloads.iter().any(|ex| {
            if let Some(dir) = ex.strip_suffix('/') {
                let segment = dir.trim_start_matches("*/");
                path.split('/').any(|comp| comp == segment)
            } else if let Some(suffix) = ex.strip_prefix('*') {
                path.ends_with(suffix)
            } else {
                path == *ex
            }
        })
    };
    let included = |path: &str| -> bool {
        if excluded(path) {
            return false;
        }
        includes.iter().any(|inc| {
            if let Some(prefix) = inc.strip_suffix("/**") {
                path.starts_with(&format!("{prefix}/"))
            } else {
                path == inc.as_str()
            }
        })
    };

    // The final binary (directly under the profile dir) IS retrieved.
    assert!(
        included("debug/my_app"),
        "the final debug binary must be synced back: {patterns:?}"
    );
    assert!(
        included("release/my_app"),
        "the final release binary must be synced back: {patterns:?}"
    );
    // The crate's compiled deps artifacts ARE retrieved.
    assert!(
        included("debug/deps/libmy_app.rlib"),
        "crate deps artifacts must be synced back: {patterns:?}"
    );
    // Cache trees are NOT retrieved.
    assert!(
        !included("debug/incremental/foo/bar.bin"),
        "incremental cache must not be synced back: {patterns:?}"
    );
    assert!(
        !included("debug/.fingerprint/my_app/lib.json"),
        ".fingerprint cache must not be synced back: {patterns:?}"
    );
    assert!(
        !included("debug/build/somecrate/out/generated.rs"),
        "build-script cache must not be synced back: {patterns:?}"
    );
    assert!(
        !included("debug/deps/my_app.d"),
        "dep (*.d) files must not be synced back: {patterns:?}"
    );
}

#[test]
fn test_expected_output_glob_list_drops_excludes_and_metadata() {
    // The RCH-E326 failure message must name real output locations only:
    // `- ` exclude rules and the loose target-root metadata files are noise
    // a caller cannot act on.
    let patterns = get_custom_target_artifact_patterns(
        Some(CompilationKind::CargoBuild),
        Some("cargo build --profile release-perf"),
    );
    let expected = expected_output_glob_list(&patterns);
    assert!(
        !expected.is_empty(),
        "expected list must retain the output globs: {expected:?}"
    );
    assert!(
        expected.iter().all(|p| !p.starts_with("- ")),
        "no exclude rules in the expected list: {expected:?}"
    );
    for metadata in [".rustc_info.json", "CACHEDIR.TAG"] {
        assert!(
            !expected.iter().any(|p| p == metadata),
            "metadata file {metadata} must not be listed as an expected output"
        );
    }
    assert!(
        expected.iter().any(|p| p == "release-perf/**"),
        "the custom profile glob must be named: {expected:?}"
    );
}
// =========================================================================
// Test filtering and special flags tests (bead remote_compilation_helper-ya16)
// =========================================================================

#[test]
fn test_is_filtered_test_command_basic() {
    let _guard = test_guard!();
    // Basic test name filter
    assert!(
        is_filtered_test_command("cargo test my_test"),
        "Should detect test name filter"
    );
    assert!(
        is_filtered_test_command("cargo test test_foo"),
        "Should detect test name filter"
    );
    assert!(
        is_filtered_test_command("cargo test some::module::test"),
        "Should detect module path filter"
    );

    // Full test suite (no filter)
    assert!(
        !is_filtered_test_command("cargo test"),
        "No filter in basic cargo test"
    );
    assert!(
        !is_filtered_test_command("cargo test --release"),
        "Flags are not filters"
    );
}

#[test]
fn test_is_filtered_test_command_with_flags() {
    let _guard = test_guard!();
    // Filter with flags
    assert!(
        is_filtered_test_command("cargo test --release my_test"),
        "Should detect filter after flags"
    );
    assert!(
        is_filtered_test_command("cargo test -p mypackage my_test"),
        "Should detect filter after package flag"
    );

    // Only package flag (not a name filter)
    assert!(
        !is_filtered_test_command("cargo test -p mypackage"),
        "Package is not a test name filter"
    );
    assert!(
        !is_filtered_test_command("cargo test --lib"),
        "--lib is not a test name filter"
    );
}

#[test]
fn test_is_filtered_test_command_with_separator() {
    let _guard = test_guard!();
    // Filter before --
    assert!(
        is_filtered_test_command("cargo test my_test -- --nocapture"),
        "Should detect filter before separator"
    );

    // No filter, args after --
    assert!(
        !is_filtered_test_command("cargo test -- --nocapture"),
        "Args after -- are not test name filters"
    );
    assert!(
        !is_filtered_test_command("cargo test -- --test-threads=4"),
        "Args after -- are not test name filters"
    );
}

#[test]
fn test_has_ignored_only_flag() {
    let _guard = test_guard!();
    // Only --ignored
    assert!(
        has_ignored_only_flag("cargo test -- --ignored"),
        "Should detect --ignored"
    );

    // --include-ignored (runs all tests)
    assert!(
        !has_ignored_only_flag("cargo test -- --include-ignored"),
        "--include-ignored runs all tests"
    );

    // Both flags (--include-ignored takes precedence)
    assert!(
        !has_ignored_only_flag("cargo test -- --ignored --include-ignored"),
        "--include-ignored takes precedence"
    );

    // No flags
    assert!(!has_ignored_only_flag("cargo test"), "No flags");
}

#[test]
fn test_has_exact_flag() {
    let _guard = test_guard!();
    assert!(
        has_exact_flag("cargo test my_test -- --exact"),
        "--exact detected"
    );
    assert!(!has_exact_flag("cargo test my_test"), "No --exact");
    assert!(!has_exact_flag("cargo test -- --nocapture"), "No --exact");
}

#[test]
fn test_estimate_cores_filtered_tests() {
    let _guard = test_guard!();
    let config = rch_common::CompilationConfig {
        build_slots: 6,
        test_slots: 10,
        check_slots: 3,
        ..Default::default()
    };

    // Full test suite gets default slots
    let full = estimate_cores_for_command(Some(CompilationKind::CargoTest), "cargo test", &config);
    assert_eq!(full, 10, "Full test suite uses default test_slots");

    // Filtered test gets reduced slots (test_slots / 2, min 2)
    let filtered = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "cargo test my_test",
        &config,
    );
    assert_eq!(filtered, 5, "Filtered test uses reduced slots");

    // --exact flag gets reduced slots
    let exact = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "cargo test my_test -- --exact",
        &config,
    );
    assert_eq!(exact, 5, "--exact uses reduced slots");

    // --ignored only gets reduced slots
    let ignored = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "cargo test -- --ignored",
        &config,
    );
    assert_eq!(ignored, 5, "--ignored uses reduced slots");

    // --include-ignored gets full slots (runs all tests plus ignored)
    let include_ignored = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "cargo test -- --include-ignored",
        &config,
    );
    assert_eq!(include_ignored, 10, "--include-ignored uses full slots");
}

#[test]
fn test_estimate_cores_explicit_threads_overrides_filter() {
    let _guard = test_guard!();
    let config = rch_common::CompilationConfig {
        build_slots: 6,
        test_slots: 10,
        check_slots: 3,
        ..Default::default()
    };

    // Explicit --test-threads should override filtering heuristics
    let explicit = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "cargo test my_test -- --test-threads=8",
        &config,
    );
    assert_eq!(explicit, 8, "Explicit --test-threads overrides filtering");

    // RUST_TEST_THREADS also overrides
    let env = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "RUST_TEST_THREADS=6 cargo test my_test",
        &config,
    );
    assert_eq!(env, 6, "RUST_TEST_THREADS overrides filtering");
}

#[test]
fn test_estimate_cores_filtered_minimum() {
    let _guard = test_guard!();
    let config = rch_common::CompilationConfig {
        build_slots: 6,
        test_slots: 2, // Very low test_slots
        check_slots: 3,
        ..Default::default()
    };

    // With test_slots=2, filtered should be max(2/2, 2) = max(1, 2) = 2
    let filtered = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "cargo test my_test",
        &config,
    );
    assert!(filtered >= 2, "Filtered slots should be at least 2");
}

#[test]
fn test_estimate_cores_filtered_never_exceeds_default() {
    let _guard = test_guard!();
    let config = rch_common::CompilationConfig {
        build_slots: 6,
        test_slots: 1, // Single-slot environment
        check_slots: 3,
        ..Default::default()
    };

    let filtered = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "cargo test my_test",
        &config,
    );
    assert_eq!(
        filtered, 1,
        "Filtered tests should not request more slots than test_slots"
    );
}

#[test]
fn test_nocapture_does_not_affect_slots() {
    let _guard = test_guard!();
    let config = rch_common::CompilationConfig {
        build_slots: 6,
        test_slots: 10,
        check_slots: 3,
        ..Default::default()
    };

    // --nocapture doesn't affect slot estimation
    let with_nocapture = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "cargo test -- --nocapture",
        &config,
    );
    let without =
        estimate_cores_for_command(Some(CompilationKind::CargoTest), "cargo test", &config);
    assert_eq!(with_nocapture, without, "--nocapture doesn't affect slots");

    // --show-output also doesn't affect slots
    let with_show = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "cargo test -- --show-output",
        &config,
    );
    assert_eq!(with_show, without, "--show-output doesn't affect slots");
}

#[test]
fn test_skip_pattern_uses_full_slots() {
    let _guard = test_guard!();
    let config = rch_common::CompilationConfig {
        build_slots: 6,
        test_slots: 10,
        check_slots: 3,
        ..Default::default()
    };

    // --skip doesn't reduce the test suite significantly
    // (still runs most tests, just skipping some)
    let with_skip = estimate_cores_for_command(
        Some(CompilationKind::CargoTest),
        "cargo test -- --skip slow_test",
        &config,
    );
    assert_eq!(with_skip, 10, "--skip uses full slots");
}

#[test]
fn test_parse_selection_response_accepts_known_newer_health_reason() {
    let _guard = test_guard!();
    let json = serde_json::json!({
        "selection_protocol_version": rch_common::SELECTION_RESPONSE_PROTOCOL_VERSION,
        "worker": null,
        "reason": "no_workers_passed_health",
        "build_id": null,
        "diagnostics": null
    })
    .to_string();

    let response = parse_selection_response(&json).expect("selection response parses");

    assert_eq!(response.reason, SelectionReason::NoWorkersPassedHealth);
    assert!(response.worker.is_none());
}

#[test]
fn test_parse_selection_response_tolerates_unknown_unit_reason() {
    let _guard = test_guard!();
    let json = serde_json::json!({
        "selection_protocol_version": rch_common::SELECTION_RESPONSE_PROTOCOL_VERSION,
        "worker": null,
        "reason": "future_selector_gate",
        "build_id": null,
        "diagnostics": null
    })
    .to_string();

    let response = parse_selection_response(&json).expect("unknown reason should not fail");

    assert!(response.worker.is_none());
    assert!(matches!(
        response.reason,
        SelectionReason::SelectionError(_)
    ));
    assert!(
        response
            .reason
            .to_string()
            .contains("unknown daemon selection reason")
    );
    assert!(
        response.reason.to_string().contains("future_selector_gate"),
        "unknown unit reason should preserve daemon detail: {}",
        response.reason
    );
}

#[test]
fn test_parse_selection_response_preserves_unknown_structured_reason_detail() {
    let _guard = test_guard!();
    let json = serde_json::json!({
        "selection_protocol_version": rch_common::SELECTION_RESPONSE_PROTOCOL_VERSION,
        "worker": null,
        "reason": { "future_selector_gate": "runtime_probe_missing" },
        "build_id": null,
        "diagnostics": null
    })
    .to_string();

    let response = parse_selection_response(&json).expect("unknown reason should not fail");
    let detail = response.reason.to_string();

    assert!(matches!(
        response.reason,
        SelectionReason::SelectionError(_)
    ));
    assert!(
        detail.contains("future_selector_gate"),
        "unknown structured reason should preserve variant name: {detail}"
    );
    assert!(
        detail.contains("runtime_probe_missing"),
        "unknown structured reason should preserve daemon payload: {detail}"
    );
}

#[test]
fn test_parse_selection_response_rejects_unsupported_protocol_version() {
    let _guard = test_guard!();
    let json = serde_json::json!({
        "selection_protocol_version": rch_common::SELECTION_RESPONSE_PROTOCOL_VERSION + 1,
        "worker": null,
        "reason": "all_workers_busy",
        "build_id": null,
        "diagnostics": null
    })
    .to_string();

    let error = parse_selection_response(&json).expect_err("future protocol should fail");

    assert!(
        error.to_string().contains("exceeds client support"),
        "unexpected error: {error}"
    );
}

// =========================================================================
// Timeout handling tests (bead bd-1aim.2)
// =========================================================================

#[tokio::test]
async fn test_daemon_query_connect_timeout_fail_open() {
    // When the daemon socket exists but doesn't accept connections quickly,
    // the hook should timeout and fail-open to allow local execution.
    //
    // We simulate this by creating a socket that accepts but never responds.
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_connect_timeout_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    // Clean up any existing socket
    let _ = std::fs::remove_file(&socket_path);

    // Create a socket that accepts connections but never responds
    let listener = UnixListener::bind(&socket_path).expect("Failed to create test socket");

    let socket_path_clone = socket_path.clone();
    tokio::spawn(async move {
        // Accept the connection but do nothing with it
        let _ = listener.accept().await;
        // Hold connection open for longer than the timeout
        tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
    });

    // Give listener time to start
    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    // Query should timeout since daemon never responds
    let result: anyhow::Result<SelectionResponse> = query_daemon(
        &socket_path,
        "test-project",
        4,
        0,
        "cargo build",
        None,
        RequiredRuntime::None,
        CommandPriority::Normal,
        100,
        None,
        None,
        false,
        &[],
        false,
        &[],
    )
    .await;

    let _ = std::fs::remove_file(&socket_path_clone);

    // Should fail due to read timeout (empty response)
    assert!(
        result.is_err(),
        "Query should fail when daemon doesn't respond"
    );
}

#[tokio::test]
async fn test_process_hook_timeout_fail_open() {
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_process_timeout_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    // Create test config with our socket
    let _overrides = TestOverridesGuard::set(
        &socket_path,
        MockConfig::default(),
        MockRsyncConfig::success(),
    );

    // Clean up any existing socket
    let _ = std::fs::remove_file(&socket_path);

    // Create a slow daemon that doesn't respond in time
    let listener = UnixListener::bind(&socket_path).expect("bind");

    tokio::spawn(async move {
        // Accept and hold connection but don't respond
        let (stream, _) = listener.accept().await.expect("accept");
        // Hold the stream open
        let (_reader, _writer) = stream.into_split();
        tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
    });

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let input = HookInput {
        tool_name: "Bash".to_string(),
        tool_input: ToolInput {
            command: "cargo build".to_string(),
            description: None,
        },
        session_id: None,
    };

    let output = process_hook(input).await;
    let _ = std::fs::remove_file(&socket_path);

    // Should fail-open when daemon times out
    assert!(
        output.is_allow(),
        "Hook should fail-open when daemon query times out"
    );
}

#[tokio::test]
async fn test_daemon_query_partial_response_timeout() {
    // Test behavior when daemon sends partial response and then hangs
    let _lock = test_lock().lock().await;
    let socket_path = format!(
        "/tmp/rch_test_partial_timeout_{}_{}.sock",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    let _ = std::fs::remove_file(&socket_path);
    let listener = UnixListener::bind(&socket_path).expect("bind");

    let socket_path_clone = socket_path.clone();
    tokio::spawn(async move {
        let (stream, _) = listener.accept().await.expect("accept");
        let (reader, mut writer) = stream.into_split();
        let mut buf_reader = TokioBufReader::new(reader);

        // Read request
        let mut request_line = String::new();
        let _ = buf_reader.read_line(&mut request_line).await;

        // Write partial HTTP response (no body)
        writer
            .write_all(b"HTTP/1.1 200 OK\r\n")
            .await
            .expect("write");
        // Hang without completing the response
        tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
    });

    tokio::time::sleep(tokio::time::Duration::from_millis(25)).await;

    let result = query_daemon(
        &socket_path,
        "test-project",
        4,
        0,
        "cargo build",
        None,
        RequiredRuntime::None,
        CommandPriority::Normal,
        100,
        None,
        None,
        false,
        &[],
        false,
        &[],
    )
    .await;

    let _ = std::fs::remove_file(&socket_path_clone);

    // Partial response should result in error (no body to parse)
    assert!(result.is_err(), "Partial response should result in error");
}

#[test]
fn test_queue_when_busy_enabled_parser() {
    let _guard = test_guard!();
    assert!(queue_when_busy_enabled_from(None));
    assert!(queue_when_busy_enabled_from(Some("1")));
    assert!(queue_when_busy_enabled_from(Some("true")));
    assert!(queue_when_busy_enabled_from(Some("yes")));
    assert!(!queue_when_busy_enabled_from(Some("0")));
    assert!(!queue_when_busy_enabled_from(Some("false")));
    assert!(!queue_when_busy_enabled_from(Some("off")));
}

#[test]
fn test_daemon_response_timeout_defaults_and_overrides() {
    let _guard = test_guard!();
    assert_eq!(
        daemon_response_timeout_for(false, None, None),
        Duration::from_secs(DEFAULT_DAEMON_RESPONSE_TIMEOUT_SECS)
    );
    assert_eq!(
        daemon_response_timeout_for(true, None, None),
        Duration::from_secs(DEFAULT_DAEMON_WAIT_RESPONSE_TIMEOUT_SECS)
    );
    assert_eq!(
        daemon_response_timeout_for(true, None, Some("900")),
        Duration::from_secs(900)
    );
    assert_eq!(
        daemon_response_timeout_for(true, Some("45"), Some("900")),
        Duration::from_secs(45)
    );
    assert_eq!(
        daemon_response_timeout_for(true, Some("invalid"), Some("invalid")),
        Duration::from_secs(DEFAULT_DAEMON_WAIT_RESPONSE_TIMEOUT_SECS)
    );
}

// ============================================================================
// Auto-start (Self-Healing) Tests
// ============================================================================

/// Test helper to create a unique temp directory for auto-start tests
fn create_test_state_dir() -> tempfile::TempDir {
    tempfile::TempDir::new().expect("Failed to create temp dir")
}

// Auto-start (Self-Healing) unit tests for these helpers now live in
// the `auto_start` submodule (`rch/src/hook/auto_start.rs`).

// -----------------------------------------------------------------------
// bd-session-history-remediation-ocv9i.3.1: hook socket-failure recovery.
// The six bead scenarios exercised against the pure decision cores and the
// structured incidents they emit — no daemon spawn required.
// -----------------------------------------------------------------------

#[test]
fn test_classify_socket_failure_missing_when_socket_not_found() {
    let err: anyhow::Error = super::DaemonError::SocketNotFound {
        socket_path: "/run/rch/rch.sock".to_string(),
    }
    .into();
    // The socket file is genuinely absent.
    assert_eq!(
        super::classify_socket_failure(&err, false),
        super::SocketFailureKind::Missing
    );
}

#[test]
fn test_classify_socket_failure_refused_socket() {
    // Scenario: refused socket (no live listener on an existing socket).
    let err = anyhow::Error::from(std::io::Error::from(std::io::ErrorKind::ConnectionRefused));
    assert_eq!(
        super::classify_socket_failure(&err, true),
        super::SocketFailureKind::Refused
    );
}

#[test]
fn test_classify_socket_failure_stale_socket_on_timeout() {
    // Scenario: stale socket. The 5s connect timeout is a plain anyhow
    // string error (no io::Error source).
    let err = anyhow::anyhow!("Daemon connect timed out after 5s");
    assert_eq!(
        super::classify_socket_failure(&err, true),
        super::SocketFailureKind::Stale
    );
    // A TimedOut io error classifies the same way.
    let io_timeout = anyhow::Error::from(std::io::Error::from(std::io::ErrorKind::TimedOut));
    assert_eq!(
        super::classify_socket_failure(&io_timeout, true),
        super::SocketFailureKind::Stale
    );
}

#[test]
fn test_detect_socket_path_mismatch_wrong_configured_socket() {
    // Scenario: wrong configured socket. Configured path differs from the
    // canonical default => reported mismatch (detection only).
    let mismatch = super::detect_socket_path_mismatch(
        "/tmp/custom-rch.sock",
        "/home/dev/.cache/rch/rch.sock",
        true,
    )
    .expect("differing paths must be reported as a mismatch");
    assert_eq!(mismatch.configured, "/tmp/custom-rch.sock");
    assert_eq!(mismatch.canonical, "/home/dev/.cache/rch/rch.sock");
    assert!(mismatch.canonical_exists);
    // Equivalent paths (ignoring surrounding whitespace) => no mismatch.
    assert!(
        super::detect_socket_path_mismatch(
            " /home/dev/.cache/rch/rch.sock ",
            "/home/dev/.cache/rch/rch.sock",
            true,
        )
        .is_none()
    );
}

#[test]
fn test_decide_recovery_action_daemon_start_success_proceeds_remote() {
    // Scenario: daemon start success. A successful retry proceeds remotely
    // regardless of proof mode.
    assert_eq!(
        super::decide_recovery_action(true, false),
        super::DaemonRecoveryAction::ProceedRemote
    );
    assert_eq!(
        super::decide_recovery_action(true, true),
        super::DaemonRecoveryAction::ProceedRemote
    );
}

#[test]
fn test_decide_recovery_action_daemon_start_failure_falls_back_open() {
    // Scenario: daemon start failure, convenience lane => fail open local.
    assert_eq!(
        super::decide_recovery_action(false, false),
        super::DaemonRecoveryAction::LocalFallback
    );
}

#[test]
fn test_decide_recovery_action_proof_mode_refuses() {
    // Scenario: proof-mode refusal. Retry failed under proof mode => fail
    // closed (refuse local fallback).
    assert_eq!(
        super::decide_recovery_action(false, true),
        super::DaemonRecoveryAction::Refuse
    );
}

#[test]
fn test_build_socket_failure_incident_records_reason_and_mismatch() {
    let mismatch = super::SocketPathMismatch {
        configured: "/home/alice/.cache/rch/rch.sock".to_string(),
        canonical: "/home/alice/.config/rch/rch.sock".to_string(),
        canonical_exists: true,
    };
    let event = super::build_socket_failure_incident(
        super::SocketFailureKind::Refused,
        Some(&mismatch),
        "demo-project",
        "cargo build --release",
        false,
        1_700_000_000_000,
    );
    assert_eq!(
        event.reason_code,
        rch_common::IncidentReasonCode::DaemonSocketRefused
    );
    assert_eq!(event.reason_code.code(), "RCH-I010");
    assert_eq!(event.source, rch_common::IncidentSource::Hook);
    assert_eq!(event.selected_mode, rch_common::SelectedMode::Local);
    assert!(
        event.local_fallback_allowed,
        "convenience lane permits fallback"
    );
    assert_eq!(
        event.details.get("socket_failure").map(String::as_str),
        Some("refused")
    );
    assert_eq!(
        event
            .details
            .get("socket_path_mismatch")
            .map(String::as_str),
        Some("true")
    );
    // Home segment must be masked in the recorded path detail.
    let configured = event.details.get("configured_socket").unwrap();
    assert!(
        configured.contains("<redacted>"),
        "home user must be masked: {configured}"
    );
    assert!(
        !configured.contains("alice"),
        "raw username must not leak: {configured}"
    );
    assert_eq!(
        event
            .details
            .get("canonical_socket_exists")
            .map(String::as_str),
        Some("true")
    );
}

#[test]
fn test_build_recovery_terminal_incident_proof_vs_fallback() {
    // Proof mode => ProofRefusal (RCH-I012), no local fallback allowed.
    let refusal = super::build_recovery_terminal_incident(
        true,
        "demo",
        "cargo test",
        "daemon unavailable",
        1_700_000_000_001,
    );
    assert_eq!(
        refusal.reason_code,
        rch_common::IncidentReasonCode::ProofRefusal
    );
    assert_eq!(refusal.reason_code.code(), "RCH-I012");
    assert!(!refusal.local_fallback_allowed);
    assert!(refusal.control.strict_remote_policy);
    // Convenience mode => LocalFallback (RCH-I011), fallback allowed.
    let fallback = super::build_recovery_terminal_incident(
        false,
        "demo",
        "cargo test",
        "daemon unavailable",
        1_700_000_000_002,
    );
    assert_eq!(
        fallback.reason_code,
        rch_common::IncidentReasonCode::LocalFallback
    );
    assert_eq!(fallback.reason_code.code(), "RCH-I011");
    assert!(fallback.local_fallback_allowed);
    assert!(!fallback.control.strict_remote_policy);
}

#[test]
fn test_local_fallback_incident_records_reason_and_redacts_command() {
    // bd-qawj7: every terminal local fallback records WHY, durably.
    let command = "GITHUB_TOKEN=ghp_supersecretvalue123456 cargo build --release";
    let local = super::build_local_fallback_incident(
        command,
        "no admissible workers (critical_pressure=5)",
        false,
        1_700_000_000_010,
        None,
    );
    assert!(!local.details.contains_key("error"));
    assert_eq!(
        local.reason_code,
        rch_common::IncidentReasonCode::LocalFallback
    );
    assert_eq!(local.reason_code.code(), "RCH-I011");
    assert!(local.local_fallback_allowed);
    assert_eq!(
        local.details.get("reason").map(String::as_str),
        Some("no admissible workers (critical_pressure=5)")
    );
    assert!(!local.command_fingerprint.contains("supersecretvalue"));
    assert!(local.command_fingerprint.contains("cargo build --release"));
    assert!(!local.project_id.is_empty());

    let refused = super::build_local_fallback_incident(
        "cargo test",
        "remote execution failed; remote retries exhausted",
        true,
        1_700_000_000_011,
        Some(&format!(
            "hz3: remote execution completion is unconfirmed: GITHUB_TOKEN=ghp_supersecretvalue123456 {}",
            "x".repeat(2_000)
        )),
    );
    assert_eq!(
        refused.reason_code,
        rch_common::IncidentReasonCode::ProofRefusal
    );
    // The stable reason is untouched (it is grouped in `rch status`); the
    // cause travels separately, redacted and bounded.
    assert_eq!(
        refused.details.get("reason").map(String::as_str),
        Some("remote execution failed; remote retries exhausted")
    );
    let error = refused.details.get("error").expect("error chain recorded");
    assert!(error.starts_with("hz3: remote execution completion is unconfirmed"));
    assert!(!error.contains("supersecretvalue"), "{error}");
    assert!(
        error.chars().count() <= 601,
        "bounded: {}",
        error.chars().count()
    );
    assert!(!refused.local_fallback_allowed);
    assert!(refused.control.strict_remote_policy);

    let dir = create_test_state_dir();
    let ledger = rch_common::IncidentLedger::with_path(dir.path().join("incidents.jsonl"));
    ledger.append(&local).expect("append must succeed");
    ledger.append(&refused).expect("append must succeed");
    let read = rch_common::IncidentLedger::with_path(ledger.path()).read_all();
    assert_eq!(read.len(), 2);
    assert_eq!(
        read[0].details.get("reason").map(String::as_str),
        Some("no admissible workers (critical_pressure=5)")
    );
}

#[test]
fn test_socket_failure_incident_durably_appends_to_ledger() {
    // End-to-end durable record: build the incident the hook emits, append
    // it to a temp ledger, and read it back — proving the structured
    // incident survives a process restart (no env mutation needed).
    let dir = create_test_state_dir();
    let ledger = rch_common::IncidentLedger::with_path(dir.path().join("incidents.jsonl"));
    let event = super::build_socket_failure_incident(
        super::SocketFailureKind::Stale,
        None,
        "demo",
        "cargo check",
        true,
        1_700_000_000_003,
    );
    ledger.append(&event).expect("append must succeed");
    let read = rch_common::IncidentLedger::with_path(ledger.path()).read_all();
    assert_eq!(read.len(), 1);
    assert_eq!(
        read[0].reason_code,
        rch_common::IncidentReasonCode::DaemonSocketRefused
    );
    assert_eq!(
        read[0].details.get("socket_failure").map(String::as_str),
        Some("stale")
    );
    assert!(
        !read[0].local_fallback_allowed,
        "proof mode records no fallback"
    );
}

// Auto-start socket-staleness, state-dir/path, and cooldown unit tests
// now live in the `auto_start` submodule (`rch/src/hook/auto_start.rs`).

// =========================================================================
// Timing History Tests
// =========================================================================

#[test]
fn test_timing_record_creation() {
    let _guard = test_guard!();
    let now_secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs();

    let record = TimingRecord {
        timestamp: now_secs,
        duration_ms: 5000,
        remote: true,
    };

    assert_eq!(record.duration_ms, 5000);
    assert!(record.remote);
    assert!(record.timestamp >= now_secs - 1 && record.timestamp <= now_secs + 1);
}

#[test]
fn test_project_timing_data_add_sample() {
    let _guard = test_guard!();
    let mut data = ProjectTimingData::default();

    // Add local sample
    data.add_sample(1000, false);
    assert_eq!(data.local_samples.len(), 1);
    assert_eq!(data.remote_samples.len(), 0);
    assert_eq!(data.local_samples[0].duration_ms, 1000);

    // Add remote sample
    data.add_sample(500, true);
    assert_eq!(data.local_samples.len(), 1);
    assert_eq!(data.remote_samples.len(), 1);
    assert_eq!(data.remote_samples[0].duration_ms, 500);
}

#[test]
fn test_project_timing_data_median_odd_count() {
    let _guard = test_guard!();
    let mut data = ProjectTimingData::default();
    data.add_sample(100, false);
    data.add_sample(300, false);
    data.add_sample(200, false);

    // Median of [100, 200, 300] = 200
    assert_eq!(data.median_duration(false), Some(200));
}

#[test]
fn test_project_timing_data_median_even_count() {
    let _guard = test_guard!();
    let mut data = ProjectTimingData::default();
    data.add_sample(100, true);
    data.add_sample(300, true);
    data.add_sample(200, true);
    data.add_sample(400, true);

    // Median of [100, 200, 300, 400] = (200 + 300) / 2 = 250
    assert_eq!(data.median_duration(true), Some(250));
}

#[test]
fn test_project_timing_data_median_empty() {
    let _guard = test_guard!();
    let data = ProjectTimingData::default();
    assert_eq!(data.median_duration(false), None);
    assert_eq!(data.median_duration(true), None);
}

#[test]
fn test_project_timing_data_speedup_ratio() {
    let _guard = test_guard!();
    let mut data = ProjectTimingData::default();
    // Local takes 1000ms
    data.add_sample(1000, false);
    // Remote takes 500ms
    data.add_sample(500, true);

    // Speedup = local / remote = 1000 / 500 = 2.0
    assert_eq!(data.speedup_ratio(), Some(2.0));
}

#[test]
fn test_project_timing_data_speedup_no_data() {
    let _guard = test_guard!();
    let mut data = ProjectTimingData::default();
    data.add_sample(1000, false);

    // No remote data, can't compute speedup
    assert_eq!(data.speedup_ratio(), None);
}

#[test]
fn test_project_timing_data_sample_truncation() {
    let _guard = test_guard!();
    let mut data = ProjectTimingData::default();

    // Add more than MAX_TIMING_SAMPLES
    for i in 0..25 {
        data.add_sample(i * 100, false);
    }

    // Should be capped at MAX_TIMING_SAMPLES (20)
    assert_eq!(data.local_samples.len(), MAX_TIMING_SAMPLES);
    // First sample should be removed (FIFO)
    assert_eq!(data.local_samples[0].duration_ms, 500); // Started at 0, removed 0-4
}

#[test]
fn test_timing_history_key() {
    let _guard = test_guard!();
    let key = TimingHistory::key("my_project", Some(CompilationKind::CargoTest));
    assert!(key.contains("my_project"));
    assert!(key.contains("CargoTest"));

    let key_unknown = TimingHistory::key("project2", None);
    assert!(key_unknown.contains("project2"));
    assert!(key_unknown.contains("Unknown"));
}

#[test]
fn test_timing_history_record_and_get() {
    let _guard = test_guard!();
    let mut history = TimingHistory::default();

    history.record("proj1", Some(CompilationKind::CargoBuild), 1000, true);
    history.record("proj1", Some(CompilationKind::CargoBuild), 800, true);

    let data = history.get("proj1", Some(CompilationKind::CargoBuild));
    assert!(data.is_some());
    let data = data.unwrap();
    assert_eq!(data.remote_samples.len(), 2);
    assert_eq!(data.median_duration(true), Some(900)); // (800 + 1000) / 2

    // Different kind should be separate
    let data2 = history.get("proj1", Some(CompilationKind::CargoTest));
    assert!(data2.is_none());
}

#[test]
fn test_timing_history_serialization() {
    let _guard = test_guard!();
    let mut history = TimingHistory::default();
    history.record("proj", Some(CompilationKind::CargoCheck), 500, false);
    history.record("proj", Some(CompilationKind::CargoCheck), 250, true);

    let json = serde_json::to_string(&history).unwrap();
    let loaded: TimingHistory = serde_json::from_str(&json).unwrap();

    let data = loaded
        .get("proj", Some(CompilationKind::CargoCheck))
        .unwrap();
    assert_eq!(data.local_samples.len(), 1);
    assert_eq!(data.remote_samples.len(), 1);
}

// ========================================================================
// t18 — record_build_timing lock-scope discipline. Verify the write
// guard is dropped BEFORE save_to_disk, so other readers/writers
// aren't blocked on disk I/O.
// ========================================================================

#[test]
fn test_record_build_timing_releases_guard_before_disk_io() {
    // Verify: between cache.write()-release and cache.read()-acquire
    // there is no overlap — i.e., another thread can acquire a
    // read lock while save_to_disk is in flight.
    //
    // Property tested indirectly: spawn many threads each calling
    // record_build_timing concurrently. With the OLD code (save
    // inside the write guard), high contention would serialize all
    // calls behind a 5-10ms disk write per thread. With the NEW
    // code, only the in-memory mutation serializes; disk writes
    // parallelize. A wallclock cap detects the regression.
    //
    // Per-thread project keys are uniquely prefixed so the test
    // doesn't depend on cache-clearing (which would race with other
    // tests sharing the global cache).
    let _guard = test_guard!();
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::thread;
    use std::time::{Duration, Instant};

    let unique = format!(
        "t18-conc-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
    );

    let n_threads = 8;
    let calls_per_thread = 5;
    let started = Arc::new(AtomicUsize::new(0));
    let mut handles = Vec::new();
    let t0 = Instant::now();
    for t in 0..n_threads {
        let started = Arc::clone(&started);
        let unique = unique.clone();
        handles.push(thread::spawn(move || {
            for i in 0..calls_per_thread {
                started.fetch_add(1, Ordering::Relaxed);
                let project = format!("{unique}-{t}-{i}");
                record_build_timing(
                    &project,
                    Some(CompilationKind::CargoBuild),
                    100 + (i as u64),
                    true,
                );
            }
        }));
    }
    for h in handles {
        h.join().expect("worker thread panicked");
    }
    let elapsed = t0.elapsed();
    let total_calls = n_threads * calls_per_thread;
    assert_eq!(
        started.load(Ordering::Relaxed),
        total_calls,
        "all threads should have started"
    );
    // Wallclock cap: 8 threads × 5 calls × 50ms (slow disk fsync)
    // = 2000ms WORST case if serial. Allow 4s for very slow CI.
    // A regression to "save inside the write guard" would dominate
    // the wallclock at scale; this cap catches the worst regressions.
    assert!(
        elapsed < Duration::from_millis(4000),
        "{total_calls} concurrent record_build_timing calls took {elapsed:?} (expected <4s)"
    );
}

#[test]
fn test_record_build_timing_in_memory_state_survives_disk_failure() {
    // Even if save_to_disk fails (e.g., disk full, permission denied),
    // the in-memory cache MUST contain the recorded sample. The lock
    // is dropped before the I/O, so I/O failure can't corrupt the
    // cache state.
    //
    // Uses a unique key (PID + nanosecond timestamp) so the assertion
    // doesn't depend on cache-clearing — which would race with other
    // tests sharing the global cache.
    let _guard = test_guard!();

    let unique = format!(
        "t18-disk-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
    );

    record_build_timing(&unique, Some(CompilationKind::CargoBuild), 1234, true);

    let history = timing_cache().read().expect("read");
    let entry = history.get(&unique, Some(CompilationKind::CargoBuild));
    assert!(
        entry.is_some(),
        "in-memory entry for key {unique:?} must be present even if disk write failed"
    );
    let data = entry.unwrap();
    assert!(
        !data.remote_samples.is_empty(),
        "at least one remote sample recorded"
    );
    // We're the only writer for this unique key, so the last sample
    // must be the one we recorded.
    assert_eq!(
        data.remote_samples.last().unwrap().duration_ms,
        1234,
        "recorded duration matches the call"
    );
}

// ========================================================================
// WS1.4: Tests for spawn_blocking wrappers (bd-3s1j)
// ========================================================================

#[tokio::test]
async fn test_spawn_blocking_load_with_valid_file() {
    let _guard = test_guard!();
    // Create a temp directory with a timing history file
    let temp_dir = tempfile::tempdir().unwrap();
    let history_path = temp_dir.path().join("timing_history.json");

    // Create valid timing data
    let mut history = TimingHistory::default();
    history.record(
        "test-project",
        Some(CompilationKind::CargoBuild),
        1000,
        false,
    );
    let json = serde_json::to_string_pretty(&history).unwrap();
    std::fs::write(&history_path, json).unwrap();

    // Load via spawn_blocking (simulating what we do in production)
    let path = history_path.clone();
    let loaded = tokio::task::spawn_blocking(move || {
        // In production we use timing_history_path(), here we test the pattern
        std::fs::read_to_string(&path)
            .ok()
            .and_then(|content| serde_json::from_str::<TimingHistory>(&content).ok())
            .unwrap_or_default()
    })
    .await
    .unwrap();

    // Verify data loaded correctly
    let data = loaded.get("test-project", Some(CompilationKind::CargoBuild));
    assert!(data.is_some());
    assert_eq!(data.unwrap().local_samples.len(), 1);
}

#[tokio::test]
async fn test_spawn_blocking_load_missing_file() {
    let _guard = test_guard!();
    let temp_dir = tempfile::tempdir().unwrap();
    let missing_path = temp_dir.path().join("nonexistent.json");

    let loaded = tokio::task::spawn_blocking(move || {
        std::fs::read_to_string(&missing_path)
            .ok()
            .and_then(|content| serde_json::from_str::<TimingHistory>(&content).ok())
            .unwrap_or_default()
    })
    .await
    .unwrap();

    // Should return default (empty history)
    assert!(loaded.entries.is_empty());
}

#[tokio::test]
async fn test_spawn_blocking_load_corrupt_json() {
    let _guard = test_guard!();
    let temp_dir = tempfile::tempdir().unwrap();
    let corrupt_path = temp_dir.path().join("corrupt.json");
    std::fs::write(&corrupt_path, "not valid json {{{").unwrap();

    let loaded = tokio::task::spawn_blocking(move || {
        std::fs::read_to_string(&corrupt_path)
            .ok()
            .and_then(|content| serde_json::from_str::<TimingHistory>(&content).ok())
            .unwrap_or_default()
    })
    .await
    .unwrap();

    // Should return default on corrupt data (graceful degradation)
    assert!(loaded.entries.is_empty());
}

#[tokio::test]
async fn test_spawn_blocking_save_creates_file() {
    let _guard = test_guard!();
    let temp_dir = tempfile::tempdir().unwrap();
    let save_path = temp_dir.path().join("saved_history.json");

    let mut history = TimingHistory::default();
    history.record(
        "saved-project",
        Some(CompilationKind::CargoTest),
        2000,
        true,
    );

    let path = save_path.clone();
    tokio::task::spawn_blocking(move || {
        let content = serde_json::to_string_pretty(&history).unwrap();
        std::fs::write(&path, content).unwrap();
    })
    .await
    .unwrap();

    // Verify file was created and has correct content
    assert!(save_path.exists());
    let content = std::fs::read_to_string(&save_path).unwrap();
    let loaded: TimingHistory = serde_json::from_str(&content).unwrap();
    let data = loaded.get("saved-project", Some(CompilationKind::CargoTest));
    assert!(data.is_some());
    assert_eq!(data.unwrap().remote_samples.len(), 1);
}

#[tokio::test]
async fn test_spawn_blocking_timeout_protection() {
    let _guard = test_guard!();
    // Verify spawn_blocking completes within reasonable time (not deadlocked)
    let result = tokio::time::timeout(
        std::time::Duration::from_secs(5),
        tokio::task::spawn_blocking(|| {
            let history = TimingHistory::default();
            // Simulate some work
            std::thread::sleep(std::time::Duration::from_millis(10));
            history
        }),
    )
    .await;

    assert!(
        result.is_ok(),
        "spawn_blocking should complete within 5s timeout"
    );
}

#[tokio::test]
async fn test_spawn_blocking_concurrent_loads() {
    let _guard = test_guard!();
    let temp_dir = tempfile::tempdir().unwrap();
    let history_path = temp_dir.path().join("concurrent.json");

    // Create test file
    let mut history = TimingHistory::default();
    history.record("concurrent", Some(CompilationKind::CargoBuild), 500, false);
    std::fs::write(&history_path, serde_json::to_string(&history).unwrap()).unwrap();

    // Spawn 5 concurrent loads
    let mut handles = Vec::new();
    for _ in 0..5 {
        let path = history_path.clone();
        handles.push(tokio::task::spawn_blocking(move || {
            std::fs::read_to_string(&path)
                .ok()
                .and_then(|c| serde_json::from_str::<TimingHistory>(&c).ok())
                .unwrap_or_default()
        }));
    }

    // All should complete without deadlock
    for handle in handles {
        let loaded = handle.await.unwrap();
        assert!(
            loaded
                .get("concurrent", Some(CompilationKind::CargoBuild))
                .is_some()
        );
    }
}

#[tokio::test]
async fn test_spawn_blocking_concurrent_saves() {
    let _guard = test_guard!();
    let temp_dir = tempfile::tempdir().unwrap();

    // Spawn 5 concurrent saves to different files
    let mut handles = Vec::new();
    for i in 0..5 {
        let path = temp_dir.path().join(format!("save_{}.json", i));
        let mut history = TimingHistory::default();
        history.record(
            &format!("project-{}", i),
            Some(CompilationKind::CargoBuild),
            100 * i as u64,
            false,
        );

        handles.push(tokio::task::spawn_blocking(move || {
            let content = serde_json::to_string(&history).unwrap();
            std::fs::write(&path, content).unwrap();
            path
        }));
    }

    // All should complete and files should exist
    for handle in handles {
        let path = handle.await.unwrap();
        assert!(path.exists(), "File should be created: {:?}", path);
    }
}

#[tokio::test]
async fn test_spawn_blocking_performance_budget() {
    let _guard = test_guard!();
    let temp_dir = tempfile::tempdir().unwrap();
    let history_path = temp_dir.path().join("perf_test.json");

    // Create a reasonably sized history file
    let mut history = TimingHistory::default();
    for i in 0..10 {
        history.record(
            &format!("project-{}", i),
            Some(CompilationKind::CargoBuild),
            1000 + i * 100,
            false,
        );
        history.record(
            &format!("project-{}", i),
            Some(CompilationKind::CargoBuild),
            800 + i * 50,
            true,
        );
    }
    std::fs::write(
        &history_path,
        serde_json::to_string_pretty(&history).unwrap(),
    )
    .unwrap();

    // Measure load time
    let load_path = history_path.clone();
    let start = std::time::Instant::now();
    let _loaded = tokio::task::spawn_blocking(move || {
        std::fs::read_to_string(&load_path)
            .ok()
            .and_then(|c| serde_json::from_str::<TimingHistory>(&c).ok())
            .unwrap_or_default()
    })
    .await
    .unwrap();
    let load_duration = start.elapsed();

    // Measure save time
    let save_path = temp_dir.path().join("perf_save.json");
    let start = std::time::Instant::now();
    tokio::task::spawn_blocking(move || {
        let content = serde_json::to_string_pretty(&history).unwrap();
        std::fs::write(&save_path, content).unwrap();
    })
    .await
    .unwrap();
    let save_duration = start.elapsed();

    let total = load_duration + save_duration;

    // Log timings for diagnostics (visible with --nocapture)
    eprintln!("Performance test results:");
    eprintln!("  Load: {:?}", load_duration);
    eprintln!("  Save: {:?}", save_duration);
    eprintln!("  Total: {:?}", total);

    // Total should be well under 2ms budget (leaving room for the rest of the 5ms)
    // On fast SSDs this is typically <1ms, but we allow up to 50ms for slow CI
    assert!(
        total < std::time::Duration::from_millis(50),
        "Load+save took {:?}, should be <50ms for CI compatibility",
        total
    );
}

// ── Multi-root sync manifest & partial failure tests (bd-vvmd.2.3 AC5) ──

#[test]
fn test_source_intent_topology_root_has_no_trailing_separator() {
    let _guard = test_guard!();
    let (directory, policy) = topology_tempdir();
    let project_root = directory.path().to_path_buf();
    let plan = build_sync_closure_plan(
        std::slice::from_ref(&project_root),
        &project_root,
        "topology-root-hash",
        &policy,
    );
    assert_eq!(plan.len(), 1);
    assert!(plan[0].is_primary);
    assert_eq!(
        plan[0].remote_root,
        policy.canonical_root().to_str().unwrap()
    );
    let target = format!("{}/.rch-target", plan[0].remote_root);
    assert_eq!(
        target,
        policy
            .canonical_root()
            .join(".rch-target")
            .to_str()
            .unwrap()
    );

    // A child still maps beneath the same root, rather than losing its suffix.
    let child = project_root.join("nested");
    std::fs::create_dir(&child).unwrap();
    let child_plan = build_sync_closure_plan(
        std::slice::from_ref(&child),
        &child,
        "topology-child-hash",
        &policy,
    );
    assert_eq!(child_plan.len(), 1);
    assert_eq!(child_plan[0].remote_root, child.to_str().unwrap());
}

#[test]
fn test_build_sync_closure_manifest_deterministic_entries() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("project");
    let dep_a = temp_dir.path().join("dep_a");
    let dep_b = temp_dir.path().join("dep_b");
    std::fs::create_dir_all(&project_root).expect("create project root");
    std::fs::create_dir_all(&dep_a).expect("create dep_a");
    std::fs::create_dir_all(&dep_b).expect("create dep_b");

    let plan = build_sync_closure_plan(
        &[dep_b.clone(), dep_a.clone(), project_root.clone()],
        &project_root,
        "abc123",
        &policy,
    );
    let manifest_a = build_sync_closure_manifest(&plan, &project_root);
    let manifest_b = build_sync_closure_manifest(&plan, &project_root);

    // Entries must be identical (order, roots, hashes, primary flag).
    assert_eq!(
        manifest_a.entries, manifest_b.entries,
        "manifest entries should be deterministic for the same plan"
    );
    assert_eq!(
        manifest_a.schema_version, manifest_b.schema_version,
        "schema version must be stable"
    );
    assert_eq!(
        manifest_a.project_root, manifest_b.project_root,
        "project root must be stable"
    );
}

#[test]
fn test_build_sync_closure_manifest_schema_version_stable() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("project");
    std::fs::create_dir_all(&project_root).expect("create project root");

    let plan = build_sync_closure_plan(
        std::slice::from_ref(&project_root),
        &project_root,
        "deadbeef",
        &policy,
    );
    let manifest = build_sync_closure_manifest(&plan, &project_root);

    assert_eq!(
        manifest.schema_version, "rch.sync_closure_manifest.v2",
        "schema version must match the documented v2 contract"
    );
}

#[test]
fn test_build_sync_closure_manifest_entries_faithfully_represent_plan() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("project");
    let dep = temp_dir.path().join("dep");
    std::fs::create_dir_all(&project_root).expect("create project root");
    std::fs::create_dir_all(&dep).expect("create dep");

    let plan = build_sync_closure_plan(
        &[dep.clone(), project_root.clone()],
        &project_root,
        "cafe0001",
        &policy,
    );
    let manifest = build_sync_closure_manifest(&plan, &project_root);

    assert_eq!(
        manifest.entries.len(),
        plan.len(),
        "manifest must have one entry per plan entry"
    );
    for (idx, (plan_entry, manifest_entry)) in plan.iter().zip(manifest.entries.iter()).enumerate()
    {
        assert_eq!(manifest_entry.order, idx + 1, "order must be 1-indexed");
        assert_eq!(
            manifest_entry.local_root,
            plan_entry.local_root.to_string_lossy().to_string()
        );
        assert_eq!(manifest_entry.remote_root, plan_entry.remote_root);
        assert_eq!(manifest_entry.project_id, plan_entry.project_id);
        assert_eq!(manifest_entry.root_hash, plan_entry.root_hash);
        assert_eq!(manifest_entry.is_primary, plan_entry.is_primary);
    }
}

#[test]
fn test_build_sync_closure_manifest_primary_root_present() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("project");
    let dep = temp_dir.path().join("dep");
    std::fs::create_dir_all(&project_root).expect("create project root");
    std::fs::create_dir_all(&dep).expect("create dep");

    let plan = build_sync_closure_plan(
        &[dep.clone(), project_root.clone()],
        &project_root,
        "primary_hash",
        &policy,
    );
    let manifest = build_sync_closure_manifest(&plan, &project_root);

    let primary_entries: Vec<_> = manifest.entries.iter().filter(|e| e.is_primary).collect();
    assert_eq!(
        primary_entries.len(),
        1,
        "exactly one manifest entry should be the primary root"
    );
    assert_eq!(
        primary_entries[0].root_hash, "primary_hash",
        "primary entry must carry the project-level hash"
    );
}

#[test]
fn test_build_sync_closure_plan_adds_primary_even_when_absent_from_roots() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("project");
    let dep = temp_dir.path().join("dep");
    std::fs::create_dir_all(&project_root).expect("create project root");
    std::fs::create_dir_all(&dep).expect("create dep");

    // Deliberately omit project_root from sync_roots list.
    let plan = build_sync_closure_plan(
        std::slice::from_ref(&dep),
        &project_root,
        "hash_auto_add",
        &policy,
    );
    let has_primary = plan.iter().any(|e| e.is_primary);
    assert!(
        has_primary,
        "primary root must be auto-added to plan even when not in sync_roots"
    );
    let primary = plan.iter().find(|e| e.is_primary).unwrap();
    assert_eq!(primary.root_hash, "hash_auto_add");
}

#[test]
fn test_sync_root_outcome_diagnostic_counting() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("project");
    let dep_a = temp_dir.path().join("dep_a");
    let dep_b = temp_dir.path().join("dep_b");
    let dep_c = temp_dir.path().join("dep_c");
    std::fs::create_dir_all(&project_root).expect("create project root");
    std::fs::create_dir_all(&dep_a).expect("create dep_a");
    std::fs::create_dir_all(&dep_b).expect("create dep_b");
    std::fs::create_dir_all(&dep_c).expect("create dep_c");

    let plan = build_sync_closure_plan(
        &[
            dep_a.clone(),
            dep_b.clone(),
            dep_c.clone(),
            project_root.clone(),
        ],
        &project_root,
        "diag_hash",
        &policy,
    );

    // Simulate outcomes: primary synced, one dep synced, one skipped, one failed.
    let outcomes: Vec<(&SyncClosurePlanEntry, SyncRootOutcome)> = plan
        .iter()
        .map(|entry| {
            let outcome = if entry.is_primary || entry.local_root.ends_with("dep_a") {
                SyncRootOutcome::Synced
            } else if entry.local_root.ends_with("dep_b") {
                SyncRootOutcome::Skipped {
                    reason: "size too small".to_string(),
                }
            } else {
                SyncRootOutcome::Failed {
                    error: "rsync timeout".to_string(),
                }
            };
            (entry, outcome)
        })
        .collect();

    let failed_count = outcomes
        .iter()
        .filter(|(_, o)| !matches!(o, SyncRootOutcome::Synced))
        .count();
    assert_eq!(
        failed_count, 2,
        "skipped + failed should count as non-synced"
    );

    let synced_count = outcomes
        .iter()
        .filter(|(_, o)| matches!(o, SyncRootOutcome::Synced))
        .count();
    assert_eq!(synced_count, 2, "primary + dep_a should be synced");
}

#[test]
fn test_build_sync_closure_manifest_serializes_to_json() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("project");
    let dep = temp_dir.path().join("dep");
    std::fs::create_dir_all(&project_root).expect("create project root");
    std::fs::create_dir_all(&dep).expect("create dep");

    let plan = build_sync_closure_plan(
        &[dep.clone(), project_root.clone()],
        &project_root,
        "serial_hash",
        &policy,
    );
    let manifest = build_sync_closure_manifest(&plan, &project_root);

    let json = serde_json::to_string_pretty(&manifest).expect("manifest should serialize to JSON");
    assert!(
        json.contains("rch.sync_closure_manifest.v2"),
        "JSON must contain schema_version"
    );
    assert!(
        json.contains("serial_hash"),
        "JSON must contain the primary root hash"
    );
    assert!(
        json.contains("\"is_primary\": true"),
        "JSON must contain primary flag"
    );

    // Roundtrip: deserialize should also work for consumers.
    let parsed: serde_json::Value =
        serde_json::from_str(&json).expect("manifest JSON should be valid");
    let entries = parsed["entries"]
        .as_array()
        .expect("entries should be an array");
    assert_eq!(entries.len(), plan.len());
}

// ── Closure topology validation tests (bd-vvmd.2.3 AC3) ──

#[test]
fn test_is_within_sync_topology_accepts_canonical_root() {
    let _guard = test_guard!();
    let policy = rch_common::path_topology::PathTopologyPolicy::default();
    let path = PathBuf::from("/data/projects/my_project");
    assert!(
        is_within_sync_topology(&path, &policy),
        "paths under /data/projects should be accepted"
    );
}

#[test]
fn test_is_within_sync_topology_accepts_alias_root() {
    let _guard = test_guard!();
    let policy = rch_common::path_topology::PathTopologyPolicy::default();
    let path = PathBuf::from("/dp/my_project");
    assert!(
        is_within_sync_topology(&path, &policy),
        "paths under /dp alias should be accepted"
    );
}

#[test]
fn test_is_within_sync_topology_rejects_outside_paths() {
    let _guard = test_guard!();
    let policy = rch_common::path_topology::PathTopologyPolicy::default();
    assert!(
        !is_within_sync_topology(Path::new("/tmp/evil"), &policy),
        "/tmp paths should be rejected"
    );
    assert!(
        !is_within_sync_topology(Path::new("/home/user/project"), &policy),
        "/home paths should be rejected"
    );
    assert!(
        !is_within_sync_topology(Path::new("/var/lib/data"), &policy),
        "/var paths should be rejected"
    );
}

#[test]
fn test_build_sync_closure_plan_excludes_out_of_topology_roots() {
    let _guard = test_guard!();
    // Use paths under /data/projects (canonical root) for valid paths,
    // and a /tmp path for the invalid one. Since these dirs may not exist
    // on the test runner, the canonicalization will fall back to the raw
    // path, which is exactly what we want to test.
    let project_root = PathBuf::from("/data/projects/test_proj");
    let valid_dep = PathBuf::from("/data/projects/valid_dep");
    let invalid_dep = PathBuf::from("/tmp/not_allowed");

    let plan = build_sync_closure_plan(
        &[valid_dep.clone(), invalid_dep.clone(), project_root.clone()],
        &project_root,
        "topo_hash",
        &PathTopologyPolicy::default(),
    );

    // The plan should contain the primary root and valid dep, but NOT the invalid dep.
    let plan_paths: Vec<_> = plan.iter().map(|e| &e.local_root).collect();
    assert!(
        plan_paths
            .iter()
            .any(|p| p.starts_with("/data/projects/test_proj")),
        "primary root must be in plan"
    );
    assert!(
        plan_paths
            .iter()
            .any(|p| p.starts_with("/data/projects/valid_dep")),
        "valid dependency root must be in plan"
    );
    assert!(
        !plan_paths.iter().any(|p| p.starts_with("/tmp")),
        "out-of-topology dependency must be excluded from plan"
    );
}

#[test]
fn test_build_sync_closure_plan_topology_filter_preserves_primary() {
    let _guard = test_guard!();
    // Even with all deps invalid, the primary root must survive.
    let project_root = PathBuf::from("/data/projects/primary_proj");
    let bad_dep_a = PathBuf::from("/home/user/dep_a");
    let bad_dep_b = PathBuf::from("/var/lib/dep_b");

    let plan = build_sync_closure_plan(
        &[bad_dep_a, bad_dep_b],
        &project_root,
        "lonely_hash",
        &PathTopologyPolicy::default(),
    );

    assert_eq!(plan.len(), 1, "only the primary root should remain");
    assert!(
        plan[0].is_primary,
        "surviving entry must be the primary root"
    );
}

// ── bd-3jjc.6: canonicalize_sync_root_for_plan() edge cases ─────────

#[test]
fn test_canonicalize_existing_path() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let dir = temp_dir.path().join("real_dir");
    std::fs::create_dir_all(&dir).expect("create dir");

    let result = canonicalize_sync_root_for_plan(&dir, &policy);
    // Should be a canonical absolute path containing the dir name.
    assert!(result.is_absolute());
    assert!(
        result.to_string_lossy().contains("real_dir"),
        "canonicalized path should contain dir name: {}",
        result.display()
    );
}

#[test]
fn test_canonicalize_nonexistent_path() {
    let _guard = test_guard!();
    let path = PathBuf::from("/data/projects/does_not_exist_xyz_12345");
    let policy = rch_common::path_topology::PathTopologyPolicy::default();
    let result = canonicalize_sync_root_for_plan(&path, &policy);
    // Fallback: should return original path since normalize and canonicalize both fail.
    assert_eq!(result, path);
}

#[test]
fn test_canonicalize_trailing_slash() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let dir = temp_dir.path().join("trail");
    std::fs::create_dir_all(&dir).expect("create dir");

    let with_trailing = PathBuf::from(format!("{}/", dir.display()));
    let without_trailing = canonicalize_sync_root_for_plan(&dir, &policy);
    let with_result = canonicalize_sync_root_for_plan(&with_trailing, &policy);
    // Both should resolve to the same canonical path.
    assert_eq!(with_result, without_trailing);
}

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

    let (temp_dir, policy) = topology_tempdir();
    let real_dir = temp_dir.path().join("real");
    let link_dir = temp_dir.path().join("link");
    std::fs::create_dir_all(&real_dir).expect("create real dir");
    symlink(&real_dir, &link_dir).expect("create symlink");

    let from_real = canonicalize_sync_root_for_plan(&real_dir, &policy);
    let from_link = canonicalize_sync_root_for_plan(&link_dir, &policy);
    assert_eq!(
        from_real, from_link,
        "symlink and real path should canonicalize to the same path"
    );
}

#[test]
fn test_canonicalize_dp_alias() {
    let _guard = test_guard!();
    // /dp is an alias for /data/projects on the maintainer's dev host.
    // This test is environment-dependent: only meaningful when BOTH the
    // alias and the canonical target exist and the concrete subdir
    // (`remote_compilation_helper`) is present under each.
    //
    // Using `Path::exists()` alone isn't robust — CI runners occasionally
    // have a `/dp` inode that doesn't resolve through `canonicalize`
    // (broken or partially-populated mount). Guard on canonicalization
    // success of the actual input path instead, and skip otherwise.
    let dp_path = PathBuf::from("/dp/remote_compilation_helper");
    let canonical_expected = PathBuf::from("/data/projects/remote_compilation_helper");
    let (Ok(dp_canonical), true) = (std::fs::canonicalize(&dp_path), canonical_expected.exists())
    else {
        return;
    };
    if dp_canonical != canonical_expected {
        // Alias target exists but points somewhere else on this host —
        // nothing to assert here.
        return;
    }

    let policy = rch_common::path_topology::PathTopologyPolicy::default();
    let result = canonicalize_sync_root_for_plan(&dp_path, &policy);
    assert_eq!(
        result, canonical_expected,
        "/dp alias should resolve to /data/projects"
    );
}

// ── bd-3jjc.7: is_within_sync_topology() edge cases ─────────────────

#[test]
fn test_topology_deeply_nested_accepted() {
    let _guard = test_guard!();
    let policy = rch_common::path_topology::PathTopologyPolicy::default();
    let path = PathBuf::from("/data/projects/a/b/c/d/e/f/g");
    assert!(
        is_within_sync_topology(&path, &policy),
        "deeply nested /data/projects subpaths should be accepted"
    );
}

#[test]
fn test_topology_exact_root_match() {
    let _guard = test_guard!();
    let policy = rch_common::path_topology::PathTopologyPolicy::default();
    // The exact root (/data/projects itself) should be accepted.
    assert!(
        is_within_sync_topology(Path::new("/data/projects"), &policy),
        "/data/projects itself should be accepted"
    );
    assert!(
        is_within_sync_topology(Path::new("/dp"), &policy),
        "/dp itself should be accepted"
    );
}

#[test]
fn test_topology_parent_of_root_rejected() {
    let _guard = test_guard!();
    let policy = rch_common::path_topology::PathTopologyPolicy::default();
    assert!(
        !is_within_sync_topology(Path::new("/data"), &policy),
        "/data (parent of root) should be rejected"
    );
}

#[test]
fn test_topology_prefix_collision_rejected() {
    let _guard = test_guard!();
    let policy = rch_common::path_topology::PathTopologyPolicy::default();
    // /data/projects_extra starts with /data/projects as a string prefix
    // but is NOT a child path. Path::starts_with uses component-based matching.
    assert!(
        !is_within_sync_topology(Path::new("/data/projects_extra"), &policy),
        "/data/projects_extra should be rejected (not a child path)"
    );
}

#[test]
fn test_topology_empty_path_rejected() {
    let _guard = test_guard!();
    let policy = rch_common::path_topology::PathTopologyPolicy::default();
    assert!(
        !is_within_sync_topology(Path::new(""), &policy),
        "empty path should be rejected"
    );
}

#[test]
fn test_topology_root_slash_rejected() {
    let _guard = test_guard!();
    let policy = rch_common::path_topology::PathTopologyPolicy::default();
    assert!(
        !is_within_sync_topology(Path::new("/"), &policy),
        "root path (/) should be rejected"
    );
}

// ── bd-3jjc.8: build_sync_closure_plan() edge cases ─────────────────

#[test]
fn test_plan_empty_sync_roots() {
    let _guard = test_guard!();
    let project_root = PathBuf::from("/data/projects/solo_project");
    let plan = build_sync_closure_plan(
        &[],
        &project_root,
        "solo_hash",
        &PathTopologyPolicy::default(),
    );
    assert_eq!(
        plan.len(),
        1,
        "empty sync_roots should produce single primary entry"
    );
    assert!(plan[0].is_primary);
    assert_eq!(plan[0].root_hash, "solo_hash");
}

#[test]
fn test_plan_primary_is_only_root() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("only");
    std::fs::create_dir_all(&project_root).expect("create dir");

    let plan = build_sync_closure_plan(
        std::slice::from_ref(&project_root),
        &project_root,
        "only_hash",
        &policy,
    );
    assert_eq!(plan.len(), 1);
    assert!(plan[0].is_primary);
    assert_eq!(plan[0].root_hash, "only_hash");
}

#[test]
fn test_plan_large_root_set() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("main_proj");
    std::fs::create_dir_all(&project_root).expect("create main");

    let mut roots = Vec::new();
    for i in 0..100u32 {
        let dep = temp_dir.path().join(format!("dep_{i:04}"));
        std::fs::create_dir_all(&dep).expect("create dep");
        roots.push(dep);
    }
    roots.push(project_root.clone());

    let start = std::time::Instant::now();
    let plan = build_sync_closure_plan(&roots, &project_root, "large_hash", &policy);
    let elapsed = start.elapsed();

    // 100 deps + 1 primary (deduped) = 101 entries.
    assert_eq!(plan.len(), 101);
    assert!(
        elapsed.as_millis() < 500,
        "plan build took too long: {elapsed:?}"
    );

    // Verify lexicographic ordering.
    for window in plan.windows(2) {
        assert!(
            window[0].local_root <= window[1].local_root,
            "plan should be lexicographically ordered: {} > {}",
            window[0].local_root.display(),
            window[1].local_root.display(),
        );
    }
}

#[test]
fn test_plan_duplicate_roots_deduped() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("proj");
    let dep = temp_dir.path().join("dep");
    std::fs::create_dir_all(&project_root).expect("create proj");
    std::fs::create_dir_all(&dep).expect("create dep");

    let plan = build_sync_closure_plan(
        &[dep.clone(), dep.clone(), dep.clone(), project_root.clone()],
        &project_root,
        "dup_hash",
        &policy,
    );

    // dep appears 3 times in input but should be deduped to 1 entry + primary = 2.
    assert_eq!(plan.len(), 2, "duplicate roots should be deduped");
}

#[test]
fn test_plan_primary_via_dp_alias_canonical() {
    let _guard = test_guard!();
    // Verify /dp/X resolves to /data/projects/X — but only when the
    // maintainer's alias layout is actually present. `Path::exists`
    // alone is too permissive (some CI images have a broken `/dp`
    // node that `canonicalize` refuses).
    let dp_path = PathBuf::from("/dp/remote_compilation_helper");
    let Ok(canonical) = std::fs::canonicalize(&dp_path) else {
        return;
    };
    let plan = build_sync_closure_plan(&[], &dp_path, "dp_hash", &PathTopologyPolicy::default());
    assert_eq!(plan.len(), 1);
    assert!(plan[0].is_primary);
    assert_eq!(
        plan[0].local_root, canonical,
        "primary via /dp alias should canonicalize to the alias target"
    );
    assert_eq!(
        plan[0].remote_root, "/data/projects/remote_compilation_helper",
        "remote root should stay in worker canonical topology"
    );
}

#[test]
fn test_build_sync_closure_plan_maps_alias_target_roots_to_worker_canonical_topology() {
    let _guard = test_guard!();
    if let Ok(local_projects_root) = std::fs::canonicalize("/dp") {
        let project_root = local_projects_root.join("frankenterm");
        let dep_root = local_projects_root.join("frankentui");

        let plan = build_sync_closure_plan(
            &[dep_root.clone(), project_root.clone()],
            &project_root,
            "mapped_hash",
            &PathTopologyPolicy::default(),
        );

        assert!(
            plan.iter().any(|entry| entry.local_root == project_root
                && entry.remote_root == "/data/projects/frankenterm"),
            "primary root should map back to worker canonical topology"
        );
        assert!(
            plan.iter().any(|entry| entry.local_root == dep_root
                && entry.remote_root == "/data/projects/frankentui"),
            "dependency root should map back to worker canonical topology"
        );
    }
}

#[test]
fn test_plan_entry_ordering_is_lexicographic() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("proj");
    let dep_z = temp_dir.path().join("z_dep");
    let dep_a = temp_dir.path().join("a_dep");
    let dep_m = temp_dir.path().join("m_dep");
    std::fs::create_dir_all(&project_root).expect("create proj");
    std::fs::create_dir_all(&dep_z).expect("create dep_z");
    std::fs::create_dir_all(&dep_a).expect("create dep_a");
    std::fs::create_dir_all(&dep_m).expect("create dep_m");

    let plan = build_sync_closure_plan(
        &[dep_z, dep_a, dep_m, project_root.clone()],
        &project_root,
        "order_hash",
        &policy,
    );

    for window in plan.windows(2) {
        assert!(
            window[0].local_root <= window[1].local_root,
            "entries must be lexicographically sorted"
        );
    }
}

// ── bd-3jjc.9: build_sync_closure_manifest() edge cases ─────────────

#[test]
fn test_manifest_empty_plan() {
    let _guard = test_guard!();
    let project_root = PathBuf::from("/data/projects/empty_proj");
    let manifest = build_sync_closure_manifest(&[], &project_root);
    assert_eq!(manifest.entries.len(), 0);
    assert_eq!(manifest.project_root, "/data/projects/empty_proj");
    assert_eq!(manifest.schema_version, "rch.sync_closure_manifest.v2");
}

#[test]
fn test_manifest_generated_at_is_recent() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("proj");
    std::fs::create_dir_all(&project_root).expect("create proj");

    let before_ms = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;
    let plan = build_sync_closure_plan(
        std::slice::from_ref(&project_root),
        &project_root,
        "ts_hash",
        &policy,
    );
    let manifest = build_sync_closure_manifest(&plan, &project_root);
    let after_ms = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;

    assert!(
        manifest.generated_at_unix_ms >= before_ms,
        "generated_at should be >= start time"
    );
    assert!(
        manifest.generated_at_unix_ms <= after_ms,
        "generated_at should be <= end time"
    );
}

#[test]
fn test_manifest_order_field_sequential() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let project_root = temp_dir.path().join("proj");
    std::fs::create_dir_all(&project_root).expect("create proj");

    let mut roots = Vec::new();
    for i in 0..10u32 {
        let dep = temp_dir.path().join(format!("dep_{i:02}"));
        std::fs::create_dir_all(&dep).expect("create dep");
        roots.push(dep);
    }
    roots.push(project_root.clone());

    let plan = build_sync_closure_plan(&roots, &project_root, "seq_hash", &policy);
    let manifest = build_sync_closure_manifest(&plan, &project_root);

    // Order field should be 1-indexed and sequential.
    for (idx, entry) in manifest.entries.iter().enumerate() {
        assert_eq!(
            entry.order,
            idx + 1,
            "order should be 1-indexed sequential, got {} at position {}",
            entry.order,
            idx
        );
    }
}

#[test]
fn test_manifest_unicode_paths() {
    let _guard = test_guard!();
    // Use synthetic plan entries with unicode paths.
    let entries = vec![SyncClosurePlanEntry {
        local_root: PathBuf::from("/data/projects/日本語プロジェクト"),
        remote_root: "/data/projects/日本語プロジェクト".to_string(),
        project_id: "日本語".to_string(),
        root_hash: "unicode_hash".to_string(),
        is_primary: true,
        mode: SyncClosureMode::Full,
    }];
    let manifest =
        build_sync_closure_manifest(&entries, Path::new("/data/projects/日本語プロジェクト"));
    assert_eq!(manifest.entries.len(), 1);
    assert!(manifest.entries[0].local_root.contains("日本語"));

    // Verify JSON serialization handles unicode.
    let json = serde_json::to_string(&manifest).expect("should serialize unicode");
    assert!(json.contains("日本語"));
}

#[test]
fn test_manifest_long_strings() {
    let _guard = test_guard!();
    let long_id = "x".repeat(10_000);
    let long_hash = "h".repeat(10_000);
    let entries = vec![SyncClosurePlanEntry {
        local_root: PathBuf::from("/data/projects/long_test"),
        remote_root: "/data/projects/long_test".to_string(),
        project_id: long_id.clone(),
        root_hash: long_hash.clone(),
        is_primary: true,
        mode: SyncClosureMode::Full,
    }];
    let manifest = build_sync_closure_manifest(&entries, Path::new("/data/projects/long_test"));
    assert_eq!(
        manifest.entries[0].project_id, long_id,
        "project_id should not be truncated"
    );
    assert_eq!(
        manifest.entries[0].root_hash, long_hash,
        "root_hash should not be truncated"
    );
}

// ── bd-3jjc.10: SyncRootOutcome variant coverage ────────────────────

#[test]
fn test_sync_root_outcome_all_synced() {
    let _guard = test_guard!();
    let outcomes: Vec<SyncRootOutcome> = (0..5).map(|_| SyncRootOutcome::Synced).collect();
    let non_synced = outcomes
        .iter()
        .filter(|o| !matches!(o, SyncRootOutcome::Synced))
        .count();
    assert_eq!(non_synced, 0);
}

#[test]
fn test_sync_root_outcome_all_failed() {
    let _guard = test_guard!();
    let outcomes: Vec<SyncRootOutcome> = (0..3)
        .map(|i| SyncRootOutcome::Failed {
            error: format!("error_{i}"),
        })
        .collect();
    let failed_count = outcomes
        .iter()
        .filter(|o| matches!(o, SyncRootOutcome::Failed { .. }))
        .count();
    assert_eq!(failed_count, 3);

    // Verify error messages are preserved.
    let errors: Vec<&str> = outcomes
        .iter()
        .filter_map(|o| match o {
            SyncRootOutcome::Failed { error } => Some(error.as_str()),
            _ => None,
        })
        .collect();
    assert_eq!(errors, vec!["error_0", "error_1", "error_2"]);
}

#[test]
fn test_sync_root_outcome_all_skipped() {
    let _guard = test_guard!();
    let outcomes: Vec<SyncRootOutcome> = (0..4)
        .map(|i| SyncRootOutcome::Skipped {
            reason: format!("reason_{i}"),
        })
        .collect();
    let skipped_count = outcomes
        .iter()
        .filter(|o| matches!(o, SyncRootOutcome::Skipped { .. }))
        .count();
    assert_eq!(skipped_count, 4);
}

#[test]
fn test_sync_root_outcome_empty_collection() {
    let _guard = test_guard!();
    let outcomes: Vec<SyncRootOutcome> = vec![];
    let synced = outcomes
        .iter()
        .filter(|o| matches!(o, SyncRootOutcome::Synced))
        .count();
    let failed = outcomes
        .iter()
        .filter(|o| matches!(o, SyncRootOutcome::Failed { .. }))
        .count();
    let skipped = outcomes
        .iter()
        .filter(|o| matches!(o, SyncRootOutcome::Skipped { .. }))
        .count();
    assert_eq!(synced, 0);
    assert_eq!(failed, 0);
    assert_eq!(skipped, 0);
}

#[test]
fn test_sync_root_outcome_mixed_with_reasons() {
    let _guard = test_guard!();
    let outcomes = [
        SyncRootOutcome::Synced,
        SyncRootOutcome::Synced,
        SyncRootOutcome::Skipped {
            reason: "stale".to_string(),
        },
        SyncRootOutcome::Failed {
            error: "timeout".to_string(),
        },
        SyncRootOutcome::Skipped {
            reason: "denied".to_string(),
        },
    ];

    let synced = outcomes
        .iter()
        .filter(|o| matches!(o, SyncRootOutcome::Synced))
        .count();
    let failed = outcomes
        .iter()
        .filter(|o| matches!(o, SyncRootOutcome::Failed { .. }))
        .count();
    let skipped = outcomes
        .iter()
        .filter(|o| matches!(o, SyncRootOutcome::Skipped { .. }))
        .count();

    assert_eq!(synced, 2);
    assert_eq!(failed, 1);
    assert_eq!(skipped, 2);

    // Verify reason extraction.
    let skip_reasons: Vec<&str> = outcomes
        .iter()
        .filter_map(|o| match o {
            SyncRootOutcome::Skipped { reason } => Some(reason.as_str()),
            _ => None,
        })
        .collect();
    assert_eq!(skip_reasons, vec!["stale", "denied"]);

    let error_msgs: Vec<&str> = outcomes
        .iter()
        .filter_map(|o| match o {
            SyncRootOutcome::Failed { error } => Some(error.as_str()),
            _ => None,
        })
        .collect();
    assert_eq!(error_msgs, vec!["timeout"]);
}

// ── bd-3jjc.13: E2E sync closure plan + manifest generation ─────────

#[test]
fn test_e2e_sync_closure_plan_and_manifest() {
    let _guard = test_guard!();
    let (temp_dir, policy) = topology_tempdir();
    let primary = temp_dir.path().join("primary_project");
    let dep_a = temp_dir.path().join("dep_a");
    let dep_b = temp_dir.path().join("dep_b");
    std::fs::create_dir_all(&primary).expect("create primary");
    std::fs::create_dir_all(&dep_a).expect("create dep_a");
    std::fs::create_dir_all(&dep_b).expect("create dep_b");

    // Step 2: Build plan with valid deps + an out-of-topology sentinel
    // that must be filtered. Pick any path that lies outside the
    // `topology_tempdir` root — `/var/empty` exists on Linux & macOS
    // and is not under our scratch area.
    let out_of_topology = PathBuf::from("/var/empty/invalid_dep");
    let plan = build_sync_closure_plan(
        &[
            primary.clone(),
            dep_a.clone(),
            dep_b.clone(),
            out_of_topology.clone(),
        ],
        &primary,
        "e2e_hash",
        &policy,
    );

    // Step 3: 3 entries (primary, dep_a, dep_b), out-of-topology excluded.
    assert_eq!(
        plan.len(),
        3,
        "plan should have 3 entries (primary + 2 deps), got {}",
        plan.len()
    );
    let out_of_topology_str = out_of_topology.to_string_lossy().to_string();
    assert!(
        !plan
            .iter()
            .any(|e| e.local_root.to_string_lossy() == out_of_topology_str),
        "out-of-topology dep should be excluded by topology filter"
    );

    // Step 4: Verify lexicographic ordering.
    for window in plan.windows(2) {
        assert!(
            window[0].local_root <= window[1].local_root,
            "plan entries should be lexicographically sorted"
        );
    }

    // Step 5: Primary entry has is_primary=true with correct hash.
    let primary_entry = plan
        .iter()
        .find(|e| e.is_primary)
        .expect("primary must exist");
    assert_eq!(primary_entry.root_hash, "e2e_hash");
    let non_primary: Vec<_> = plan.iter().filter(|e| !e.is_primary).collect();
    assert_eq!(non_primary.len(), 2, "should have 2 non-primary entries");

    // Step 6-7: Generate manifest.
    let before_ms = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;
    let manifest = build_sync_closure_manifest(&plan, &primary);
    let after_ms = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;

    assert_eq!(manifest.schema_version, "rch.sync_closure_manifest.v2");
    assert_eq!(manifest.entries.len(), 3);
    assert!(manifest.generated_at_unix_ms >= before_ms);
    assert!(manifest.generated_at_unix_ms <= after_ms);

    // Step 8-9: JSON roundtrip.
    let json = serde_json::to_string_pretty(&manifest).expect("serialize");
    let parsed: serde_json::Value = serde_json::from_str(&json).expect("parse");
    let entries = parsed["entries"].as_array().expect("entries array");
    assert_eq!(entries.len(), 3);

    // Step 10: Verify order fields are 1-indexed sequential.
    for (idx, entry) in manifest.entries.iter().enumerate() {
        assert_eq!(entry.order, idx + 1, "order should be 1-indexed sequential");
        assert_eq!(entry.is_primary, plan[idx].is_primary);
        assert_eq!(entry.root_hash, plan[idx].root_hash);
    }
}

// ── bd-3jjc.15: E2E topology validation with symlinks ───────────────

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

    let (temp_dir, policy) = topology_tempdir();
    let valid_root = temp_dir.path().join("valid_root");
    let valid_sub = valid_root.join("sub");
    std::fs::create_dir_all(&valid_sub).expect("create valid_root/sub");

    let primary = temp_dir.path().join("primary");
    std::fs::create_dir_all(&primary).expect("create primary");

    // Create symlink alias within the same tempdir.
    let alias_link = temp_dir.path().join("alias_for_valid");
    symlink(&valid_root, &alias_link).expect("create symlink");

    // Build plan with mixed valid/invalid/alias paths. Rejection paths
    // are deliberately under system roots that won't overlap with the
    // `topology_tempdir` scratch area (which itself lives under
    // `/tmp/.tmpXXXX` on Linux or `/var/folders/...` on macOS).
    let reject_a = PathBuf::from("/etc/rch_should_reject");
    let reject_b = PathBuf::from("/usr/local/fake_project");
    let reject_c = PathBuf::from("/opt/fake_thing");
    let plan = build_sync_closure_plan(
        &[
            valid_root.clone(),
            alias_link.clone(), // should dedup with valid_root
            reject_a.clone(),
            reject_b.clone(),
            reject_c.clone(),
            primary.clone(),
        ],
        &primary,
        "topo_e2e_hash",
        &policy,
    );

    // Should contain primary + valid_root (deduped with alias) = 2 entries.
    assert_eq!(
        plan.len(),
        2,
        "plan should have 2 entries (primary + deduped valid_root), got {}",
        plan.len()
    );

    // Verify the three explicit rejection paths were excluded.
    let reject_strs: Vec<String> = [reject_a, reject_b, reject_c]
        .iter()
        .map(|p| p.to_string_lossy().to_string())
        .collect();
    for entry in &plan {
        let path_str = entry.local_root.to_string_lossy().to_string();
        assert!(
            !reject_strs.contains(&path_str),
            "out-of-topology path should not appear in plan: {}",
            path_str
        );
    }

    // Verify alias was deduplicated (only one entry for valid_root).
    let valid_canonical = std::fs::canonicalize(&valid_root).expect("canonicalize");
    let matching_entries = plan
        .iter()
        .filter(|e| {
            std::fs::canonicalize(&e.local_root)
                .map(|c| c == valid_canonical)
                .unwrap_or(false)
        })
        .count();
    assert_eq!(
        matching_entries, 1,
        "symlink alias should be deduplicated with canonical path"
    );

    // Verify primary is present.
    assert!(
        plan.iter().any(|e| e.is_primary),
        "primary root must always be in plan"
    );
}

// =========================================================================
// Regression suite: Classification timing budget & edge cases (bd-vvmd.2.9)
// =========================================================================

/// Verify classification completes well within the 5ms panic threshold for
/// compilation commands, and within 1ms for non-compilation commands.
/// This acts as a regression gate: if any code change blows the budget,
/// this test catches it.
#[test]
fn test_classification_timing_budget_non_compilation() {
    let _guard = test_guard!();
    let non_compilation_cmds = [
        "ls -la",
        "pwd",
        "git status",
        "echo hello world",
        "cat Cargo.toml",
        "npm install",
        "python main.py",
        "docker build -t myapp .",
        "mkdir -p build",
        "rm -rf target/",
    ];

    for cmd in non_compilation_cmds {
        let start = std::time::Instant::now();
        for _ in 0..100 {
            let _ = classify_command(cmd);
        }
        let elapsed = start.elapsed();
        let per_call_us = elapsed.as_micros() / 100;
        // Non-compilation: budget <1ms, panic at 5ms
        // We check the median is under 1ms (1000us)
        assert!(
            per_call_us < 1000,
            "Non-compilation command {:?} exceeded 1ms budget: {}us per call",
            cmd,
            per_call_us
        );
    }
}

#[test]
fn test_classification_timing_budget_compilation() {
    let _guard = test_guard!();
    let compilation_cmds = [
        "cargo build --release",
        "cargo test --workspace",
        "cargo clippy --all-targets",
        "gcc -c main.c -o main.o",
        "make -j8",
        "bun test",
        "rustc main.rs",
        "ninja -j4",
    ];

    for cmd in compilation_cmds {
        let start = std::time::Instant::now();
        for _ in 0..100 {
            let _ = classify_command(cmd);
        }
        let elapsed = start.elapsed();
        let per_call_us = elapsed.as_micros() / 100;
        // Compilation: budget <5ms, panic at 10ms
        assert!(
            per_call_us < 5000,
            "Compilation command {:?} exceeded 5ms budget: {}us per call",
            cmd,
            per_call_us
        );
    }
}

/// Verify that process_hook handles compilation commands correctly when
/// daemon is absent — the classification MUST work, and the hook MUST
/// fail-open to allow local execution.
#[tokio::test]
async fn test_hook_classification_fail_open_all_compilation_kinds() {
    let _lock = test_lock().lock().await;
    mock::set_mock_enabled_override(Some(false));

    let compilation_commands = [
        ("cargo build --release", "CargoBuild"),
        ("cargo test --workspace", "CargoTest"),
        ("cargo check --all-targets", "CargoCheck"),
        ("cargo clippy", "CargoClippy"),
        ("cargo doc --no-deps", "CargoDoc"),
        ("cargo run", "CargoRun"),
        ("cargo bench", "CargoBench"),
        ("cargo nextest run", "CargoNextest"),
        ("bun test", "BunTest"),
        ("bun typecheck", "BunTypecheck"),
    ];

    for (cmd, label) in compilation_commands {
        let input = HookInput {
            tool_name: "Bash".to_string(),
            tool_input: ToolInput {
                command: cmd.to_string(),
                description: None,
            },
            session_id: None,
        };

        let output = process_hook(input).await;
        assert!(
            output.is_allow(),
            "Hook should fail-open for {} ({}) when daemon absent",
            label,
            cmd
        );
    }

    mock::set_mock_enabled_override(None);
}

/// Verify that non-compilation commands pass through the hook immediately
/// (are allowed without daemon interaction).
#[tokio::test]
async fn test_hook_non_compilation_passthrough() {
    let non_compilation = [
        "ls -la",
        "git status",
        "cargo fmt --check",
        "cargo install ripgrep",
        "bun install",
        "bun run dev",
        "echo hello",
        "cat Cargo.toml",
    ];

    for cmd in non_compilation {
        let input = HookInput {
            tool_name: "Bash".to_string(),
            tool_input: ToolInput {
                command: cmd.to_string(),
                description: None,
            },
            session_id: None,
        };

        let output = process_hook(input).await;
        assert!(
            output.is_allow(),
            "Non-compilation command {:?} should pass through the hook (Allow)",
            cmd
        );
    }
}

/// Verify that non-Bash tool invocations are always allowed.
#[tokio::test]
async fn test_hook_non_bash_tools_always_allowed() {
    let tools = ["Read", "Write", "Edit", "Glob", "Grep", "WebSearch"];

    for tool in tools {
        let input = HookInput {
            tool_name: tool.to_string(),
            tool_input: ToolInput {
                command: "cargo build".to_string(), // Even compilation keyword
                description: None,
            },
            session_id: None,
        };

        let output = process_hook(input).await;
        assert!(
            output.is_allow(),
            "Non-Bash tool {:?} should always be allowed, even with compilation keyword",
            tool
        );
    }
}

/// Verify that classify_command_detailed produces valid structured output
/// for every tier decision path, enabling structured logging.
#[test]
fn test_structured_log_output_per_tier() {
    let _guard = test_guard!();

    // Tier 0 reject: empty command
    let d = classify_command_detailed("");
    assert_eq!(d.tiers.len(), 1);
    assert_eq!(d.tiers[0].tier, 0);
    assert_eq!(d.tiers[0].decision, TierDecision::Reject);
    assert!(!d.tiers[0].reason.is_empty());

    // Tier 1 reject: input redirect (transforms input; still declined).
    // Note: `cargo build | tee log` is now ACCEPTED (issue #24 benign pager).
    let d = classify_command_detailed("cargo build < input.txt");
    assert!(
        d.tiers
            .iter()
            .any(|t| t.tier == 1 && t.decision == TierDecision::Reject)
    );

    // Tier 2 reject: no keyword
    let d = classify_command_detailed("ls -la");
    assert!(
        d.tiers
            .iter()
            .any(|t| t.tier == 2 && t.decision == TierDecision::Reject)
    );

    // Tier 3 reject: never-intercept
    let d = classify_command_detailed("cargo install serde");
    assert!(
        d.tiers
            .iter()
            .any(|t| t.tier == 3 && t.decision == TierDecision::Reject)
    );

    // Tier 4 pass: full classification
    let d = classify_command_detailed("cargo build --release");
    assert!(
        d.tiers
            .iter()
            .any(|t| t.tier == 4 && t.decision == TierDecision::Pass)
    );
    assert!(d.classification.is_compilation);
    assert!(d.classification.confidence > 0.0);
    assert!(d.classification.kind.is_some());

    // Tier 4 reject: keyword present but no matching pattern
    let d = classify_command_detailed("cargo tree");
    assert!(
        d.tiers
            .iter()
            .any(|t| t.tier == 4 && t.decision == TierDecision::Reject)
    );
}

/// Issue #63: `--job` commands must yield the toolchain the remote cargo will
/// actually use — an explicit env-style `RUSTUP_TOOLCHAIN=` assignment or a
/// `cargo +<tc>` selector — so the daemon's component gate never sees
/// `<unknown>` for a pinned clippy run.
#[test]
fn rustup_toolchain_from_command_tokens_parses_env_prefix_and_selector() {
    let tokens = |cmd: &str| -> Vec<String> { cmd.split_whitespace().map(String::from).collect() };

    // The exact shape from issue #63.
    assert_eq!(
        rustup_toolchain_from_command_tokens(&tokens(
            "env RCH_CARGO_WRAPPER_BYPASS=1 RUSTUP_TOOLCHAIN=nightly-2026-08-25 \
             CARGO_TARGET_DIR=/data/p/.rch-target cargo clippy --workspace -- -D warnings"
        )),
        Some("nightly-2026-08-25".to_string())
    );
    // Bare env-assignment prefix (no `env`).
    assert_eq!(
        rustup_toolchain_from_command_tokens(&tokens("RUSTUP_TOOLCHAIN=stable cargo clippy")),
        Some("stable".to_string())
    );
    // `cargo +<tc>` selector, including a path-qualified cargo.
    assert_eq!(
        rustup_toolchain_from_command_tokens(&tokens("cargo +nightly-2026-08-25 clippy")),
        Some("nightly-2026-08-25".to_string())
    );
    assert_eq!(
        rustup_toolchain_from_command_tokens(&tokens("/usr/bin/cargo +beta build")),
        Some("beta".to_string())
    );
    // A `+`-prefixed token NOT following cargo is an argument, not a selector.
    assert_eq!(
        rustup_toolchain_from_command_tokens(&tokens("cargo build --features +weird")),
        None
    );
    assert_eq!(
        rustup_toolchain_from_command_tokens(&tokens("go build ./...")),
        None
    );
    // Empty assignment is ignored.
    assert_eq!(
        rustup_toolchain_from_command_tokens(&tokens("RUSTUP_TOOLCHAIN= cargo clippy")),
        None
    );
}

/// Issue #63(c): explicit `--job` admission counts as strict-remote once
/// remote options are exhausted — the refusal must be typed (retryable exit
/// code + `refused` envelope), never a silent local build.
#[test]
fn job_admission_exhausted_is_a_typed_retryable_refusal() {
    assert!(strict_remote_for_exhausted_admission(false, true));
    assert!(strict_remote_for_exhausted_admission(true, false));
    assert!(strict_remote_for_exhausted_admission(true, true));
    assert!(!strict_remote_for_exhausted_admission(false, false));

    // The job-refusal reason routes through the retryable refusal lane.
    let reason = "job admission exhausted: no admissible workers: missing_toolchain_component=14";
    assert!(remote_required_refusal_is_retryable(reason));
    let summary = remote_required_refusal_summary(reason);
    assert!(summary.contains("refusing local fallback"));
    assert!(summary.contains("retryable"));
}

/// Issue #62: only an SSH timeout whose post-timeout remote group-kill is
/// UNVERIFIED triggers the worker quarantine; verified/no-op cleanups and
/// unrelated errors never do.
#[test]
fn ssh_timeout_unverified_cleanup_detection() {
    use crate::transfer::{RemoteTimeoutCleanup, SshCommandTimedOut};

    let unverified: anyhow::Error = SshCommandTimedOut {
        timeout: std::time::Duration::from_secs(1800),
        cleanup: RemoteTimeoutCleanup::Unverified,
        detail: "kill probe timed out".to_string(),
        evidence: None,
    }
    .into();
    // Also through an added context layer, as the pipeline surfaces it.
    let unverified = unverified.context("remote execution failed");
    assert!(ssh_timeout_with_unverified_cleanup(&unverified).is_some());
    // The fail-closed classifier still recognizes the typed error text.
    assert!(is_ssh_command_timeout_error(&unverified));

    let verified: anyhow::Error = SshCommandTimedOut {
        timeout: std::time::Duration::from_secs(1800),
        cleanup: RemoteTimeoutCleanup::Verified,
        detail: "remote process group SIGKILLed and verified dead".to_string(),
        evidence: None,
    }
    .into();
    assert!(ssh_timeout_with_unverified_cleanup(&verified).is_none());
    assert!(is_ssh_command_timeout_error(&verified));

    let unrelated = anyhow::anyhow!("some other failure");
    assert!(ssh_timeout_with_unverified_cleanup(&unrelated).is_none());
}

#[test]
fn project_topology_local_reason_admits_projects_under_the_canonical_root_only() {
    let root = tempfile::tempdir().unwrap();
    let canonical = root.path().canonicalize().unwrap();
    let inside = canonical.join("repo");
    std::fs::create_dir_all(&inside).unwrap();
    let outside_parent = tempfile::tempdir().unwrap();
    let outside = outside_parent.path().canonicalize().unwrap().join("repo");
    std::fs::create_dir_all(&outside).unwrap();
    let policy = PathTopologyPolicy::new(canonical.clone(), canonical.clone());

    assert_eq!(project_topology_local_reason(&policy, &inside), None);

    let reason = project_topology_local_reason(&policy, &outside)
        .expect("a project outside the canonical root must run locally");
    assert!(reason.contains("outside canonical root"), "{reason}");
    assert!(reason.contains(&outside.display().to_string()), "{reason}");
    assert!(
        reason.contains("canonical_root"),
        "the reason names the fix: {reason}"
    );
}

/// bd-1nhd: the fast path may only answer what `process_hook` answers with a
/// plain allow, and must hand everything else to the full path.
#[tokio::test]
async fn fast_passthrough_answers_only_what_process_hook_plainly_allows() {
    let request = |tool: &str, command: &str| {
        serde_json::json!({
            "session_id": "s",
            "hook_event_name": "PreToolUse",
            "tool_name": tool,
            "tool_input": {"command": command},
        })
        .to_string()
    };
    for command in [
        "ls -la",
        "git status",
        "cd /tmp && ls",
        r#"br comments add x "cargo test -p rchd""#,
        "echo cargo build",
    ] {
        let input = request("Bash", command);
        assert!(super::fast_passthrough_allows(&input), "{command}");
        let output = process_hook(serde_json::from_str(&input).unwrap()).await;
        assert!(
            matches!(output, HookOutput::Allow(_)),
            "fast path allowed what process_hook would not: {command} -> {output:?}"
        );
    }
    assert!(super::fast_passthrough_allows(""));
    assert!(super::fast_passthrough_allows(&request(
        "Read",
        "cargo build"
    )));
    for command in [
        "cargo build --release",
        "cargo test -p rch",
        "cargo build | tee build.log",
        "cargo build > build.log 2>&1 &",
    ] {
        assert!(
            !super::fast_passthrough_allows(&request("Bash", command)),
            "{command} must reach the full path"
        );
    }
    assert!(!super::fast_passthrough_allows("{not json"));
}