trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! Unit tests for the post-merge cleanup engine (#7275).
//!
//! Every test drives the `Gh`, `Git` and `ClaimEnder` seams with a scripted
//! fake, so nothing here touches the network, a live `gh`, or a real worktree.

use std::cell::RefCell;
use std::path::{Path, PathBuf};

use super::CleanupRequest;
use super::driver::{ClaimEnder, CmdOut, Gh, Git, Landing};
use super::plan::{
    AGENT_BRANCH_PREFIX, MergeCommit, PrView, StepLine, StepStatus, agent_branches_at,
    merge_refusal, parse_worktree_list, worktree_targets,
};
use super::registry::{CleanupRegistry, OpenedPr};
use super::{ClaimOwnership, CleanupReport, DirtProbe, HolderState, run_with};

/// #8301: every test runs with its claim double as the ownership answer.
async fn run<G: Gh, T: Git, C: ClaimEnder + ClaimOwnership>(
    gh: &G,
    git: &T,
    claims: &C,
    landing: &dyn Landing,
    probe_dirt: DirtProbe<'_>,
    req: &CleanupRequest,
) -> CleanupReport {
    run_with(gh, git, claims, landing, probe_dirt, req, claims).await
}
use crate::session_manager::DirtyWorktree;
use crate::session_manager::worktree_reclaim::BranchPrState;
use crate::session_manager::worktree_reclaim_pr_match::worktree_reclaim_pr_match_tests::FakeProbe;

// ── fakes ────────────────────────────────────────────────────────────────

/// A seam that answers by argv-substring match, in registration order.
struct Scripted {
    /// (substring that must appear in the joined argv, response).
    routes: Vec<(String, CmdOut)>,
    /// Every argv this fake was asked to run, joined, in order.
    seen: RefCell<Vec<String>>,
    /// #8489: trees a routed `git worktree remove` succeeded on.
    removed: RefCell<Vec<PathBuf>>,
}

impl Scripted {
    fn new() -> Self {
        Self {
            routes: Vec::new(),
            seen: RefCell::new(Vec::new()),
            removed: RefCell::new(Vec::new()),
        }
    }

    fn on(mut self, needle: &str, stdout: &str) -> Self {
        self.routes.push((
            needle.to_string(),
            CmdOut {
                success: true,
                stdout: stdout.to_string(),
                stderr: String::new(),
            },
        ));
        self
    }

    fn on_fail(mut self, needle: &str, stderr: &str) -> Self {
        self.routes.push((
            needle.to_string(),
            CmdOut {
                success: false,
                stdout: String::new(),
                stderr: stderr.to_string(),
            },
        ));
        self
    }

    fn answer(&self, joined: &str) -> anyhow::Result<CmdOut> {
        self.seen.borrow_mut().push(joined.to_string());
        for (needle, out) in &self.routes {
            if joined.contains(needle.as_str()) {
                return Ok(out.clone());
            }
        }
        // An unrouted call is a scripting mistake, not a command failure —
        // failing loudly here is what keeps a test from silently exercising a
        // path it never meant to.
        anyhow::bail!("Scripted: no route for `{joined}`")
    }

    fn calls(&self) -> Vec<String> {
        self.seen.borrow().clone()
    }
}

impl Gh for Scripted {
    fn run(&self, args: &[String]) -> anyhow::Result<CmdOut> {
        self.answer(&format!("gh {}", args.join(" ")))
    }
}

impl Scripted {
    /// The head this fake's own worktree listing gives `dir` (#7275 round 4).
    ///
    /// Why: the pre-removal re-read asks each WORKTREE for its HEAD, and a
    /// substring route cannot tell two trees apart. Answering out of the
    /// porcelain listing this fake already serves keeps the two consistent by
    /// construction — a real `git` cannot disagree with itself either — and
    /// costs no route per test.
    fn head_of(&self, dir: &Path) -> anyhow::Result<CmdOut> {
        let listing = self
            .routes
            .iter()
            .find(|(needle, _)| needle.contains("worktree list"))
            .map(|(_, out)| out.stdout.clone())
            .unwrap_or_default();
        let head = parse_worktree_list(&listing)
            .into_iter()
            .find(|e| e.path == dir)
            .map(|e| e.head);
        match head {
            Some(h) => Ok(CmdOut {
                success: true,
                stdout: format!("{h}\n"),
                stderr: String::new(),
            }),
            None => anyhow::bail!("Scripted: no worktree listed at {}", dir.display()),
        }
    }
}

impl Git for Scripted {
    fn run(&self, dir: &Path, args: &[String]) -> anyhow::Result<CmdOut> {
        let joined = format!("git {}", args.join(" "));
        if args == ["rev-parse", "HEAD"] {
            self.seen.borrow_mut().push(joined);
            return self.head_of(dir);
        }
        // #8489: real git refuses `-D` on a branch a remaining worktree holds.
        if let [verb, flag, branch] = args
            && verb == "branch"
            && flag == "-D"
            && let Some(holder) = self.holder_of(branch)
        {
            self.seen.borrow_mut().push(joined);
            return Ok(CmdOut {
                success: false,
                stdout: String::new(),
                stderr: format!(
                    "error: cannot delete branch '{branch}' used by worktree at '{}'",
                    holder.display()
                ),
            });
        }
        let out = self.answer(&joined)?;
        if out.success
            && let [verb, sub, path] = args
            && verb == "worktree"
            && sub == "remove"
        {
            self.removed.borrow_mut().push(PathBuf::from(path));
        }
        Ok(out)
    }
}

impl Scripted {
    /// The listed, not-yet-removed tree that has `branch` checked out (#8489).
    fn holder_of(&self, branch: &str) -> Option<PathBuf> {
        let listing = self
            .routes
            .iter()
            .find(|(needle, out)| needle.contains("worktree list") && out.success)
            .map(|(_, out)| out.stdout.clone())
            .unwrap_or_default();
        let removed = self.removed.borrow();
        parse_worktree_list(&listing)
            .into_iter()
            .find(|e| e.branch.as_deref() == Some(branch) && !removed.contains(&e.path))
            .map(|e| e.path)
    }
}

/// A [`ClaimEnder`] with a pinned answer and a record of what it ended.
struct FakeClaims {
    /// Session ids every path is reported as claimed by.
    holders: Vec<String>,
    /// Ids passed to `end_claim`, in order.
    ended: std::sync::Mutex<Vec<String>>,
    /// #8301: holders reported as LIVE foreign sessions; every other one ended.
    live: Vec<String>,
    /// #8301: the ownership gate's refusal, or `None` to permit.
    refuse: Option<String>,
    /// #8301: when non-empty, each path's own holders; unlisted paths are
    /// unclaimed. Empty means every path answers `holders`.
    per_path: Vec<(PathBuf, Vec<String>)>,
    /// #8301: `claims_on` answers popped in order before the fallback above.
    claims_script: std::sync::Mutex<std::collections::VecDeque<Result<Vec<String>, String>>>,
    /// #8301: `tree_gate` answers popped in order before `refuse`.
    gate_script: std::sync::Mutex<std::collections::VecDeque<Result<(), String>>>,
    /// #7771: `release_stale_lock`'s refusal, or `None` to release.
    lock_refuse: Option<String>,
    /// #7771: paths `release_stale_lock` was asked about, in order.
    released: std::sync::Mutex<Vec<PathBuf>>,
}

impl FakeClaims {
    fn none() -> Self {
        Self::held(&[])
    }

    fn held_by(id: &str) -> Self {
        Self::held(&[id])
    }

    fn held(ids: &[&str]) -> Self {
        Self {
            holders: ids.iter().map(|s| (*s).to_string()).collect(),
            ended: std::sync::Mutex::new(Vec::new()),
            live: Vec::new(),
            refuse: None,
            per_path: Vec::new(),
            claims_script: Default::default(),
            gate_script: Default::default(),
            lock_refuse: None,
            released: Default::default(),
        }
    }

    /// #8301: script the next `claims_on` answers.
    fn claims_then(self, answers: Vec<Result<Vec<String>, String>>) -> Self {
        *self.claims_script.lock().expect("claims script") = answers.into();
        self
    }

    /// #8301: script the next `tree_gate` answers.
    fn gate_then(self, answers: Vec<Result<(), String>>) -> Self {
        *self.gate_script.lock().expect("gate script") = answers.into();
        self
    }
}

#[async_trait::async_trait]
impl ClaimEnder for FakeClaims {
    async fn claims_on(&self, path: &Path) -> anyhow::Result<Vec<String>> {
        if let Some(next) = self
            .claims_script
            .lock()
            .expect("claims script")
            .pop_front()
        {
            return next.map_err(|e| anyhow::anyhow!(e));
        }
        if self.per_path.is_empty() {
            return Ok(self.holders.clone());
        }
        Ok(self
            .per_path
            .iter()
            .find(|(p, _)| p == path)
            .map(|(_, ids)| ids.clone())
            .unwrap_or_default())
    }
    async fn end_claim(&self, id: &str) -> anyhow::Result<()> {
        self.ended.lock().expect("claims lock").push(id.to_string());
        Ok(())
    }
}

#[async_trait::async_trait]
impl ClaimOwnership for FakeClaims {
    async fn holder_state(&self, id: &str) -> HolderState {
        if self.live.iter().any(|l| l == id) {
            HolderState::Live
        } else {
            HolderState::Ended
        }
    }
    async fn tree_gate(&self, _path: &Path) -> Result<(), String> {
        if let Some(next) = self.gate_script.lock().expect("gate script").pop_front() {
            return next;
        }
        self.refuse.clone().map_or(Ok(()), Err)
    }
    async fn release_stale_lock(&self, path: &Path) -> Result<(), String> {
        self.released
            .lock()
            .expect("released lock")
            .push(path.to_path_buf());
        self.lock_refuse.clone().map_or(Ok(()), Err)
    }
}

// ── fixtures ─────────────────────────────────────────────────────────────

const HEAD_OID: &str = "abc1234def5678000000000000000000000000aa";
const BRANCH: &str = "feat/7275-post-merge-cleanup";
const TREE: &str = "/repo/.claude/worktrees/agent-aa11";

fn root() -> PathBuf {
    PathBuf::from("/repo")
}

fn req(dry_run: bool) -> CleanupRequest {
    CleanupRequest {
        pr: 7275,
        repo: Some("bobmatnyc/trusty-tools".to_string()),
        repo_root: root(),
        dry_run,
        head_only: false,
    }
}

fn merged_json() -> String {
    format!(
        "{{\"state\":\"MERGED\",\"headRefName\":\"{BRANCH}\",\"headRefOid\":\"{HEAD_OID}\",\
         \"mergeCommit\":{{\"oid\":\"9999888877776666555544443333222211110000\"}}}}"
    )
}

fn worktree_listing() -> String {
    format!(
        "worktree /repo\nHEAD 1111111111111111111111111111111111111111\nbranch refs/heads/main\n\n\
         worktree {TREE}\nHEAD {HEAD_OID}\nbranch refs/heads/{BRANCH}\n\n"
    )
}

fn branch_listing() -> String {
    format!(
        "main 1111111111111111111111111111111111111111\n\
         {BRANCH} {HEAD_OID}\n\
         {AGENT_BRANCH_PREFIX}aa11 {HEAD_OID}\n\
         {AGENT_BRANCH_PREFIX}bb22 2222222222222222222222222222222222222222\n"
    )
}

/// #7275 round 2: the argv the repo/checkout reconciliation runs, and the
/// answer that AGREES with `req()`'s stated repository.
const ORIGIN_QUERY: &str = "config --get remote.origin.url";
/// See [`ORIGIN_QUERY`]. An https URL, so no test reads an SSH alias table.
const ORIGIN_URL: &str = "https://github.com/bobmatnyc/trusty-tools.git\n";

/// A `gh` fake that reports the PR merged.
fn gh_merged() -> Scripted {
    Scripted::new().on("gh pr view 7275", &merged_json())
}

/// A `git` fake with the remote branch present and one matching worktree.
fn git_full() -> Scripted {
    Scripted::new()
        .on(ORIGIN_QUERY, ORIGIN_URL)
        .on(
            "git ls-remote",
            &format!("{HEAD_OID}\trefs/heads/{BRANCH}\n"),
        )
        .on("git push origin --delete", "")
        .on("git worktree list", &worktree_listing())
        .on("git worktree remove", "")
        .on("git branch --format", &branch_listing())
        .on("git branch -D", "")
        .on("git worktree prune", "")
        .on("git fetch --prune", "")
}

/// Nothing in any worktree is dirty.
fn clean(_p: &Path) -> Option<DirtyWorktree> {
    None
}

/// A [`Landing`] over #7267's own `LandingProbe` fake (#7275 round 3).
///
/// Why: what is under test is the ahead-count gate's POLICY, not `gh`. Routing
/// through `driver::resolve_merged_pr` means these tests run the production
/// seed-then-ladder body rather than a second copy of it, and the probe below
/// is the fake `worktree_reclaim_pr_match_tests` already drives.
struct FakeLanding {
    /// The scripted merged-pull-request answers.
    probe: FakeProbe,
}

impl FakeLanding {
    /// A probe that knows of no pull request at all — the refusal arm.
    fn nothing_merged() -> Self {
        Self {
            probe: FakeProbe::default(),
        }
    }

    /// A probe reporting `branch` as carried by a MERGED pull request.
    fn merged(branch: &str, pr: u64) -> Self {
        Self {
            probe: FakeProbe::default().with_head(branch, BranchPrState::Merged { pr }),
        }
    }
}

impl Landing for FakeLanding {
    fn merged_pr(
        &self,
        repo_root: &Path,
        worktree: &Path,
        branch: Option<&str>,
        exact: Option<u64>,
    ) -> Option<u64> {
        super::driver::resolve_merged_pr(&self.probe, repo_root, worktree, branch, exact)
    }
}

/// A dirt probe reporting `n` commits ahead of the upstream and nothing else —
/// exactly what `inspect_dirt` says about every squash-merged worktree.
fn ahead_by(n: usize) -> impl Fn(&Path) -> Option<DirtyWorktree> {
    move |p: &Path| {
        Some(DirtyWorktree {
            path: p.to_path_buf(),
            reason: format!("0 uncommitted/untracked file(s), {n} unpushed commit(s)"),
            dirty_files: 0,
            unpushed_commits: n,
        })
    }
}

fn rendered(lines: &[StepLine]) -> String {
    lines
        .iter()
        .map(StepLine::render)
        .collect::<Vec<_>>()
        .join("\n")
}

// ── step 1: the merge gate ───────────────────────────────────────────────

#[test]
fn merge_refusal_accepts_merged() {
    let view = PrView {
        state: "MERGED".to_string(),
        head_ref_name: BRANCH.to_string(),
        head_ref_oid: HEAD_OID.to_string(),
        merge_commit: Some(MergeCommit {
            oid: "deadbeef".to_string(),
        }),
        base_ref_name: "main".to_string(),
    };
    assert_eq!(merge_refusal(&view, 7275), None);
}

#[test]
fn merge_refusal_names_the_state() {
    let view = PrView {
        state: "OPEN".to_string(),
        head_ref_name: BRANCH.to_string(),
        ..PrView::default()
    };
    let reason = merge_refusal(&view, 7275).expect("an OPEN PR must be refused");
    assert!(
        reason.contains("OPEN"),
        "reason must name the state: {reason}"
    );
    assert!(reason.contains("7275"), "reason must name the PR: {reason}");
}

#[test]
fn merge_refusal_rejects_a_payload_with_no_head() {
    let view = PrView {
        state: "MERGED".to_string(),
        ..PrView::default()
    };
    assert!(
        merge_refusal(&view, 7275).is_some(),
        "MERGED with no head names nothing to clean up"
    );
}

// ── worktree listing ─────────────────────────────────────────────────────

#[test]
fn parse_worktree_list_reads_branch_and_head() {
    let entries = parse_worktree_list(&worktree_listing());
    assert_eq!(entries.len(), 2, "{entries:?}");
    assert_eq!(entries[1].path, PathBuf::from(TREE));
    assert_eq!(entries[1].head, HEAD_OID);
    assert_eq!(entries[1].branch.as_deref(), Some(BRANCH));
}

#[test]
fn parse_worktree_list_drops_the_bare_record() {
    let entries = parse_worktree_list("worktree /repo/.git\nbare\n\n");
    assert!(entries.is_empty(), "{entries:?}");
}

#[test]
fn parse_worktree_list_keeps_a_detached_worktree() {
    let entries = parse_worktree_list(&format!("worktree {TREE}\nHEAD {HEAD_OID}\ndetached\n\n"));
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0].branch, None);
}

#[test]
fn worktree_targets_matches_branch_and_detached_head() {
    let listing = format!(
        "worktree /repo\nHEAD 1111111111111111111111111111111111111111\nbranch refs/heads/main\n\n\
         worktree /repo/wt-branch\nHEAD 3333333333333333333333333333333333333333\n\
         branch refs/heads/{BRANCH}\n\n\
         worktree /repo/wt-detached\nHEAD {HEAD_OID}\ndetached\n\n"
    );
    let entries = parse_worktree_list(&listing);
    let hits = worktree_targets(&entries, BRANCH, HEAD_OID, &root());
    let paths: Vec<_> = hits.iter().map(|e| e.path.clone()).collect();
    assert_eq!(
        paths,
        vec![
            PathBuf::from("/repo/wt-branch"),
            PathBuf::from("/repo/wt-detached")
        ],
        "both the branch match and the detached head match are targets"
    );
}

#[test]
fn worktree_targets_never_returns_the_main_checkout() {
    let listing = format!("worktree /repo\nHEAD {HEAD_OID}\nbranch refs/heads/{BRANCH}\n\n");
    let entries = parse_worktree_list(&listing);
    assert!(
        worktree_targets(&entries, BRANCH, HEAD_OID, &root()).is_empty(),
        "cleanup runs from the main checkout; it is never its own target"
    );
}

#[test]
fn worktree_targets_ignores_an_empty_head_oid() {
    let listing = format!("worktree {TREE}\nHEAD \ndetached\n\n");
    let entries = parse_worktree_list(&listing);
    assert!(
        worktree_targets(&entries, "", "", &root()).is_empty(),
        "an empty branch and OID must match nothing"
    );
}

// ── branch selection ─────────────────────────────────────────────────────

#[test]
fn agent_branches_at_matches_only_the_agent_prefix() {
    let hits = agent_branches_at(&branch_listing(), HEAD_OID);
    assert_eq!(hits, vec![format!("{AGENT_BRANCH_PREFIX}aa11")]);
}

#[test]
fn agent_branches_at_ignores_a_branch_that_moved_on() {
    let listing = format!("{AGENT_BRANCH_PREFIX}bb22 2222222222222222222222222222222222222222\n");
    assert!(
        agent_branches_at(&listing, HEAD_OID).is_empty(),
        "a tip that is not the merged head carries commits the PR never had"
    );
}

#[test]
fn agent_branches_at_returns_nothing_for_an_empty_oid() {
    assert!(agent_branches_at(&branch_listing(), "  ").is_empty());
}

#[test]
fn step_line_renders_ok_and_failed() {
    assert_eq!(StepLine::ok("pr", "fine").render(), "pr: ok — fine");
    assert_eq!(StepLine::failed("pr", "nope").render(), "pr: FAILED — nope");
    assert_eq!(StepLine::ok("pr", "fine").status, StepStatus::Ok);
}

// ── the executor ─────────────────────────────────────────────────────────

#[tokio::test]
async fn cleanup_refuses_an_open_pr() {
    let gh = Scripted::new().on(
        "gh pr view 7275",
        &format!("{{\"state\":\"OPEN\",\"headRefName\":\"{BRANCH}\"}}"),
    );
    let git = Scripted::new();
    let claims = FakeClaims::none();
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    assert_eq!(report.lines.len(), 1, "the refusal short-circuits the run");
    assert!(report.lines[0].detail.contains("OPEN"));
    assert!(
        git.calls().is_empty(),
        "no git command may run for an unmerged PR: {:?}",
        git.calls()
    );
}

#[tokio::test]
async fn cleanup_refuses_when_gh_view_fails() {
    let gh = Scripted::new().on_fail("gh pr view 7275", "no pull requests found");
    let git = Scripted::new();
    let claims = FakeClaims::none();
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(report.failed());
    assert!(report.lines[0].detail.contains("no pull requests found"));
    assert!(git.calls().is_empty());
}

#[tokio::test]
async fn cleanup_clean_path_removes_everything() {
    let gh = gh_merged();
    let git = git_full();
    let claims = FakeClaims::none();
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(!report.failed(), "{}", report.render());
    let calls = git.calls();
    let joined = calls.join("\n");
    assert!(
        joined.contains("git push origin --delete"),
        "the remote branch must be deleted: {joined}"
    );
    assert!(
        joined.contains(&format!("git worktree remove {TREE}")),
        "the worktree must be removed: {joined}"
    );
    assert!(
        !joined.contains("--force"),
        "cleanup never forces a worktree removal: {joined}"
    );
    assert!(
        joined.contains(&format!("git branch -D {BRANCH}")),
        "the head branch must be deleted: {joined}"
    );
    assert!(
        joined.contains(&format!("git branch -D {AGENT_BRANCH_PREFIX}aa11")),
        "the agent branch at the merged head must be deleted: {joined}"
    );
    assert!(
        !joined.contains(&format!("git branch -D {AGENT_BRANCH_PREFIX}bb22")),
        "an agent branch that moved on must be left alone: {joined}"
    );
    assert!(joined.contains("git worktree prune"), "{joined}");
    assert!(joined.contains("git fetch --prune origin"), "{joined}");
}

/// #8301: a second, unnamed worktree on its own `worktree-agent-*` branch whose
/// tip is the merged head commit — the shape the wide rule sweeps.
const OTHER_TREE: &str = "/repo/.claude/worktrees/agent-cc33";

/// A `git` fake listing the head tree plus [`OTHER_TREE`] (#8301).
fn git_two_trees() -> Scripted {
    let listing = format!(
        "{}worktree {OTHER_TREE}\nHEAD {HEAD_OID}\nbranch refs/heads/{AGENT_BRANCH_PREFIX}cc33\n\n",
        worktree_listing()
    );
    let branches = format!("{}{AGENT_BRANCH_PREFIX}cc33 {HEAD_OID}\n", branch_listing());
    Scripted::new()
        .on(ORIGIN_QUERY, ORIGIN_URL)
        .on("git ls-remote", "")
        .on("git worktree list", &listing)
        .on("git worktree remove", "")
        .on("git branch --format", &branches)
        .on("git branch -D", "")
        .on("git worktree prune", "")
        .on("git fetch --prune", "")
}

/// Assert the #8301 invariant: [`OTHER_TREE`] and its branch were not touched.
fn assert_other_tree_untouched(joined: &str) {
    assert!(
        !joined.contains(&format!("git worktree remove {OTHER_TREE}")),
        "an unnamed worktree must never be removed by a head-only cleanup: {joined}"
    );
    assert!(
        !joined.contains(&format!("git branch -D {AGENT_BRANCH_PREFIX}cc33")),
        "an unnamed worktree's branch must never be deleted: {joined}"
    );
    assert!(
        !joined.contains(&format!("git branch -D {AGENT_BRANCH_PREFIX}aa11")),
        "a head-only cleanup deletes the head branch and nothing else: {joined}"
    );
}

/// 🔴 #8301: two worktrees; the merge-chained cleanup of one leaves the other
/// and its branch intact, and names it in the report.
#[tokio::test]
async fn cleanup_8301_head_only_leaves_an_unnamed_tree_at_the_head_commit() {
    let git = git_two_trees();
    let req = CleanupRequest {
        head_only: true,
        ..req(false)
    };
    let report = run(
        &gh_merged(),
        &git,
        &FakeClaims::none(),
        &FakeLanding::nothing_merged(),
        &clean,
        &req,
    )
    .await;

    assert!(!report.failed(), "{}", report.render());
    let joined = git.calls().join("\n");
    assert!(
        joined.contains(&format!("git worktree remove {TREE}")),
        "the PR's own head worktree is still removed: {joined}"
    );
    assert!(
        joined.contains(&format!("git branch -D {BRANCH}")),
        "{joined}"
    );
    assert_other_tree_untouched(&joined);
    assert!(
        report.render().contains(&format!(
            "left in place, not this PR's head worktree: {OTHER_TREE}"
        )),
        "{}",
        report.render()
    );
}

/// 🔴 #8301 error arm: when the head tree cannot be read, nothing is removed —
/// neither the head tree nor the unnamed one.
#[tokio::test]
async fn cleanup_8301_an_unreadable_head_tree_removes_nothing() {
    let git = git_two_trees();
    let unreadable = |p: &Path| {
        Some(DirtyWorktree {
            path: p.to_path_buf(),
            reason: "`git status` could not be run".to_string(),
            dirty_files: 0,
            unpushed_commits: 0,
        })
    };
    let req = CleanupRequest {
        head_only: true,
        ..req(false)
    };
    let report = run(
        &gh_merged(),
        &git,
        &FakeClaims::none(),
        &FakeLanding::nothing_merged(),
        &unreadable,
        &req,
    )
    .await;

    assert!(report.failed(), "an unreadable tree must fail the run");
    let joined = git.calls().join("\n");
    assert!(
        !joined.contains("git worktree remove"),
        "nothing may be removed when unsaved work cannot be ruled out: {joined}"
    );
    assert_other_tree_untouched(&joined);
}

/// 🔴 REGRESSION (#7275 round 2): a registry entry whose `repo` and
/// `repo_root` name different repositories REFUSES.
///
/// Why: `--repo` aims `gh` and `repo_root` aims every git command, and the two
/// are recorded independently at open time. A directory later reused for a
/// different clone would let a MERGED pull request in one repository authorise
/// branch deletion and worktree removal in another. Fails on round 1, where the
/// two were never compared and the deletions ran.
#[tokio::test]
async fn cleanup_refuses_when_the_registry_repo_and_checkout_disagree() {
    let gh = gh_merged();
    let git = Scripted::new()
        .on(
            ORIGIN_QUERY,
            "https://github.com/someone-else/other-repo.git\n",
        )
        .on("git ls-remote", "");
    let claims = FakeClaims::none();
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    let rendered = report.render();
    assert!(rendered.contains("someone-else/other-repo"), "{rendered}");
    assert!(rendered.contains("bobmatnyc/trusty-tools"), "{rendered}");
    let joined = git.calls().join("\n");
    assert!(
        !joined.contains("push origin --delete") && !joined.contains("branch -D"),
        "nothing destructive may run against a repository this cleanup is not for: {joined}"
    );
}

/// #7275 round 2: an `origin` that cannot be read is undeterminable, so the
/// destructive steps are refused rather than run on an unverified checkout.
#[tokio::test]
async fn cleanup_refuses_when_the_checkout_origin_cannot_be_read() {
    let gh = gh_merged();
    let git = Scripted::new()
        .on_fail(ORIGIN_QUERY, "not a git repository")
        .on("git ls-remote", "");
    let claims = FakeClaims::none();
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    assert!(
        report.render().contains("could not be read"),
        "{}",
        report.render()
    );
}

/// #9124: an origin that names no repository is quoted in the refusal, which
/// reaches the log; its token never is.
#[tokio::test]
async fn cleanup_refusal_never_quotes_the_origin_token() {
    const TOKEN: &str = "ghp_9124CleanupSyntheticToken0000";
    let origin = format!("https://octo:{TOKEN}@github.com/\n");
    let gh = gh_merged();
    let git = Scripted::new()
        .on(ORIGIN_QUERY, &origin)
        .on("git ls-remote", "");
    let report = run(
        &gh,
        &git,
        &FakeClaims::none(),
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    let rendered = report.render();
    assert!(!rendered.contains(TOKEN), "the token reached the refusal");
    assert!(report.failed(), "the cleanup must refuse");
    assert!(
        rendered.contains("https://***@github.com/") && rendered.contains("names no"),
        "the refusal must name the redacted origin: {rendered}"
    );
}

#[tokio::test]
async fn cleanup_clean_path_with_the_remote_branch_already_gone() {
    let gh = gh_merged();
    let git = Scripted::new()
        .on(ORIGIN_QUERY, ORIGIN_URL)
        .on("git ls-remote", "")
        .on("git worktree list", &worktree_listing())
        .on("git worktree remove", "")
        .on("git branch --format", &branch_listing())
        .on("git branch -D", "")
        .on("git worktree prune", "")
        .on("git fetch --prune", "");
    let claims = FakeClaims::none();
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(!report.failed(), "{}", report.render());
    assert!(
        !git.calls()
            .iter()
            .any(|c| c.contains("push origin --delete")),
        "an absent remote branch is a completed step, not a delete: {:?}",
        git.calls()
    );
    assert!(
        rendered(&report.lines).contains("already gone"),
        "{}",
        report.render()
    );
}

#[tokio::test]
async fn cleanup_refuses_a_dirty_worktree() {
    let gh = gh_merged();
    let git = git_full();
    let claims = FakeClaims::none();
    let dirty = |p: &Path| {
        Some(DirtyWorktree {
            path: p.to_path_buf(),
            reason: "3 uncommitted/untracked file(s), 1 unpushed commit(s)".to_string(),
            dirty_files: 3,
            unpushed_commits: 1,
        })
    };
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &dirty,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    assert!(
        !git.calls().iter().any(|c| c.contains("worktree remove")),
        "a dirty tree is never removed: {:?}",
        git.calls()
    );
    assert!(
        rendered(&report.lines).contains("unsaved work"),
        "{}",
        report.render()
    );
}

#[tokio::test]
async fn cleanup_ends_a_session_claim_before_removing_the_worktree() {
    let gh = gh_merged();
    let git = git_full();
    let claims = FakeClaims::held_by("tm-bobmatnyc-01");
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(!report.failed(), "{}", report.render());
    assert_eq!(
        claims.ended.lock().expect("claims lock").as_slice(),
        ["tm-bobmatnyc-01"],
        "a merged PR makes the claim obsolete; cleanup ends it and proceeds"
    );
    assert!(
        git.calls().iter().any(|c| c.contains("worktree remove")),
        "the claim must not block the removal: {:?}",
        git.calls()
    );
}

/// #8301: session X's cleanup must not end session Y's live claim, and keeps
/// the tree with a reason naming Y.
///
/// Fails before #8301: both claims are ended and the tree is removed.
#[tokio::test]
async fn cleanup_keeps_a_tree_another_live_session_claims() {
    let gh = gh_merged();
    let git = git_full();
    let mut claims = FakeClaims::held(&["tm-caller-01", "tm-other-02"]);
    claims.live = vec!["tm-other-02".to_string()];
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    assert!(
        report.render().contains("tm-other-02"),
        "the kept tree names the live session: {}",
        report.render()
    );
    assert!(
        claims.ended.lock().expect("claims lock").is_empty(),
        "no claim is ended when one holder is live and foreign"
    );
    assert!(
        !git.calls().iter().any(|c| c.contains("worktree remove")),
        "{:?}",
        git.calls()
    );
}

/// #8301: the #7771 ownership gate refuses BEFORE any claim is ended.
///
/// Fails before #8301: the claim is ended and the tree removed.
#[tokio::test]
async fn cleanup_keeps_a_tree_the_ownership_gate_refuses() {
    let gh = gh_merged();
    let git = git_full();
    let mut claims = FakeClaims::held_by("tm-bobmatnyc-01");
    claims.refuse = Some("its owner file names session Y, which is live".to_string());
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    assert!(
        report.render().contains("which is live"),
        "{}",
        report.render()
    );
    assert!(claims.ended.lock().expect("claims lock").is_empty());
    assert!(
        !git.calls().iter().any(|c| c.contains("worktree remove")),
        "{:?}",
        git.calls()
    );
}

/// #8301: the default claim store cannot run the gate, so it keeps the tree.
#[tokio::test]
async fn cleanup_default_ownership_gate_fails_closed() {
    struct Bare;
    #[async_trait::async_trait]
    impl ClaimEnder for Bare {
        async fn claims_on(&self, _path: &Path) -> anyhow::Result<Vec<String>> {
            Ok(Vec::new())
        }
        async fn end_claim(&self, _id: &str) -> anyhow::Result<()> {
            Ok(())
        }
    }
    // The trait's own defaults: nothing overridden.
    impl ClaimOwnership for Bare {}
    let git = git_full();
    let report = run(
        &gh_merged(),
        &git,
        &Bare,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;
    assert!(report.failed(), "{}", report.render());
    assert!(!git.calls().iter().any(|c| c.contains("worktree remove")));
}

/// 🔴 #8301: two sessions each hold a tree on the merged head. Session X's
/// cleanup removes X's tree and ends X's claim only; session Y's tree and
/// claim are left intact, and the report names Y.
#[tokio::test]
async fn cleanup_8301_two_sessions_each_keep_their_own_tree() {
    let git = git_two_trees();
    let mut claims = FakeClaims::none();
    claims.per_path = vec![
        (PathBuf::from(TREE), vec!["tm-caller-01".to_string()]),
        (PathBuf::from(OTHER_TREE), vec!["tm-other-02".to_string()]),
    ];
    claims.live = vec!["tm-other-02".to_string()];
    let report = run(
        &gh_merged(),
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    let joined = git.calls().join("\n");
    assert!(
        joined.contains(&format!("git worktree remove {TREE}")),
        "the caller's own tree is removed: {joined}"
    );
    assert!(
        !joined.contains(&format!("git worktree remove {OTHER_TREE}")),
        "another live session's tree is never removed: {joined}"
    );
    assert_eq!(
        claims.ended.lock().expect("claims lock").as_slice(),
        ["tm-caller-01"],
        "only the caller's claim is ended"
    );
    let rendered = report.render();
    assert!(
        rendered.contains(&format!("{OTHER_TREE} kept")) && rendered.contains("tm-other-02"),
        "the kept tree names its live owner: {rendered}"
    );
}

/// 🔴 #8301 error arm: the ownership gate is judged again right before the
/// removal. A tree that the gate refuses at that point (an agent resumed in it,
/// re-locking it under a live pid) keeps its lock and stays on disk.
///
/// Fails at a4a5d16c6: the first answer's stale-lock verdict unlocks and removes.
#[tokio::test]
async fn cleanup_8301_rejudges_ownership_before_removing() {
    let git = git_full().on("git worktree unlock", "");
    let claims = FakeClaims::held_by("tm-bobmatnyc-01").gate_then(vec![
        Ok(()),
        Err("git still reports the harness's agent-lifetime lock".to_string()),
    ]);
    let report = run(
        &gh_merged(),
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    assert!(
        report.render().contains("pre-removal check"),
        "{}",
        report.render()
    );
    let joined = git.calls().join("\n");
    assert!(
        !joined.contains("git worktree unlock"),
        "a lock judged live now is never released: {joined}"
    );
    assert!(
        claims.released.lock().expect("released lock").is_empty(),
        "a refused tree's lock is never judged for release"
    );
    assert!(!joined.contains("git worktree remove"), "{joined}");
}

/// 🔴 #7771 critic: the lock is judged again at the moment it would be
/// released. A lock re-taken under a live pid since the gate keeps the tree,
/// its lock and its claim.
///
/// Fails with the release judgement removed from `remove_one`: the claim is
/// ended and `git worktree remove` runs. At a3ffce106 the gate's second lock
/// read turned a live lock into "no unlock needed".
#[tokio::test]
async fn cleanup_8301_a_lock_judged_live_at_release_keeps_the_tree_and_its_claim() {
    let git = git_full();
    let mut claims = FakeClaims::held_by("tm-bobmatnyc-01");
    claims.lock_refuse = Some("pid 4242 runs with the start time it recorded".to_string());
    let report = run(
        &gh_merged(),
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    assert!(
        report.render().contains("judged again at release"),
        "{}",
        report.render()
    );
    assert!(claims.ended.lock().expect("claims lock").is_empty());
    assert!(
        !git.calls().iter().any(|c| c.contains("worktree remove")),
        "{:?}",
        git.calls()
    );
}

/// #7771: a claim store that cannot judge the lock keeps the tree (ADR-0045).
#[tokio::test]
async fn cleanup_default_lock_release_fails_closed() {
    struct NoLockJudge;
    #[async_trait::async_trait]
    impl ClaimEnder for NoLockJudge {
        async fn claims_on(&self, _path: &Path) -> anyhow::Result<Vec<String>> {
            Ok(Vec::new())
        }
        async fn end_claim(&self, _id: &str) -> anyhow::Result<()> {
            Ok(())
        }
    }
    // Permits the tree; `release_stale_lock` keeps the trait's default.
    #[async_trait::async_trait]
    impl ClaimOwnership for NoLockJudge {
        async fn tree_gate(&self, _path: &Path) -> Result<(), String> {
            Ok(())
        }
    }
    let git = git_full();
    let report = run(
        &gh_merged(),
        &git,
        &NoLockJudge,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;
    assert!(report.failed(), "{}", report.render());
    assert!(
        report.render().contains("cannot judge the lock"),
        "{}",
        report.render()
    );
    assert!(!git.calls().iter().any(|c| c.contains("worktree remove")));
}

/// 🔴 #8301 critic: a tree the pre-removal check refuses stays on disk, so its
/// claim must stay too — no claim is ended unless the tree is removed.
///
/// Fails at 4b1f480af: the claim was tombstoned before the check refused.
#[tokio::test]
async fn cleanup_8301_a_refused_pre_removal_check_ends_no_claim() {
    let git = git_full();
    let claims = FakeClaims::held_by("tm-bobmatnyc-01").gate_then(vec![
        Ok(()),
        Err("its owner file names session Y, which is live".to_string()),
    ]);
    let report = run(
        &gh_merged(),
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    assert!(
        report.render().contains("pre-removal check"),
        "{}",
        report.render()
    );
    assert!(
        claims.ended.lock().expect("claims lock").is_empty(),
        "a kept tree keeps its claim"
    );
    assert!(
        !git.calls().iter().any(|c| c.contains("worktree remove")),
        "{:?}",
        git.calls()
    );
}

/// 🔴 #8301 error arm: a live session that claims the tree while cleanup runs
/// keeps it, and its claim is not ended.
///
/// Fails at a4a5d16c6: the claim list is never re-read, so the tree is removed.
#[tokio::test]
async fn cleanup_8301_a_claim_taken_during_cleanup_keeps_the_tree() {
    let git = git_full();
    let mut claims =
        FakeClaims::none().claims_then(vec![Ok(Vec::new()), Ok(vec!["tm-other-02".to_string()])]);
    claims.live = vec!["tm-other-02".to_string()];
    let report = run(
        &gh_merged(),
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    assert!(
        report.render().contains("tm-other-02"),
        "{}",
        report.render()
    );
    assert!(claims.ended.lock().expect("claims lock").is_empty());
    assert!(
        !git.calls().iter().any(|c| c.contains("worktree remove")),
        "{:?}",
        git.calls()
    );
}

/// 🔴 #8301 error arm: claims that cannot be re-read before the removal keep
/// the tree (ADR-0045).
///
/// Fails at a4a5d16c6: the claim list is never re-read, so the tree is removed.
#[tokio::test]
async fn cleanup_8301_unreadable_claims_at_the_recheck_keep_the_tree() {
    let git = git_full();
    let claims = FakeClaims::none().claims_then(vec![
        Ok(Vec::new()),
        Err("the daemon stopped answering".to_string()),
    ]);
    let report = run(
        &gh_merged(),
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    assert!(
        report.render().contains("could not be re-read"),
        "{}",
        report.render()
    );
    assert!(
        !git.calls().iter().any(|c| c.contains("worktree remove")),
        "{:?}",
        git.calls()
    );
}

#[tokio::test]
async fn cleanup_fails_the_worktree_step_when_claims_cannot_be_read() {
    let gh = gh_merged();
    let git = git_full();
    let claims = super::UnavailableClaims::new("the daemon is not reachable");
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    assert!(
        !git.calls().iter().any(|c| c.contains("worktree remove")),
        "an unanswerable claim question must not advance toward a delete: {:?}",
        git.calls()
    );
}

#[tokio::test]
async fn cleanup_dry_run_makes_no_mutating_call() {
    let gh = gh_merged();
    let git = git_full();
    let claims = FakeClaims::held_by("tm-bobmatnyc-01");
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(true),
    )
    .await;

    assert!(!report.failed(), "{}", report.render());
    for call in git.calls() {
        assert!(
            !(call.contains("push origin --delete")
                || call.contains("worktree remove")
                || call.contains("branch -D")
                || call.contains("worktree prune")
                || call.contains("fetch --prune")),
            "--dry-run issued a mutating command: {call}"
        );
    }
    assert!(
        claims.ended.lock().expect("claims lock").is_empty(),
        "--dry-run must not end a claim"
    );
    let text = report.render();
    assert!(text.contains("would delete"), "{text}");
    assert!(text.contains("would remove"), "{text}");
}

// ── round-N siblings ─────────────────────────────────────────────────────

#[test]
fn strip_round_suffix_removes_only_a_numbered_round() {
    use super::plan::strip_round_suffix;
    assert_eq!(strip_round_suffix("fix/7232-thing-r2"), "fix/7232-thing");
    assert_eq!(strip_round_suffix("fix/7232-thing-r13"), "fix/7232-thing");
    assert_eq!(strip_round_suffix("fix/7232-thing"), "fix/7232-thing");
    assert_eq!(
        strip_round_suffix("feat/add-r-flag"),
        "feat/add-r-flag",
        "`-r` followed by letters is part of the name, not a round"
    );
    assert_eq!(
        strip_round_suffix("-r2"),
        "-r2",
        "a bare suffix is the name"
    );
}

#[test]
fn is_pr_branch_relates_round_siblings() {
    use super::plan::is_pr_branch;
    // The PR merged under the unsuffixed name; `-r2` is its sibling.
    assert!(is_pr_branch("fix/7232-thing", "fix/7232-thing-r2"));
    // …and the reverse: the PR opened from `-r2`, round 1 never had one.
    assert!(is_pr_branch("fix/7232-thing-r2", "fix/7232-thing"));
    // …and two rounds of the same work.
    assert!(is_pr_branch("fix/7232-thing-r2", "fix/7232-thing-r3"));
    assert!(is_pr_branch("fix/7232-thing", "fix/7232-thing"));
}

#[test]
fn is_pr_branch_rejects_an_unrelated_branch() {
    use super::plan::is_pr_branch;
    assert!(!is_pr_branch("fix/7232-thing", "fix/7233-other"));
    assert!(!is_pr_branch("fix/7232-thing", "main"));
    assert!(!is_pr_branch("", "fix/7232-thing"));
    assert!(!is_pr_branch("fix/7232-thing", ""));
}

#[test]
fn worktree_targets_includes_a_round_sibling() {
    let listing = format!(
        "worktree /repo\nHEAD 1111111111111111111111111111111111111111\nbranch refs/heads/main\n\n\
         worktree /repo/wt-r2\nHEAD 3333333333333333333333333333333333333333\n\
         branch refs/heads/{BRANCH}-r2\n\n"
    );
    let entries = parse_worktree_list(&listing);
    let hits = worktree_targets(&entries, BRANCH, HEAD_OID, &root());
    assert_eq!(
        hits.iter().map(|e| e.path.clone()).collect::<Vec<_>>(),
        vec![PathBuf::from("/repo/wt-r2")],
        "a `-r2` tree carries no merged PR of its own and nothing else reclaims it"
    );
}

#[test]
fn pr_branches_lists_head_then_siblings() {
    use super::plan::pr_branches;
    let listing = format!("main 1111\n{BRANCH}-r2 2222\n{BRANCH} {HEAD_OID}\nfix/other-r2 3333\n");
    assert_eq!(
        pr_branches(&listing, BRANCH),
        vec![BRANCH.to_string(), format!("{BRANCH}-r2")],
        "the head is deleted first, then its siblings"
    );
}

#[test]
fn pr_branches_ignores_an_unrelated_branch() {
    use super::plan::pr_branches;
    assert!(pr_branches("main 1111\nfix/other 2222\n", BRANCH).is_empty());
}

/// The round-N sibling `git` fake: the merge into the base is a no-op.
fn git_with_sibling(landed: bool) -> Scripted {
    let listing = format!(
        "worktree /repo\nHEAD 1111111111111111111111111111111111111111\nbranch refs/heads/main\n\n\
         worktree {TREE}\nHEAD {HEAD_OID}\nbranch refs/heads/{BRANCH}\n\n\
         worktree /repo/wt-r2\nHEAD 3333333333333333333333333333333333333333\n\
         branch refs/heads/{BRANCH}-r2\n\n"
    );
    let branches = format!("main 1111\n{BRANCH} {HEAD_OID}\n{BRANCH}-r2 3333\n");
    let s = Scripted::new()
        .on(ORIGIN_QUERY, ORIGIN_URL)
        .on("git ls-remote", "")
        // The sibling's tip is NOT an ancestor of the merged head, so the
        // merge-tree test is what decides.
        .on_fail("git merge-base --is-ancestor", "not an ancestor")
        // #7275 round 4: the base ref is refreshed once, before the first
        // merge-tree comparison that reads it.
        .on("git fetch origin", "")
        .on("git merge-tree --write-tree", "aaaabbbbccccdddd\n")
        .on("git worktree list", &listing)
        .on("git worktree remove", "")
        .on("git branch --format", &branches)
        .on("git branch -D", "")
        .on("git worktree prune", "")
        .on("git fetch --prune", "");
    if landed {
        s.on("git diff --name-only", "")
    } else {
        s.on(
            "git diff --name-only",
            "crates/a/src/lib.rs\ncrates/a/src/x.rs\n",
        )
    }
}

/// REGRESSION (#7275): a `-r2` sibling whose content the squash carried is
/// reclaimed along with the head — nothing else in the delivery chain deletes
/// it, and the ADR-0057 guard refused two such trees on 2026-09-09.
#[tokio::test]
async fn cleanup_removes_a_round_sibling_whose_content_landed() {
    let gh = gh_merged();
    let git = git_with_sibling(true);
    let claims = FakeClaims::none();
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(!report.failed(), "{}", report.render());
    let joined = git.calls().join("\n");
    assert!(
        joined.contains("git worktree remove /repo/wt-r2"),
        "the sibling tree must be removed: {joined}"
    );
    assert!(
        joined.contains(&format!("git branch -D {BRANCH}-r2")),
        "and its branch with it: {joined}"
    );
    assert!(!joined.contains("--force"), "still never forced: {joined}");
}

/// REGRESSION (#7275): a sibling holding work the merge did not carry is
/// refused, and the refusal NAMES the residue files so a person can look.
#[tokio::test]
async fn cleanup_refuses_a_sibling_whose_content_is_not_on_the_base() {
    let gh = gh_merged();
    let git = git_with_sibling(false);
    let claims = FakeClaims::none();
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    let text = report.render();
    assert!(text.contains("crates/a/src/lib.rs"), "{text}");
    assert!(text.contains("2 files"), "{text}");
    assert!(
        !git.calls()
            .iter()
            .any(|c| c.contains("worktree remove /repo/wt-r2")),
        "the sibling must not be removed: {:?}",
        git.calls()
    );
}

/// REGRESSION (#7275): a round-1 branch that never had a pull request of its
/// own — superseded by the `-r2` that opened the PR — is reclaimed when its tip
/// is an ancestor of the merged head, without a merge-tree round trip.
#[tokio::test]
async fn cleanup_removes_a_round_one_branch_that_never_had_its_own_pr() {
    let head_r2 = format!("{BRANCH}-r2");
    let gh = Scripted::new().on(
        "gh pr view 7275",
        &format!(
            "{{\"state\":\"MERGED\",\"headRefName\":\"{head_r2}\",\"headRefOid\":\"{HEAD_OID}\",\
             \"baseRefName\":\"main\"}}"
        ),
    );
    let listing = format!(
        "worktree /repo\nHEAD 1111\nbranch refs/heads/main\n\n\
         worktree /repo/wt-r1\nHEAD 4444\nbranch refs/heads/{BRANCH}\n\n"
    );
    let git = Scripted::new()
        .on(ORIGIN_QUERY, ORIGIN_URL)
        .on("git ls-remote", "")
        .on("git merge-base --is-ancestor", "")
        .on("git worktree list", &listing)
        .on("git worktree remove", "")
        .on(
            "git branch --format",
            &format!("main 1111\n{BRANCH} 4444\n"),
        )
        .on("git branch -D", "")
        .on("git worktree prune", "")
        .on("git fetch --prune", "");
    let claims = FakeClaims::none();
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(!report.failed(), "{}", report.render());
    let joined = git.calls().join("\n");
    assert!(
        joined.contains("git worktree remove /repo/wt-r1"),
        "the round-1 tree has no PR of its own and nothing else reclaims it: {joined}"
    );
    assert!(
        joined.contains(&format!("git branch -D {BRANCH}")),
        "and its branch with it: {joined}"
    );
    assert!(
        !joined.contains("merge-tree"),
        "an ancestor tip needs no merge test: {joined}"
    );
}

// ── the ahead-count gate (#7275 round 3) ─────────────────────────────────

/// A commit that is not the merged head — a sibling branch's own tip.
const SIB_OID: &str = "5555555555555555555555555555555555555555";

/// The squash-merge shape: `origin/<head>` is already gone, the tip is an
/// ancestor of nothing, and the merge into the base is or is not a no-op.
///
/// `merge-base --is-ancestor` FAILS on purpose, so every test below reaches the
/// `git merge-tree --write-tree` comparison the owner's round-3 brief names
/// rather than the ancestor shortcut.
fn git_squash(listing: &str, branches: &str, landed: bool) -> Scripted {
    let s = Scripted::new()
        .on(ORIGIN_QUERY, ORIGIN_URL)
        .on("git ls-remote", "")
        .on_fail("git merge-base --is-ancestor", "not an ancestor")
        // #7275 round 4: the base ref is refreshed once, before the first
        // merge-tree comparison that reads it.
        .on("git fetch origin", "")
        .on("git merge-tree --write-tree", "aaaabbbbccccdddd\n")
        .on("git worktree list", listing)
        .on("git worktree remove", "")
        .on("git branch --format", branches)
        .on("git branch -D", "")
        .on("git worktree prune", "")
        .on("git fetch --prune", "");
    if landed {
        s.on("git diff --name-only", "")
    } else {
        s.on("git diff --name-only", "crates/a/src/lib.rs\n")
    }
}

/// 🔴 REGRESSION (#7275 round 3): a squash-merged worktree is landed and
/// removable, however many commits it is "ahead" by.
///
/// Why: a squash merge puts the branch's content on `main` as a NEW commit, so
/// nothing the branch holds is an ancestor of `main` and `inspect_dirt` counts
/// every one of its commits as unpushed. Seven worktrees were refused that way
/// on 2026-09-09 — the exact population cleanup exists to reclaim. FAILS on
/// origin/main, where the count alone refused.
#[tokio::test]
async fn cleanup_removes_a_squash_merged_worktree() {
    let gh = gh_merged();
    let git = git_squash(&worktree_listing(), &branch_listing(), true);
    let claims = FakeClaims::none();
    let probe = ahead_by(2);
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &probe,
        &req(false),
    )
    .await;

    assert!(!report.failed(), "{}", report.render());
    let joined = git.calls().join("\n");
    assert!(
        joined.contains(&format!("git worktree remove {TREE}")),
        "a squash-merged tree must be removed, not refused for being ahead: {joined}"
    );
    assert!(
        joined.contains("git merge-tree --write-tree origin/main"),
        "the merge-tree no-op is what proves it landed: {joined}"
    );
    assert!(!joined.contains("--force"), "still never forced: {joined}");
    assert!(
        report.render().contains("landed"),
        "the line must say the ahead-count was accounted for: {}",
        report.render()
    );
}

/// 🔴 REGRESSION (#7275 round 3): a branch with a merged pull request whose
/// merge-tree still ADDS content is refused, and the refusal names what.
///
/// Why: the merged pull request proves the branch's NAME landed, not that this
/// checkout holds only what landed. Without the merge-tree half, a tree whose
/// branch gained commits after the merge would be removed with them.
#[tokio::test]
async fn cleanup_refuses_a_squash_merged_tree_that_moved_on() {
    let gh = gh_merged();
    let git = git_squash(&worktree_listing(), &branch_listing(), false);
    let claims = FakeClaims::none();
    let probe = ahead_by(3);
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &probe,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    let text = report.render();
    assert!(
        text.contains("crates/a/src/lib.rs"),
        "the refusal must name the divergence: {text}"
    );
    assert!(
        text.contains("3 unpushed commit(s)"),
        "and still report what the probe saw: {text}"
    );
    assert!(
        !git.calls()
            .iter()
            .any(|c| c.contains(&format!("worktree remove {TREE}"))),
        "a tree that moved on past the merge is never removed: {:?}",
        git.calls()
    );
}

/// 🔴 REGRESSION (#7275 round 3): an ahead-of-upstream tree that NO merged pull
/// request matches is refused.
///
/// Why: the ahead count stops being a refusal only because a merge accounts for
/// it. With no merged pull request under the branch name, its round stem or its
/// head commit, nothing does — and today's refusal must stand.
#[tokio::test]
async fn cleanup_refuses_an_ahead_tree_with_no_merged_pr() {
    let gh = gh_merged();
    // The tree carries the PR's branch NAME but sits on a different commit, so
    // step 1's own proof does not settle it and the matcher is asked.
    let listing = format!(
        "worktree /repo\nHEAD 1111\nbranch refs/heads/main\n\n\
         worktree {TREE}\nHEAD {SIB_OID}\nbranch refs/heads/{BRANCH}\n\n"
    );
    let git = git_squash(&listing, &format!("main 1111\n{BRANCH} {SIB_OID}\n"), true);
    let claims = FakeClaims::none();
    let probe = ahead_by(1);
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &probe,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    let text = report.render();
    assert!(
        text.contains("no MERGED pull request matches"),
        "the refusal must name the missing evidence: {text}"
    );
    assert!(
        !git.calls().iter().any(|c| c.contains("worktree remove")),
        "no merged pull request means no removal: {:?}",
        git.calls()
    );
}

/// REGRESSION (#7275 round 3): a round sibling reaches its merged pull request
/// through the #7267 round-stem rung, not through its own name.
#[tokio::test]
async fn cleanup_removes_a_squash_merged_round_sibling() {
    let gh = gh_merged();
    let listing = format!(
        "worktree /repo\nHEAD 1111\nbranch refs/heads/main\n\n\
         worktree /repo/wt-r2\nHEAD {SIB_OID}\nbranch refs/heads/{BRANCH}-r2\n\n"
    );
    let branches = format!("main 1111\n{BRANCH}-r2 {SIB_OID}\n");
    let git = git_squash(&listing, &branches, true);
    let claims = FakeClaims::none();
    let probe = ahead_by(1);
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::merged(BRANCH, 7275),
        &probe,
        &req(false),
    )
    .await;

    assert!(!report.failed(), "{}", report.render());
    assert!(
        git.calls()
            .iter()
            .any(|c| c.contains("worktree remove /repo/wt-r2")),
        "the stem's merged pull request vouches for the sibling: {:?}",
        git.calls()
    );
}

/// 🔴 FAIL-CLOSED (#7275 round 3): a `git merge-tree` that cannot run leaves
/// the refusal standing.
///
/// Why: the gate's grant deletes a checkout, so an unanswerable question must
/// never read as "landed" (ADR-0045).
#[tokio::test]
async fn cleanup_refuses_when_the_merge_test_cannot_run() {
    let gh = gh_merged();
    let git = Scripted::new()
        .on(ORIGIN_QUERY, ORIGIN_URL)
        .on("git ls-remote", "")
        .on_fail("git merge-base --is-ancestor", "not an ancestor")
        .on("git fetch origin", "")
        .on_fail("git merge-tree --write-tree", "fatal: not a valid object")
        .on("git worktree list", &worktree_listing())
        .on("git worktree remove", "")
        .on("git branch --format", &branch_listing())
        .on("git branch -D", "")
        .on("git worktree prune", "")
        .on("git fetch --prune", "");
    let claims = FakeClaims::none();
    let probe = ahead_by(1);
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &probe,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    assert!(
        !git.calls().iter().any(|c| c.contains("worktree remove")),
        "a failed merge test must not advance toward a delete: {:?}",
        git.calls()
    );
}

/// 🔴 FAIL-CLOSED (#7275 round 3): an `inspect_dirt` that could not read the
/// tree — both counts zero, its error arm — still refuses.
#[tokio::test]
async fn cleanup_refuses_an_unreadable_worktree() {
    let gh = gh_merged();
    let git = git_full();
    let claims = FakeClaims::none();
    let unreadable = |p: &Path| {
        Some(DirtyWorktree {
            path: p.to_path_buf(),
            reason: "`git status` could not be run".to_string(),
            dirty_files: 0,
            unpushed_commits: 0,
        })
    };
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &unreadable,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    assert!(
        report.render().contains("unsaved work"),
        "an unreadable tree is dirty, not ahead: {}",
        report.render()
    );
    assert!(
        !git.calls().iter().any(|c| c.contains("worktree remove")),
        "{:?}",
        git.calls()
    );
}

// ── the base ref and the removal window (#7275 round 4) ──────────────────

/// A `git` fake whose `origin/main` is STALE until a targeted fetch lands.
///
/// Why: this is the shape of a real checkout the moment after a merge. The
/// squash commit is on GitHub and not in the local ref store, so the merge test
/// diffs the branch against a base that predates it and NAMES every file the
/// branch touched as residue. Only a fetch of that ref makes the same
/// comparison empty.
struct StaleBase {
    /// The routes for everything the run does besides the base comparison.
    inner: Scripted,
    /// Set once `git fetch origin <base>` has run.
    fetched: RefCell<bool>,
}

impl StaleBase {
    fn new(inner: Scripted) -> Self {
        Self {
            inner,
            fetched: RefCell::new(false),
        }
    }
}

impl Git for StaleBase {
    fn run(&self, dir: &Path, args: &[String]) -> anyhow::Result<CmdOut> {
        let joined = args.join(" ");
        if joined.starts_with("fetch origin ") {
            *self.fetched.borrow_mut() = true;
        }
        if joined.starts_with("diff --name-only") && !*self.fetched.borrow() {
            self.inner.seen.borrow_mut().push(format!("git {joined}"));
            return Ok(CmdOut {
                success: true,
                stdout: "crates/a/src/lib.rs\n".to_string(),
                stderr: String::new(),
            });
        }
        Git::run(&self.inner, dir, args)
    }
}

/// 🔴 REGRESSION (#7275 round 4): a tree whose `origin/<base>` had not yet been
/// fetched is reclaimed in ONE pass, not the pass after next.
///
/// Why: the merge test compares against the local `origin/<base>`, and the only
/// fetch in the run is step 5's — which runs AFTER the worktree step. So the
/// first cleanup following a merge compared against a base predating it, found
/// the branch's content missing, and refused a tree that had genuinely landed;
/// under `--auto` that is a whole sweep interval of delay, and by hand it looks
/// like a false refusal. FAILS on round 3, where no fetch precedes the compare.
#[tokio::test]
async fn cleanup_reclaims_a_tree_whose_base_ref_was_stale() {
    let gh = gh_merged();
    let git = StaleBase::new(git_squash(&worktree_listing(), &branch_listing(), true));
    let claims = FakeClaims::none();
    let probe = ahead_by(2);
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &probe,
        &req(false),
    )
    .await;

    assert!(!report.failed(), "{}", report.render());
    let calls = git.inner.calls();
    let joined = calls.join("\n");
    assert!(
        joined.contains("git fetch origin main"),
        "the base ref must be refreshed before it is compared against: {joined}"
    );
    let fetch_at = calls
        .iter()
        .position(|c| c.contains("fetch origin main"))
        .expect("the fetch must have run");
    let diff_at = calls
        .iter()
        .position(|c| c.contains("diff --name-only"))
        .expect("the merge comparison must have run");
    assert!(
        fetch_at < diff_at,
        "the refresh must precede the comparison it feeds: {calls:?}"
    );
    assert!(
        joined.contains(&format!("git worktree remove {TREE}")),
        "one pass must reclaim it: {joined}"
    );
}

/// 🔴 FAIL-CLOSED (#7275 round 4): a base ref that cannot be refreshed refuses.
///
/// Why: the alternative is comparing against a ref that may predate the merge,
/// and that comparison's only two answers are "refuse" and "delete a checkout".
/// An unanswerable question must never take the second (ADR-0045).
#[tokio::test]
async fn cleanup_refuses_when_the_base_ref_cannot_be_refreshed() {
    let gh = gh_merged();
    // Every other route says landed; only the refresh fails.
    let git = Scripted::new()
        .on(ORIGIN_QUERY, ORIGIN_URL)
        .on("git ls-remote", "")
        .on_fail("git merge-base --is-ancestor", "not an ancestor")
        .on_fail(
            "git fetch origin",
            "fatal: could not read from remote repository",
        )
        .on("git merge-tree --write-tree", "aaaabbbbccccdddd\n")
        .on("git diff --name-only", "")
        .on("git worktree list", &worktree_listing())
        .on("git worktree remove", "")
        .on("git branch --format", &branch_listing())
        .on("git branch -D", "")
        .on("git worktree prune", "")
        .on("git fetch --prune", "");
    let claims = FakeClaims::none();
    let probe = ahead_by(1);
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &probe,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    let text = report.render();
    assert!(
        text.contains("could not read from remote repository"),
        "the refusal must name what failed: {text}"
    );
    assert!(
        !git.calls().iter().any(|c| c.contains("worktree remove")),
        "a base ref that may predate the merge must not authorise a delete: {:?}",
        git.calls()
    );
}

/// A dirt probe that answers once, then differently — an agent that wrote in
/// the window between cleanup's two reads.
fn dirt_then(later: Option<DirtyWorktree>) -> impl Fn(&Path) -> Option<DirtyWorktree> {
    let calls = std::cell::Cell::new(0usize);
    move |p: &Path| {
        let n = calls.get();
        calls.set(n + 1);
        if n == 0 {
            return None;
        }
        later.clone().map(|mut d| {
            d.path = p.to_path_buf();
            d
        })
    }
}

/// 🔴 REGRESSION (#7275 round 4): a tree that gains unsaved work WHILE cleanup
/// is checking it is refused, not removed on the stale first reading.
///
/// Why: the first probe and the removal are separated by the merged-pull-request
/// lookup, the merge-tree comparison, the claim read and the claim tombstone —
/// several `gh` and `git` round trips. Ending a claim is record-only, so the
/// agent that held it keeps writing; on round 3 the removal ran on an answer
/// taken before all of that. FAILS on round 3, where the tree is removed with
/// the file in it.
#[tokio::test]
async fn cleanup_refuses_a_tree_that_changed_while_cleanup_was_checking_it() {
    let gh = gh_merged();
    let git = git_full();
    let claims = FakeClaims::held_by("tm-bobmatnyc-01");
    let probe = dirt_then(Some(DirtyWorktree {
        path: PathBuf::from(TREE),
        reason: "1 uncommitted/untracked file(s), 0 unpushed commit(s)".to_string(),
        dirty_files: 1,
        unpushed_commits: 0,
    }));
    let report = run(
        &gh,
        &git,
        &claims,
        &FakeLanding::nothing_merged(),
        &probe,
        &req(false),
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    let text = report.render();
    assert!(
        text.contains("changed while cleanup was checking it"),
        "the refusal must say the reading went stale: {text}"
    );
    assert!(
        text.contains("uncommitted/untracked files went from 0 to 1"),
        "and name what changed: {text}"
    );
    assert!(
        !git.calls().iter().any(|c| c.contains("worktree remove")),
        "work written during the window is never deleted: {:?}",
        git.calls()
    );
    // #8301 critic: the tree stays, so its claim stays.
    assert!(claims.ended.lock().expect("claims lock").is_empty());
}

// ── the registry ─────────────────────────────────────────────────────────

fn entry(pr: u64, cleaned: bool) -> OpenedPr {
    OpenedPr {
        pr,
        repo: "bobmatnyc/trusty-tools".to_string(),
        repo_root: root(),
        opened_at: chrono::Utc::now(),
        cleaned_at: cleaned.then(chrono::Utc::now),
        scope: Default::default(),
    }
}

#[test]
fn registry_round_trips_an_entry() {
    let dir = tempfile::tempdir().expect("tempdir");
    let reg = CleanupRegistry::under_root(dir.path());
    reg.record_open(entry(7275, false)).expect("record");
    let back = reg.entries();
    assert_eq!(back.len(), 1);
    assert_eq!(back[0].pr, 7275);
    assert!(back[0].pending());
}

#[test]
fn registry_record_open_is_idempotent() {
    let dir = tempfile::tempdir().expect("tempdir");
    let reg = CleanupRegistry::under_root(dir.path());
    reg.record_open(entry(7275, false)).expect("first");
    reg.record_open(entry(7275, false)).expect("second");
    assert_eq!(
        reg.entries().len(),
        1,
        "recording the same PR twice would clean it twice"
    );
}

#[test]
fn registry_pending_excludes_a_cleaned_entry() {
    let dir = tempfile::tempdir().expect("tempdir");
    let reg = CleanupRegistry::under_root(dir.path());
    reg.record_open(entry(7275, false)).expect("pending");
    reg.record_open(entry(7276, true)).expect("cleaned");
    let pending: Vec<u64> = reg.pending().into_iter().map(|e| e.pr).collect();
    assert_eq!(pending, vec![7275]);
}

#[test]
fn registry_mark_cleaned_stamps_the_entry() {
    let dir = tempfile::tempdir().expect("tempdir");
    let reg = CleanupRegistry::under_root(dir.path());
    reg.record_open(entry(7275, false)).expect("record");
    reg.mark_cleaned("bobmatnyc/trusty-tools", 7275, chrono::Utc::now())
        .expect("stamp");
    assert!(
        reg.pending().is_empty(),
        "a stamped entry never sweeps again"
    );
}

#[test]
fn registry_mark_cleaned_ignores_an_unknown_pr() {
    let dir = tempfile::tempdir().expect("tempdir");
    let reg = CleanupRegistry::under_root(dir.path());
    reg.mark_cleaned("bobmatnyc/trusty-tools", 999, chrono::Utc::now())
        .expect("stamping an unknown PR is a no-op, not an error");
    assert!(reg.entries().is_empty());
}

#[test]
fn registry_unreadable_file_reads_as_empty() {
    let dir = tempfile::tempdir().expect("tempdir");
    let reg = CleanupRegistry::under_root(dir.path());
    std::fs::write(reg.path(), "{ this is not json").expect("write garbage");
    assert!(
        reg.entries().is_empty(),
        "a corrupt registry makes the sweep idle, never guess"
    );
}

/// 🔴 #8301 round 2: concurrent read-modify-write never loses an update — a
/// sweep's `mark_cleaned` racing a merge's `record_scope` must keep both.
/// Fails before the lock, where a writer that read first wrote a stale copy.
#[test]
fn registry_concurrent_writers_lose_no_update() {
    const N: u64 = 24;
    for round in 0..4 {
        let dir = tempfile::tempdir().expect("tempdir");
        let reg = CleanupRegistry::under_root(dir.path());
        for pr in 0..N {
            reg.record_open(entry(pr, false)).expect("seed");
        }
        let barrier = std::sync::Arc::new(std::sync::Barrier::new(N as usize));
        let handles: Vec<_> = (0..N)
            .map(|pr| {
                let (reg, barrier) = (reg.clone(), std::sync::Arc::clone(&barrier));
                std::thread::spawn(move || {
                    barrier.wait();
                    if pr % 2 == 0 {
                        reg.mark_cleaned("bobmatnyc/trusty-tools", pr, chrono::Utc::now())
                    } else {
                        reg.record_scope(
                            "bobmatnyc/trusty-tools",
                            pr,
                            super::CleanupScope::Deferred,
                        )
                        .map(|_| ())
                    }
                })
            })
            .collect();
        for h in handles {
            h.join().expect("join").expect("write");
        }
        let entries = reg.entries();
        assert_eq!(entries.len(), N as usize, "round {round}");
        for e in &entries {
            if e.pr % 2 == 0 {
                assert!(
                    e.cleaned_at.is_some(),
                    "round {round}: #{} lost its stamp",
                    e.pr
                );
            } else {
                assert_eq!(
                    e.scope,
                    super::CleanupScope::Deferred,
                    "round {round}: #{} lost its deferral",
                    e.pr
                );
            }
        }
    }
}

/// #8301 round 2: the repo slug matches case-insensitively, as GitHub does.
#[test]
fn registry_record_scope_matches_the_repo_case_insensitively() {
    let dir = tempfile::tempdir().expect("tempdir");
    let reg = CleanupRegistry::under_root(dir.path());
    reg.record_open(entry(7275, false)).expect("record");

    let hit = reg
        .record_scope(
            "BobMatNYC/Trusty-Tools",
            7275,
            super::CleanupScope::Deferred,
        )
        .expect("write");

    assert!(hit, "a differently cased slug names the same repository");
    assert!(reg.pending().is_empty());
}

/// 🔴 #8301 round 2: an older writer's rewrite — no `format` stamp beside the
/// scope-aware marker — is detected, and a scope-aware write clears it.
#[test]
fn registry_detects_a_rewrite_by_an_older_writer() {
    let dir = tempfile::tempdir().expect("tempdir");
    let reg = CleanupRegistry::under_root(dir.path());
    reg.record_open(entry(7275, false)).expect("record");
    assert!(
        !reg.rewritten_by_older_writer(),
        "a scope-aware write is not a downgrade"
    );

    // What an older daemon's `mark_cleaned` writes: no `format`, no `scope`.
    std::fs::write(
        reg.path(),
        "{\"entries\":[{\"pr\":7275,\"repo\":\"bobmatnyc/trusty-tools\",\
         \"repo_root\":\"/repo\",\"opened_at\":\"2026-09-23T00:00:00Z\"}]}",
    )
    .expect("older write");
    assert!(reg.rewritten_by_older_writer());

    reg.mark_cleaned("bobmatnyc/trusty-tools", 7275, chrono::Utc::now())
        .expect("scope-aware write");
    assert!(!reg.rewritten_by_older_writer());
}

/// 🔴 #8301 round 3: a registry that does not parse is never replaced by a
/// write — the write errors and the bytes stay exactly as they were. Fails
/// if `update` treats a malformed file as empty.
#[test]
fn registry_write_refuses_to_replace_a_malformed_file() {
    let dir = tempfile::tempdir().expect("tempdir");
    let reg = CleanupRegistry::under_root(dir.path());
    let garbage = b"{ this is not json".to_vec();
    std::fs::write(reg.path(), &garbage).expect("write garbage");

    let outcome = reg.record_scope(
        "bobmatnyc/trusty-tools",
        7275,
        super::CleanupScope::Deferred,
    );

    assert!(outcome.is_err(), "a malformed registry must fail the write");
    assert_eq!(
        std::fs::read(reg.path()).expect("read back"),
        garbage,
        "the file must be left byte-for-byte"
    );
}

/// A pre-#8301 registry file, never touched by a scope-aware writer, is not a
/// downgrade: no marker exists.
#[test]
fn registry_an_old_file_alone_is_not_a_downgrade() {
    let dir = tempfile::tempdir().expect("tempdir");
    let reg = CleanupRegistry::under_root(dir.path());
    std::fs::write(reg.path(), "{\"entries\":[]}").expect("old file");
    assert!(!reg.rewritten_by_older_writer());
}

// ── #7185: the harness marker git counts and this engine's gate does not ─────

/// 🔴 REGRESSION (#7185, recurrence 2026-09-11): the worktree step clears the
/// harness ownership marker before it removes the tree.
///
/// Why: `count_dirty_files` excuses `.trusty-mpm-worktree` (it is the harness's
/// marker, not the agent's work), so the dirt gate above authorises the
/// removal — but `git worktree remove` runs git's OWN clean check, which counts
/// every untracked entry. Verified against git 2.54.0: a worktree whose only
/// untracked file is that marker is refused with `contains modified or
/// untracked files, use --force to delete it`. The two answers agree only where
/// the project gitignores the marker (this repo does; the project that hit the
/// recurrence does not), so `tm pr merge`'s cleanup left EVERY merged worktree
/// on disk there. Fails on 4cc327dbc, where nothing clears the marker.
/// What this does NOT assert: `--force`. Forcing would override the dirt gate
/// itself, which is the one thing standing between this step and unsaved work.
#[tokio::test]
async fn cleanup_clears_the_harness_marker_before_removing_the_tree() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let tree = tmp.path().join("agent-aa11");
    std::fs::create_dir_all(&tree).expect("tree");
    let marker = tree.join(crate::session_manager::decommission::WORKTREE_SENTINEL_FILE);
    std::fs::write(&marker, b"{}").expect("marker");
    let kept = tree.join("notes.md");
    std::fs::write(&kept, "left alone\n").expect("sibling");
    let shown = tree.display().to_string();

    let listing = format!(
        "worktree /repo\nHEAD 1111111111111111111111111111111111111111\n\
         branch refs/heads/main\n\n\
         worktree {shown}\nHEAD {HEAD_OID}\nbranch refs/heads/{BRANCH}\n\n"
    );
    let git = Scripted::new()
        .on(ORIGIN_QUERY, ORIGIN_URL)
        .on(
            "git ls-remote",
            &format!("{HEAD_OID}\trefs/heads/{BRANCH}\n"),
        )
        .on("git push origin --delete", "")
        .on("git worktree list", &listing)
        .on("git worktree remove", "")
        .on("git branch --format", &branch_listing())
        .on("git branch -D", "")
        .on("git worktree prune", "")
        .on("git fetch --prune", "");

    let report = run(
        &gh_merged(),
        &git,
        &FakeClaims::none(),
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(!report.failed(), "{}", report.render());
    assert!(
        !marker.exists(),
        "the harness marker must be cleared before the removal, or git refuses it"
    );
    assert!(
        kept.exists(),
        "clearing the marker must touch nothing else in the tree"
    );
    let joined = git.calls().join("\n");
    assert!(
        joined.contains(&format!("git worktree remove {shown}")),
        "the tree must still be removed: {joined}"
    );
    assert!(
        !joined.contains("--force"),
        "clearing the marker is not licence to force: {joined}"
    );
}

/// 🔴 REGRESSION (#7511 review, MEDIUM 1): a removal that fails AFTER the clear
/// puts the marker back.
///
/// Why: taking the marker is safe only because the removal that follows deletes
/// the directory. When the removal fails the tree survives, and without the
/// marker it is unattributed — `agent_ownership_blocks` refuses it and
/// `prune_orphaned_worktrees` reports it `owner_unknown`, so it is stranded
/// rather than lost, which is the #7185 symptom in a rarer branch. The failure
/// is forced by leaving `git worktree remove` unrouted on the fake, which is
/// what `Scripted` turns into an `Err` — the same arm a locked worktree or a
/// permission error reaches in production.
#[tokio::test]
async fn cleanup_restores_the_harness_marker_when_the_removal_fails() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let tree = tmp.path().join("agent-aa11");
    std::fs::create_dir_all(&tree).expect("tree");
    let marker = tree.join(crate::session_manager::decommission::WORKTREE_SENTINEL_FILE);
    // Real sentinel bytes, so the restore is proved faithful and not merely present.
    let original = br#"{"owner_session_id":"s-1","created_at":"2026-09-11T00:00:00Z"}"#;
    std::fs::write(&marker, original).expect("marker");
    let shown = tree.display().to_string();

    let listing = format!(
        "worktree /repo\nHEAD 1111111111111111111111111111111111111111\n\
         branch refs/heads/main\n\n\
         worktree {shown}\nHEAD {HEAD_OID}\nbranch refs/heads/{BRANCH}\n\n"
    );
    // Every route the run needs EXCEPT `worktree remove`, which therefore errors.
    let git = Scripted::new()
        .on(ORIGIN_QUERY, ORIGIN_URL)
        .on(
            "git ls-remote",
            &format!("{HEAD_OID}\trefs/heads/{BRANCH}\n"),
        )
        .on("git push origin --delete", "")
        .on("git worktree list", &listing)
        .on("git branch --format", &branch_listing())
        .on("git branch -D", "")
        .on("git worktree prune", "")
        .on("git fetch --prune", "");

    let report = run(
        &gh_merged(),
        &git,
        &FakeClaims::none(),
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    assert!(
        report.failed(),
        "an unroutable removal must fail the step: {}",
        report.render()
    );
    assert!(
        marker.exists(),
        "a removal that did not happen must leave the tree attributed"
    );
    assert_eq!(
        std::fs::read(&marker).expect("read restored marker"),
        original,
        "the restore must write back the ORIGINAL bytes, not a re-serialised payload"
    );
    assert!(
        !report.render().contains("could not be restored"),
        "a successful restore must add no note: {}",
        report.render()
    );
}

/// 🔴 A dry run inspects and reports; it must not touch the tree.
///
/// Why: `--dry-run` exists so an operator can see what cleanup would do. A
/// marker deleted by a preview is a write the preview promised not to make, and
/// the tree stays registered afterwards — so the next real run would find it
/// unmarked and owner-unknown.
#[tokio::test]
async fn a_dry_run_leaves_the_harness_marker_in_place() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let tree = tmp.path().join("agent-aa11");
    std::fs::create_dir_all(&tree).expect("tree");
    let marker = tree.join(crate::session_manager::decommission::WORKTREE_SENTINEL_FILE);
    std::fs::write(&marker, b"{}").expect("marker");
    let shown = tree.display().to_string();

    let listing = format!(
        "worktree /repo\nHEAD 1111111111111111111111111111111111111111\n\
         branch refs/heads/main\n\n\
         worktree {shown}\nHEAD {HEAD_OID}\nbranch refs/heads/{BRANCH}\n\n"
    );
    let git = Scripted::new()
        .on(ORIGIN_QUERY, ORIGIN_URL)
        .on(
            "git ls-remote",
            &format!("{HEAD_OID}\trefs/heads/{BRANCH}\n"),
        )
        .on("git worktree list", &listing)
        .on("git branch --format", &branch_listing());

    let report = run(
        &gh_merged(),
        &git,
        &FakeClaims::none(),
        &FakeLanding::nothing_merged(),
        &clean,
        &req(true),
    )
    .await;

    assert!(!report.failed(), "{}", report.render());
    assert!(
        marker.exists(),
        "a dry run must leave the tree exactly as it found it"
    );
}

// ── #8489: never "no worktree holds X" while one does ───────────────────

/// A full `git` fake whose worktree listing is `listing` (#8489).
fn git_listing(listing: &str) -> Scripted {
    git_listing_with(listing, &branch_listing())
}

/// [`git_listing`] with its own `git branch` listing. Its `-D` refuses a
/// branch a remaining listed tree holds, as real git does (#8489 round 2).
fn git_listing_with(listing: &str, branches: &str) -> Scripted {
    Scripted::new()
        .on(ORIGIN_QUERY, ORIGIN_URL)
        .on("git ls-remote", "")
        .on("git worktree list", listing)
        .on("git worktree remove", "")
        .on("git branch --format", branches)
        .on("git branch -D", "")
        .on("git worktree prune", "")
        .on("git fetch --prune", "")
}

/// Assert the #8489 invariant on a rendered report: the worktree step names
/// `holder` as kept and never claims that no worktree holds the head.
fn assert_holder_named(rendered: &str, holder: &str) {
    assert!(
        !rendered.contains("no worktree holds"),
        "a tree holds {BRANCH}; the report must not say none does:\n{rendered}"
    );
    assert!(
        rendered.contains(&format!(
            "worktree: FAILED — {holder}: holds {BRANCH} and was kept"
        )),
        "the holder must be named with the reason it was kept:\n{rendered}"
    );
    // #8489 round 3: `git switch main` fails in an agent tree; `--detach` works.
    assert!(
        rendered.contains(&format!(
            "run `git switch --detach` in it, then `git branch -D {BRANCH}`; or run \
             `tm pr cleanup 7275` from the main checkout"
        )),
        "the recovery must name a switch that works in any worktree:\n{rendered}"
    );
}

/// 🔴 #8489: `tm pr cleanup` run from the harness tree that holds the head —
/// the shape `tm pr open` records when it runs there. That tree is never a
/// target, and the report used to say no worktree held the branch.
#[tokio::test]
async fn cleanup_8489_names_the_checkout_it_runs_from_when_that_holds_the_head() {
    let git = git_listing(&worktree_listing());
    let req = CleanupRequest {
        repo_root: PathBuf::from(TREE),
        ..req(false)
    };
    let report = run(
        &gh_merged(),
        &git,
        &FakeClaims::none(),
        &FakeLanding::nothing_merged(),
        &clean,
        &req,
    )
    .await;

    assert!(report.failed(), "{}", report.render());
    assert_holder_named(&report.render(), TREE);
    let joined = git.calls().join("\n");
    assert!(
        !joined.contains("git worktree remove"),
        "the checkout cleanup runs in is never removed: {joined}"
    );
}

/// 🔴 #8489 error arm: a listing that names no tree at all was not read, and
/// must never be reported as "no worktree holds X".
#[tokio::test]
async fn cleanup_8489_an_empty_worktree_listing_is_inconclusive() {
    let git = git_listing("");
    let report = run(
        &gh_merged(),
        &git,
        &FakeClaims::none(),
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    let rendered = report.render();
    assert!(report.failed(), "{rendered}");
    assert!(!rendered.contains("no worktree holds"), "{rendered}");
    assert!(
        rendered.contains("worktree: FAILED — `git worktree list --porcelain` named no worktree")
            && rendered.contains("inconclusive"),
        "{rendered}"
    );
}

/// 🔴 #8489: git lists the tree by its real path while the caller spells it
/// through a symlink. Compared as strings, the running checkout became a
/// removal target; it is the same directory and is kept and named.
#[cfg(unix)]
#[tokio::test]
async fn cleanup_8489_a_symlinked_spelling_of_the_checkout_is_still_the_checkout() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let real = tmp.path().join("agent-real");
    std::fs::create_dir_all(&real).expect("tree");
    let link = tmp.path().join("agent-link");
    std::os::unix::fs::symlink(&real, &link).expect("symlink");
    let shown = real.display().to_string();

    let listing = format!(
        "worktree /repo\nHEAD 1111111111111111111111111111111111111111\n\
         branch refs/heads/main\n\n\
         worktree {shown}\nHEAD {HEAD_OID}\nbranch refs/heads/{BRANCH}\n\n"
    );
    let git = git_listing(&listing);
    let req = CleanupRequest {
        repo_root: link,
        ..req(false)
    };
    let report = run(
        &gh_merged(),
        &git,
        &FakeClaims::none(),
        &FakeLanding::nothing_merged(),
        &clean,
        &req,
    )
    .await;

    assert_holder_named(&report.render(), &shown);
    let joined = git.calls().join("\n");
    assert!(
        !joined.contains("git worktree remove"),
        "a symlinked spelling of the running checkout is still that checkout: {joined}"
    );
}

// ── #8489 round 2: step 4 never attempts a branch a worktree holds ───────

/// A synthetic harness tree cleanup is run from.
const RUN_TREE: &str = "/repo/.claude/worktrees/agent-run";

/// Did the run issue exactly `git branch -D <branch>`?
fn deleted(git: &Scripted, branch: &str) -> bool {
    let argv = format!("git branch -D {branch}");
    git.calls().contains(&argv)
}

/// 🔴 #8489 round 2 (critic HIGH 1): run from the tree holding the head, step 4
/// issued `git branch -D <head>`, git refused it, and the refusal stopped the
/// loop before `worktree-agent-aa11` was deleted.
#[tokio::test]
async fn cleanup_8489_local_branch_skips_the_held_head_and_deletes_the_rest() {
    let git = git_listing(&worktree_listing());
    let req = CleanupRequest {
        repo_root: PathBuf::from(TREE),
        ..req(false)
    };
    let report = run(
        &gh_merged(),
        &git,
        &FakeClaims::none(),
        &FakeLanding::nothing_merged(),
        &clean,
        &req,
    )
    .await;

    let rendered = report.render();
    let joined = git.calls().join("\n");
    assert!(
        !deleted(&git, BRANCH),
        "a held branch is never attempted: {joined}"
    );
    assert!(
        deleted(&git, &format!("{AGENT_BRANCH_PREFIX}aa11")),
        "the unheld agent branch is still deleted: {joined}"
    );
    assert!(
        rendered.contains(&format!(
            "local-branch: FAILED — deleted {AGENT_BRANCH_PREFIX}aa11; kept {BRANCH}: the \
             worktree at {TREE} has it checked out"
        )),
        "{rendered}"
    );
}

/// 🔴 #8489 round 2 (critic HIGH 2, the #8487 shape): the running checkout sits
/// on a `worktree-agent-*` branch at the merged head. It was not named, the
/// step said no worktree held the head, and step 4 hit "used by worktree".
#[tokio::test]
async fn cleanup_8489_a_running_checkout_on_an_agent_branch_at_the_head_is_kept() {
    let agent = format!("{AGENT_BRANCH_PREFIX}run");
    let listing = format!(
        "worktree /repo\nHEAD 1111111111111111111111111111111111111111\n\
         branch refs/heads/main\n\n\
         worktree {RUN_TREE}\nHEAD {HEAD_OID}\nbranch refs/heads/{agent}\n\n"
    );
    let branches = format!(
        "main 1111111111111111111111111111111111111111\n{BRANCH} {HEAD_OID}\n{agent} {HEAD_OID}\n"
    );
    let git = git_listing_with(&listing, &branches);
    let req = CleanupRequest {
        repo_root: PathBuf::from(RUN_TREE),
        ..req(false)
    };
    let report = run(
        &gh_merged(),
        &git,
        &FakeClaims::none(),
        &FakeLanding::nothing_merged(),
        &clean,
        &req,
    )
    .await;

    let rendered = report.render();
    assert!(!rendered.contains("no worktree holds"), "{rendered}");
    assert!(
        rendered.contains(&format!(
            "worktree: FAILED — {RUN_TREE}: holds {agent} and was kept"
        )),
        "{rendered}"
    );
    assert!(!deleted(&git, &agent), "{}", git.calls().join("\n"));
    assert!(deleted(&git, BRANCH), "{}", git.calls().join("\n"));
    assert!(
        rendered.contains(&format!("kept {agent}: the worktree at {RUN_TREE}")),
        "{rendered}"
    );
}

/// 🔴 #8489 round 2 (critic MEDIUM 3): a merge-chained run from a checkout on
/// the round sibling `<head>-r2` never deletes that sibling, so the checkout is
/// no reason to fail — only an exact-head holder is kept, as `split_head_only`.
#[tokio::test]
async fn cleanup_8489_head_only_ignores_a_running_checkout_on_a_sibling() {
    let listing = format!(
        "worktree /repo\nHEAD 1111111111111111111111111111111111111111\n\
         branch refs/heads/main\n\n\
         worktree {TREE}\nHEAD {HEAD_OID}\nbranch refs/heads/{BRANCH}\n\n\
         worktree {RUN_TREE}\nHEAD 3333333333333333333333333333333333333333\n\
         branch refs/heads/{BRANCH}-r2\n\n"
    );
    let git = git_listing(&listing);
    let req = CleanupRequest {
        repo_root: PathBuf::from(RUN_TREE),
        head_only: true,
        ..req(false)
    };
    let report = run(
        &gh_merged(),
        &git,
        &FakeClaims::none(),
        &FakeLanding::nothing_merged(),
        &clean,
        &req,
    )
    .await;

    let rendered = report.render();
    assert!(!report.failed(), "{rendered}");
    let joined = git.calls().join("\n");
    assert!(
        joined.contains(&format!("git worktree remove {TREE}")),
        "{joined}"
    );
    assert!(deleted(&git, BRANCH), "{joined}");
    assert!(!joined.contains(&format!("{BRANCH}-r2")), "{joined}");
}

/// #8489 round 2 (critic MEDIUM 3): a merge-chained run's recovery for a kept
/// head holder stays inside its scope — never the wider `tm pr cleanup <n>`.
#[tokio::test]
async fn cleanup_8489_head_only_recovery_stays_in_scope() {
    let git = git_listing(&worktree_listing());
    let req = CleanupRequest {
        repo_root: PathBuf::from(TREE),
        head_only: true,
        ..req(false)
    };
    let report = run(
        &gh_merged(),
        &git,
        &FakeClaims::none(),
        &FakeLanding::nothing_merged(),
        &clean,
        &req,
    )
    .await;

    let rendered = report.render();
    assert!(
        rendered.contains(&format!(
            "run `git switch --detach` in it, then `git branch -D {BRANCH}` — this merge's \
             cleanup reaches only {BRANCH}"
        )),
        "{rendered}"
    );
    assert!(!rendered.contains("tm pr cleanup"), "{rendered}");
    assert!(!deleted(&git, BRANCH), "{}", git.calls().join("\n"));
}

/// #8489 round 2 (critic LOW 5): `git worktree list` exits nonzero. Step 3
/// fails, and step 4 deletes nothing, because no branch is shown unheld.
#[tokio::test]
async fn cleanup_8489_a_failed_worktree_listing_deletes_no_branch() {
    let git = Scripted::new()
        .on(ORIGIN_QUERY, ORIGIN_URL)
        .on("git ls-remote", "")
        .on_fail("git worktree list", "fatal: not a git repository")
        .on("git branch --format", &branch_listing())
        .on("git branch -D", "")
        .on("git worktree prune", "")
        .on("git fetch --prune", "");
    let report = run(
        &gh_merged(),
        &git,
        &FakeClaims::none(),
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await;

    let rendered = report.render();
    assert!(report.failed(), "{rendered}");
    assert!(!rendered.contains("no worktree holds"), "{rendered}");
    assert!(
        rendered.contains("worktree: FAILED — ")
            && rendered.contains("local-branch: FAILED — no branch deleted"),
        "{rendered}"
    );
    let joined = git.calls().join("\n");
    assert!(!joined.contains("git branch -D"), "{joined}");
}

// ── #8603: a kept tree states how its tip relates to the merged head ────

/// A `git` fake whose PR-branch tree sits at [`SIB_OID`], not the merged head,
/// answering the relation probe with `relation` routes.
fn git_kept_tip(relation: &[(&str, Option<&str>)]) -> Scripted {
    let listing = format!(
        "worktree /repo\nHEAD 1111111111111111111111111111111111111111\nbranch refs/heads/main\n\n\
         worktree {TREE}\nHEAD {SIB_OID}\nbranch refs/heads/{BRANCH}\n\n"
    );
    let mut s = Scripted::new()
        .on(ORIGIN_QUERY, ORIGIN_URL)
        .on(
            "git ls-remote",
            &format!("{HEAD_OID}\trefs/heads/{BRANCH}\n"),
        )
        .on("git push origin --delete", "")
        .on("git worktree list", &listing)
        .on("git branch --format", &branch_listing())
        .on("git worktree prune", "")
        .on("git fetch --prune", "");
    for (needle, stdout) in relation {
        s = match stdout {
            Some(out) => s.on(needle, out),
            None => s.on_fail(needle, ""),
        };
    }
    s
}

/// Run cleanup against `git` with the ownership gate refusing the tree.
async fn kept_report(git: &Scripted) -> String {
    let mut claims = FakeClaims::held_by("tm-bobmatnyc-01");
    claims.refuse = Some("nothing proves that session ended".to_string());
    run(
        &gh_merged(),
        git,
        &claims,
        &FakeLanding::nothing_merged(),
        &clean,
        &req(false),
    )
    .await
    .render()
}

/// 🔴 REGRESSION (#8603): a tree kept with its tip an ANCESTOR of the merged
/// head says every commit on it is in the merge.
///
/// Fails on origin/main: the kept line named neither the relation nor the
/// merged head, and a downstream agent read the tip as unpushed work.
#[tokio::test]
async fn cleanup_8603_a_kept_tree_on_an_ancestor_says_every_commit_is_in_the_merge() {
    let git = git_kept_tip(&[("git merge-base --is-ancestor", Some(""))]);
    let rendered = kept_report(&git).await;
    assert!(
        rendered.contains(
            "its tip 55555555 is an ancestor of the merged head abc1234d — every commit on it \
             is in the merge"
        ),
        "{rendered}"
    );
    assert!(!rendered.contains("WARNING"), "{rendered}");
    let joined = git.calls().join("\n");
    assert!(!joined.contains("worktree remove"), "{joined}");
}

/// #8603: a tip carrying commits the merge did not gets a SEPARATE warning.
#[tokio::test]
async fn cleanup_8603_a_kept_tree_ahead_of_the_head_warns_separately() {
    let git = git_kept_tip(&[
        ("git merge-base --is-ancestor", None),
        ("git rev-list --count", Some("3\n")),
    ]);
    let rendered = kept_report(&git).await;
    assert!(
        rendered.contains("its tip 55555555 has 3 commit(s) the merged head abc1234d"),
        "{rendered}"
    );
    let warning = rendered
        .lines()
        .find(|l| l.contains("WARNING:"))
        .unwrap_or_else(|| panic!("no separate warning line:\n{rendered}"));
    assert!(
        warning.contains(&format!("{TREE} holds 3 commit(s) beyond the merged head")),
        "{warning}"
    );
    assert!(
        !warning.contains("nothing proves"),
        "the warning is its own line: {rendered}"
    );
}

/// #8603 error arm: a relation git cannot answer is stated as unknown, never
/// guessed as "every commit is in the merge".
#[tokio::test]
async fn cleanup_8603_an_unreadable_relation_is_stated_as_unknown() {
    let git = git_kept_tip(&[]).on_fail("git merge-base --is-ancestor", "fatal: bad object");
    let rendered = kept_report(&git).await;
    assert!(
        rendered.contains(
            "how its tip 55555555 relates to the merged head abc1234d could not be read: fatal: \
             bad object"
        ),
        "{rendered}"
    );
    assert!(
        !rendered.contains("every commit on it is in the merge"),
        "{rendered}"
    );
}