kono-wt 1.8.1

A single-binary CLI + TUI for managing Git worktrees and their GitHub pull requests.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
//! `wt prune` — bulk cleanup of merged or stale worktrees (detached ones
//! included), and the local branches they leave behind (spec §7/§12).
//!
//! Selection lives in [`assess`]: each worktree and branch gets a verdict naming
//! why it qualifies and what, if anything, keeps it. This module reports those
//! verdicts and removes the ones nothing keeps.

mod assess;

use std::collections::{HashMap, HashSet};
use std::path::Path;

use crate::cli::PruneArgs;
use crate::commands::{candidate_label, confirm, open_session};
use crate::config::wtconfig;
use crate::cx::Cx;
use crate::error::{Error, Result};
use crate::git::cli::GitCli;
use crate::git::discover::Repo;
use crate::git::merged::ContentCheck;
use crate::git::porcelain::RawWorktree;
use crate::git::worktrees::{HeldBranch, in_progress_branch_in, in_progress_op};
use crate::git::{
    abbrev_len, branch_ref, current_branch, enumerate, is_clean_for_removal, local_branches, ops,
};
use crate::model::Worktree;
use crate::worktree::{enrich_worktree, enumerate_worktrees, lock_repo};

use assess::{Assessor, Block, MergeTargets, Subject, Verdict};

/// Selects and removes prune candidates after confirmation (spec §7/§12).
pub(crate) fn run(cx: &mut Cx, args: &PruneArgs, json: bool) -> Result<u8> {
    if !args.includes_merged() && !args.includes_gone() && !args.includes_pushed() {
        return Err(Error::usage(
            "prune requires --merged, --gone, --pushed, or --all",
        ));
    }
    let git = cx.git.clone();
    let git = git.as_ref();
    let session = open_session(cx, git)?;
    let root = session.primary_root.clone();
    // "Gone" and "still on the remote" are only as true as the remote-tracking
    // refs, so the modes that read them refresh them first (dry runs included,
    // so a preview never promises something the real run would not do).
    if args.needs_fetch() {
        fetch_remotes(git, &session.repo, &root)?;
    }
    // Bare rows: selection reads nothing the listing enrichment adds (status,
    // ahead/behind, commits), so only `--json` enriches, and only candidates.
    let mut worktrees = enumerate_worktrees(&session.repo, git)?;
    // The porcelain records carry what the rows do not: the lock, and a detached
    // worktree's HEAD commit.
    let raws = enumerate(git, &root)?;
    let targets = MergeTargets::resolve(&session.repo);
    let current = current_branch(session.repo.gix());
    let assessor = Assessor::new(git, &root, &session.repo, args, &targets);
    // Every branch tip and detached HEAD in one recoverability check, rather
    // than one `git` per subject.
    let branch_refs: Vec<String> = local_branches(session.repo.gix())?
        .iter()
        .map(|name| branch_ref(name))
        .collect();
    assessor.prefetch_recoverable(
        branch_refs
            .iter()
            .map(String::as_str)
            .chain(raws.iter().filter_map(|raw| raw.head.as_deref())),
    );

    let mut verdicts: Vec<Verdict> = worktrees
        .iter()
        .enumerate()
        .filter_map(|(i, w)| assessor.worktree(i, w, raw_for(&raws, w)))
        .collect();

    // Branches that keep a worktree (the primary checkout and any branch checked
    // out elsewhere) are left to the worktree path, so a branch is never counted
    // — or deleted — twice. Under `--all` the branch of a worktree being removed
    // is also judged as a bare branch, so one pass clears both.
    let removing: HashSet<usize> = verdicts
        .iter()
        .filter(|v| v.block.is_none())
        .filter_map(|v| match v.subject {
            Subject::Worktree { index, .. } => Some(index),
            Subject::Branch { .. } => None,
        })
        .collect();
    let worktree_branches: HashSet<String> = worktrees
        .iter()
        .enumerate()
        .filter(|(i, _)| !(args.all && removing.contains(i)))
        .filter_map(|(_, w)| w.branch.clone())
        .collect();
    let mut branch_verdicts = assessor.branches(current.as_deref(), &worktree_branches)?;
    keep_held_branches(&assessor, &worktrees, &mut branch_verdicts);
    verdicts.extend(branch_verdicts);
    let (candidates, skipped): (Vec<Verdict>, Vec<Verdict>) =
        verdicts.into_iter().partition(|v| v.block.is_none());

    // The worktree/branch gap is the signal when a prune surprises someone.
    tracing::debug!(
        default = ?targets.default,
        merge_targets = ?targets.refs,
        worktrees = worktrees.len(),
        candidates = candidates.len(),
        skipped = skipped.len(),
        local_branches = local_branches(session.repo.gix()).map_or(0, |b| b.len()),
        "prune: candidate selection",
    );

    // Whatever qualified but is kept is always said out loud, on stderr (stdout
    // stays the candidate list, and clean for `--json`).
    if !json {
        for verdict in &skipped {
            if let Some(block) = &verdict.block {
                cx.err.line(&format!(
                    "skipping {}: {}",
                    verdict_label(&worktrees, verdict),
                    block.message()
                ))?;
            }
        }
    }

    // `--dry-run` (and the `--json` form) only report the candidate set.
    if args.dry_run || json {
        if json {
            // A worktree candidate's JSON line is its full listing row.
            let abbrev = abbrev_len(session.repo.gix());
            for verdict in &candidates {
                if let Subject::Worktree { index, .. } = verdict.subject {
                    enrich_worktree(&session.repo, git, abbrev, &mut worktrees[index]);
                }
            }
        }
        // Report the empty case explicitly on stderr so a dry-run that finds
        // nothing is never silently blank.
        if candidates.is_empty() && !json {
            cx.err.line("nothing to prune")?;
        }
        for verdict in &candidates {
            if json {
                cx.out.line(&verdict_json(&worktrees, verdict)?)?;
            } else {
                cx.out.line(&format!(
                    "would remove {}",
                    verdict_text(&worktrees, verdict)
                ))?;
            }
        }
        return Ok(0);
    }

    // Nothing is removed that was not listed: no blanket `git worktree prune`,
    // which would drop every missing worktree, including the ones kept above.
    if candidates.is_empty() {
        cx.err.line("nothing to prune")?;
        return Ok(0);
    }

    // Confirmation prompt (unless --force).
    if !args.force {
        cx.err.line("to remove:")?;
        for verdict in &candidates {
            cx.err
                .line(&format!("  {}", verdict_text(&worktrees, verdict)))?;
        }
        if !confirm(cx, "Proceed? [y/N] ")? {
            cx.err.line("aborted")?;
            return Ok(0);
        }
    }

    // Every removal below deletes worktrees, branches, and `wt.*` metadata, so
    // the whole loop is one mutation region under the advisory repo lock (issue
    // #99). `prune` runs no hooks, so nothing inside can re-enter `wt`.
    let lock = lock_repo(&root)?;
    // The merge state is re-read under the lock: a target may have moved
    // while the prompt waited, so nothing selection cached is reused.
    let removal = Removal {
        assessor: &assessor,
        content: ContentCheck::new(git, &root),
        config: &session.config,
        meta: wtconfig::meta_branches(git, &root)
            .inspect_err(|error| tracing::debug!(%error, "prune: cannot list wt metadata"))
            .ok(),
    };
    let mut removed = 0_usize;
    // Branches whose worktree was not removed (it turned dirty, or git refused)
    // stay checked out, so their `--all` branch candidate is skipped too.
    // Worktree candidates come first, one at a time; the bare branches left
    // then go in one batch.
    let mut kept: HashSet<&str> = HashSet::new();
    let mut branches: Vec<&str> = Vec::new();
    for verdict in &candidates {
        match &verdict.subject {
            Subject::Worktree {
                index,
                locked,
                head,
            } => {
                let worktree = &worktrees[*index];
                let pruned = remove_worktree(
                    cx,
                    &removal,
                    worktree,
                    head.as_deref(),
                    *locked && args.locked,
                )?;
                if pruned {
                    removed += 1;
                } else if let Some(branch) = &worktree.branch {
                    kept.insert(branch);
                }
            }
            Subject::Branch { name, .. } if kept.contains(name.as_str()) => {}
            Subject::Branch { name, .. } => branches.push(name),
        }
    }
    removed += remove_branches(cx, &removal, &branches)?;

    drop(lock);
    tracing::debug!(removed, "prune: done");
    cx.err.line(&format!("pruned {removed} item(s)"))?;
    Ok(0)
}

/// Blocks every bare-branch verdict a worktree still needs. A branch being
/// rebased or bisected is in use, although its worktree is detached meanwhile
/// and so names no branch: it is kept, and said so. When a worktree's state
/// cannot be read, the branch it holds is unknown, so every bare branch is
/// kept rather than trusting git to refuse the one in use.
fn keep_held_branches(assessor: &Assessor<'_>, worktrees: &[Worktree], verdicts: &mut [Verdict]) {
    let mut unreadable_holders: Vec<String> = Vec::new();
    let mut held: Vec<(HeldBranch, String)> = Vec::new();
    for w in worktrees {
        match assessor
            .admin_dir(w)
            .and_then(|dir| in_progress_branch_in(&dir))
        {
            Ok(Some(branch)) => held.push((branch, candidate_label(w))),
            Ok(None) => {}
            Err(error) => {
                tracing::warn!(target_wt = %w.path.display(), %error, "prune: cannot read in-progress branch");
                unreadable_holders.push(candidate_label(w));
            }
        }
    }
    let holders = unreadable_holders.join(", ");
    for verdict in verdicts {
        let Subject::Branch { name, .. } = &verdict.subject else {
            continue;
        };
        if let Some((branch, worktree)) = held.iter().find(|(b, _)| b.name == *name) {
            verdict.block = Some(Block::Held {
                activity: branch.activity,
                worktree: worktree.clone(),
            });
        } else if !unreadable_holders.is_empty() {
            verdict.block = Some(Block::HolderUnreadable(holders.clone()));
        }
    }
}

/// Runs `git fetch --all --prune` when the repository has any remote, so the
/// remote-tracking refs prune reads reflect the remote now. A failed fetch aborts
/// rather than letting a stale ref vouch for commits the remote no longer has.
fn fetch_remotes(git: &dyn GitCli, repo: &Repo, root: &Path) -> Result<()> {
    if repo.gix().remote_names().is_empty() {
        tracing::debug!("prune: no remotes; skipping fetch");
        return Ok(());
    }
    tracing::debug!("prune: fetching remotes");
    ops::fetch_all_prune(git, root).map_err(|e| {
        Error::operation(format!(
            "cannot fetch remotes: {e}\n(pass --no-fetch to trust the last fetch)"
        ))
    })?;
    Ok(())
}

/// The porcelain record for `worktree`, matched by path.
fn raw_for<'a>(raws: &'a [RawWorktree], worktree: &Worktree) -> Option<&'a RawWorktree> {
    raws.iter().find(|raw| raw.path == worktree.path)
}

/// What every removal under the repo lock shares. Nothing in it was read
/// before the confirmation prompt except the selection itself.
struct Removal<'r, 'a> {
    assessor: &'r Assessor<'a>,
    /// The merge state, re-read under the lock: a target may have moved while
    /// the prompt waited, so nothing selection cached is reused.
    content: ContentCheck<'a>,
    config: &'r crate::config::Config,
    /// The branches with `wt.*` metadata to clear, or `None` when that could
    /// not be read and every removal clears its section regardless.
    meta: Option<HashSet<String>>,
}

impl Removal<'_, '_> {
    /// Drops `branch`'s `wt.*` metadata, best-effort, spawning nothing when it
    /// has none.
    fn clear_meta(&self, branch: &str) {
        if self.meta.as_ref().is_none_or(|meta| meta.contains(branch)) {
            let assessor = self.assessor;
            let _ = wtconfig::clear_meta(assessor.git, assessor.root, branch);
        }
    }
}

/// Removes one worktree candidate, returning whether it was removed. `head` is
/// a detached worktree's HEAD as assessed; `unlock` overrides a lock
/// (`--locked` on a locked worktree). This is the per-worktree body of the prune
/// loop (spec §12).
///
/// The guards are re-read here, under the repo lock, because the confirmation
/// prompt may have waited long enough for the worktree to change: new edits, a
/// new commit on a detached HEAD, or a rebase started. A removal git refuses is
/// reported and leaves the worktree — and so its branch — in place.
fn remove_worktree(
    cx: &mut Cx,
    removal: &Removal<'_, '_>,
    worktree: &Worktree,
    head: Option<&str>,
    unlock: bool,
) -> Result<bool> {
    let assessor = removal.assessor;
    let (git, root) = (assessor.git, assessor.root);
    let label = candidate_label(worktree);
    if let Some(why) = changed_since_assessed(assessor, worktree, head) {
        cx.err.line(&format!("skipping {label}: {why}"))?;
        return Ok(false);
    }
    let path = worktree.path.to_string_lossy();
    // `--force` because the guards above are the safety decision (untracked
    // files included): git's own check also refuses a worktree with
    // submodules, and a lock needs it twice.
    // For a missing worktree this drops just its admin entry — never a blanket
    // `git worktree prune`, which would also drop missing worktrees prune chose
    // to keep.
    if let Err(error) = ops::worktree_remove(git, root, &path, true, unlock) {
        cx.err.line(&format!("could not remove {label}: {error}"))?;
        tracing::warn!(target_wt = %label, "prune: worktree remove failed");
        return Ok(false);
    }
    delete_merged_branch(removal, worktree);
    if let Some(branch) = &worktree.branch {
        removal.clear_meta(branch);
    }
    tracing::debug!(target_wt = %label, "prune: removed worktree");
    Ok(true)
}

/// Why a worktree may no longer be removed although it was a candidate at
/// selection, or `None` when it is unchanged: an operation now in progress, a
/// detached HEAD that moved off the assessed commit, or (without `--force`) new
/// uncommitted changes. A missing worktree must still be missing and idle.
fn changed_since_assessed(
    assessor: &Assessor<'_>,
    worktree: &Worktree,
    head: Option<&str>,
) -> Option<String> {
    if worktree.is_missing {
        // `git worktree remove --force` deletes whatever is at the path, so a
        // directory that came back (a remounted drive) — or one that cannot be
        // checked — must not be treated as gone.
        match std::fs::symlink_metadata(&worktree.path) {
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Ok(_) => return Some("reappeared since it was assessed; run prune again".into()),
            Err(_) => return Some(Block::Unreadable.message()),
        }
    }
    match in_progress_op(
        assessor.git,
        assessor.root,
        &worktree.path,
        worktree.is_missing,
    ) {
        Ok(None) => {}
        Ok(Some(op)) => return Some(Block::InProgress(op).message()),
        Err(_) => return Some(Block::Unreadable.message()),
    }
    if worktree.is_missing {
        return None;
    }
    let moved = "HEAD moved since it was assessed; run prune again";
    if let Some(head) = head {
        let now = assessor.git.run(
            &worktree.path,
            &["rev-parse", "--verify", "--quiet", "HEAD"],
        );
        if now.map(|h| h.trim().to_string()).ok().as_deref() != Some(head) {
            return Some(moved.into());
        }
    }
    // A branch worktree must still be on its branch: one that detached and
    // committed meanwhile holds that commit in its HEAD alone.
    if let Some(branch) = &worktree.branch {
        let now = assessor
            .git
            .run(&worktree.path, &["symbolic-ref", "--quiet", "HEAD"]);
        if now.map(|r| r.trim().to_string()).ok() != Some(branch_ref(branch)) {
            return Some(moved.into());
        }
    }
    // The same rule as the selection guard (untracked files included); a failed
    // status read counts as dirty, so the guard fails safe.
    if !assessor.args.force && !is_clean_for_removal(assessor.git, &worktree.path) {
        return Some(Block::Dirty.message());
    }
    None
}

/// Branch names per `git branch -D` call, so the argv stays bounded however
/// many branches go.
const BRANCHES_PER_DELETE: usize = 256;

/// What becomes of one bare-branch candidate under the lock.
#[derive(Debug, PartialEq, Eq)]
enum Fate {
    /// Safe, and still where it was checked: deleted.
    Delete,
    /// Kept, and said why.
    Skip(Block),
    /// Deleted by something else meanwhile: skipped quietly.
    Gone,
}

/// Deletes the bare-branch candidates `names`, in order, returning how many
/// were deleted. Each one's safety — every commit on a remote or the default
/// branch, or every change in the default branch — is re-checked under the
/// lock against its tip now (it may have moved since selection), for all of
/// them in one check. Without `--force` an unsafe branch is skipped. The rest
/// go with `git branch -D` (since `-d` only knows about HEAD and the
/// upstream), many per call. A branch already gone (deleted with its worktree)
/// is skipped quietly, and a delete failure is reported per branch and skipped
/// rather than aborting the whole prune.
fn remove_branches(cx: &mut Cx, removal: &Removal<'_, '_>, names: &[&str]) -> Result<usize> {
    if names.is_empty() {
        return Ok(0);
    }
    let assessor = removal.assessor;
    let (git, root) = (assessor.git, assessor.root);
    let tips = match branch_tips(git, root) {
        Ok(tips) => tips,
        Err(error) => {
            // Which branch is where is unknown, so none is deleted.
            tracing::warn!(%error, "prune: cannot read branch tips");
            for name in names {
                cx.err.line(&format!(
                    "skipping {name} (branch): {}",
                    Block::Unreadable.message()
                ))?;
            }
            return Ok(0);
        }
    };
    let present: Vec<(&str, Option<&str>)> = names
        .iter()
        .filter_map(|name| match tips.get(*name) {
            Some(id) => Some((*name, id.as_deref())),
            None => {
                tracing::debug!(branch = %name, "prune: branch already deleted");
                None
            }
        })
        .collect();
    let force = assessor.args.force;
    let recoverable = if force {
        HashSet::new()
    } else {
        let ids: Vec<String> = present
            .iter()
            .filter_map(|(_, id)| id.map(str::to_string))
            .collect();
        assessor.recoverable_now(&ids)
    };
    let mut outcomes: Vec<(&str, Fate)> = present
        .iter()
        .map(|&(name, id)| {
            // A tip with no commit has nothing to check, so nothing vouches
            // for it — as at selection.
            let safe = force
                || id.is_some_and(|id| {
                    recoverable.contains(id)
                        || assessor
                            .targets
                            .is_merged(&removal.content, assessor.repo, id)
                });
            let fate = if safe {
                Fate::Delete
            } else {
                Fate::Skip(Block::Unsafe)
            };
            (name, fate)
        })
        .collect();
    // The checks above take a while, and the lock keeps out only `wt`: a branch
    // that moved meanwhile was checked at a commit it no longer names, so it is
    // kept. What is left between this read and the delete is one spawn. Under
    // `--force` nothing was checked, so nothing is re-read.
    if !force && outcomes.iter().any(|(_, fate)| *fate == Fate::Delete) {
        let checked: HashMap<&str, Option<&str>> = present.iter().copied().collect();
        let now = branch_tips(git, root);
        for (name, fate) in &mut outcomes {
            if *fate != Fate::Delete {
                continue;
            }
            *fate = match &now {
                Ok(now) => match now.get(*name) {
                    None => Fate::Gone,
                    Some(id) if Some(id.as_deref()) != checked.get(name).copied() => {
                        Fate::Skip(Block::Moved)
                    }
                    Some(_) => Fate::Delete,
                },
                Err(_) => Fate::Skip(Block::Unreadable),
            };
        }
    }
    let doomed: Vec<&str> = outcomes
        .iter()
        .filter(|(_, fate)| *fate == Fate::Delete)
        .map(|(name, _)| *name)
        .collect();
    for chunk in doomed.chunks(BRANCHES_PER_DELETE) {
        // Whether each went is read back below; git's own messages are
        // translated, so they are not parsed.
        match ops::delete_branches(git, root, chunk) {
            Ok(out) if !out.success => {
                tracing::debug!(stderr = %out.stderr.trim(), "prune: batch delete left some branches");
            }
            Err(error) => tracing::debug!(%error, "prune: batch delete could not run"),
            Ok(_) => {}
        }
    }
    let left = if doomed.is_empty() {
        None
    } else {
        branch_tips(git, root)
            .inspect_err(|error| tracing::debug!(%error, "prune: cannot re-read branch tips"))
            .ok()
    };
    // Every branch is reported in candidate order, as it was checked.
    let mut deleted = 0_usize;
    for (name, fate) in outcomes {
        match fate {
            Fate::Skip(block) => {
                cx.err
                    .line(&format!("skipping {name} (branch): {}", block.message()))?;
                tracing::debug!(branch = %name, ?block, "prune: skip branch");
                continue;
            }
            Fate::Gone => {
                tracing::debug!(branch = %name, "prune: branch already deleted");
                continue;
            }
            Fate::Delete => {}
        }
        let gone = match &left {
            Some(left) => !left.contains_key(name),
            None => branch_is_gone(git, root, name),
        };
        // One the batch left is tried alone, which also yields its own error.
        if gone || delete_branch(cx, git, root, name)? {
            removal.clear_meta(name);
            tracing::debug!(branch = %name, "prune: deleted branch");
            deleted += 1;
        }
    }
    Ok(deleted)
}

/// Force-deletes the single branch `name`, reporting a failure; returns whether
/// it was deleted.
fn delete_branch(cx: &mut Cx, git: &dyn GitCli, root: &Path, name: &str) -> Result<bool> {
    match ops::delete_branch(git, root, name, true) {
        Ok(out) if out.success => Ok(true),
        Ok(out) => {
            cx.err
                .line(&format!("could not delete {name}: {}", out.stderr.trim()))?;
            tracing::warn!(branch = %name, "prune: branch delete failed");
            Ok(false)
        }
        Err(error) => {
            cx.err.line(&format!("could not delete {name}: {error}"))?;
            tracing::warn!(branch = %name, "prune: branch delete errored");
            Ok(false)
        }
    }
}

/// Every local branch's tip, read now: short name to commit id, or `None` for
/// a branch whose tip is no commit at all.
fn branch_tips(git: &dyn GitCli, root: &Path) -> Result<HashMap<String, Option<String>>> {
    let out = git.run(
        root,
        &[
            "for-each-ref",
            "--format=%(objectname) %(objecttype) %(refname)",
            "refs/heads/",
        ],
    )?;
    let mut tips = HashMap::new();
    for line in out.lines() {
        let mut fields = line.splitn(3, ' ');
        let (Some(id), Some(kind), Some(name)) = (fields.next(), fields.next(), fields.next())
        else {
            continue;
        };
        let Some(name) = name.strip_prefix("refs/heads/") else {
            continue;
        };
        // Reachability is a question about commits, and a tag object's own
        // id is never among them: a branch pointing at an annotated tag is
        // peeled to its commit — fully, which `%(*objectname)` does not do
        // for a tag of a tag on every git. One that cannot be peeled to a
        // commit (a tag of a tree) is present, with no commit to check.
        let id = if kind == "commit" {
            Some(id.to_string())
        } else {
            git.run(
                root,
                &[
                    "rev-parse",
                    "--verify",
                    "--quiet",
                    &format!("{id}^{{commit}}"),
                ],
            )
            .ok()
            .map(|peeled| peeled.trim().to_string())
        };
        tips.insert(name.to_string(), id);
    }
    Ok(tips)
}

/// Whether the local branch `name` is known to be gone: `rev-parse --quiet`
/// failed without a word, which is how it reports a missing ref. Any other
/// failure — git not running at all included — cannot tell, and reads as the
/// branch still being there.
fn branch_is_gone(git: &dyn GitCli, root: &Path, name: &str) -> bool {
    git.run_raw(
        root,
        &["rev-parse", "--verify", "--quiet", &branch_ref(name)],
    )
    .is_ok_and(|out| !out.success && out.stderr.trim().is_empty())
}

/// A human label for a verdict's subject (worktree or bare branch).
fn verdict_label(worktrees: &[Worktree], verdict: &Verdict) -> String {
    match &verdict.subject {
        Subject::Worktree { index, .. } => candidate_label(&worktrees[*index]),
        Subject::Branch { name, .. } => format!("{name} (branch)"),
    }
}

/// A candidate's label followed by why it qualifies, e.g. `feat (branch):
/// merged by content`.
fn verdict_text(worktrees: &[Worktree], verdict: &Verdict) -> String {
    format!(
        "{}: {}",
        verdict_label(worktrees, verdict),
        verdict.reason.label()
    )
}

/// A machine-readable (`--json`) line for a prune candidate. A worktree emits its
/// full row plus a `reason`; a bare branch emits a small object tagged
/// `"kind": "branch"`.
fn verdict_json(worktrees: &[Worktree], verdict: &Verdict) -> Result<String> {
    match &verdict.subject {
        Subject::Worktree { index, .. } => {
            let mut row = serde_json::to_value(&worktrees[*index])?;
            if let Some(fields) = row.as_object_mut() {
                fields.insert("reason".into(), verdict.reason.label().into());
            }
            Ok(row.to_string())
        }
        Subject::Branch { name, merged, safe } => Ok(serde_json::json!({
            "branch": name,
            "kind": "branch",
            "merged": merged,
            "safe": safe,
            "reason": verdict.reason.label(),
        })
        .to_string()),
    }
}

/// Deletes the branch of a removed worktree when `wt` created it, the config
/// allows it, and it is merged into the default branch by ancestry or content.
/// Best-effort: a branch left behind is reported as a later branch candidate
/// under `--all`, or simply kept.
fn delete_merged_branch(removal: &Removal<'_, '_>, worktree: &Worktree) {
    let assessor = removal.assessor;
    let Some(branch) = &worktree.branch else {
        return;
    };
    if !removal.config.remove_delete_merged_branch || assessor.targets.is_default(branch) {
        return;
    }
    let meta = wtconfig::read_meta(assessor.repo.gix(), branch);
    if !meta.created_by_wt {
        return;
    }
    if !assessor
        .targets
        .is_merged(&removal.content, assessor.repo, &branch_ref(branch))
    {
        return;
    }
    match ops::delete_branch(assessor.git, assessor.root, branch, true) {
        Ok(out) if !out.success => {
            tracing::debug!(branch = %branch, stderr = %out.stderr.trim(), "prune: delete merged branch failed");
        }
        Err(error) => {
            tracing::debug!(branch = %branch, %error, "prune: delete merged branch could not run");
        }
        Ok(_) => {}
    }
}

#[cfg(test)]
mod tests {
    use crate::cli::PruneArgs;
    use crate::error::Error;
    use crate::git::cli::RealGit;
    use crate::testutil::{CannedInput, TestRepo, give_upstream, make_wt, wt_dir};

    fn prune_args(merged: bool, gone: bool, dry_run: bool, force: bool) -> PruneArgs {
        PruneArgs {
            merged,
            gone,
            pushed: false,
            all: false,
            locked: false,
            no_fetch: false,
            dry_run,
            force,
        }
    }

    /// `--all` alone (no `--merged`/`--gone`), as a dry run.
    fn all_dry_run() -> PruneArgs {
        PruneArgs {
            all: true,
            ..prune_args(false, false, true, false)
        }
    }

    /// `--pushed` alone, as a dry run.
    fn pushed_dry_run() -> PruneArgs {
        PruneArgs {
            pushed: true,
            ..prune_args(false, false, true, false)
        }
    }

    /// `--all` for real, without `--force` (the confirmation is answered by `-y`).
    fn all_run() -> PruneArgs {
        PruneArgs {
            all: true,
            ..prune_args(false, false, false, false)
        }
    }

    /// Runs prune with `args` and returns stdout (the dry-run report).
    fn report(repo: &TestRepo, args: &PruneArgs) -> String {
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, args, false).unwrap();
        t.out.contents()
    }

    /// Runs prune with `args` and returns (stdout, stderr).
    fn report_both(repo: &TestRepo, args: &PruneArgs) -> (String, String) {
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, args, false).unwrap();
        (t.out.contents(), t.err.contents())
    }

    /// Runs prune with `args`, answering the prompt with `-y`, and returns stderr.
    fn run_yes(repo: &TestRepo, args: &PruneArgs) -> String {
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        t.cx.assume_yes = true;
        super::run(&mut t.cx, args, false).unwrap();
        t.err.contents()
    }

    /// Records a remote-tracking ref `refs/remotes/origin/<remote_name>` at
    /// `name`'s tip, as if the branch had been pushed there.
    fn push_tip(repo: &TestRepo, name: &str, remote_name: &str) {
        repo.git(&[
            "update-ref",
            &format!("refs/remotes/origin/{remote_name}"),
            &format!("refs/heads/{name}"),
        ]);
    }

    fn has_branch(repo: &TestRepo, name: &str) -> bool {
        !repo.git(&["branch", "--list", name]).trim().is_empty()
    }

    /// A branch at the current tip — an ancestor of the default branch (merged),
    /// with no worktree.
    fn bare_branch(repo: &TestRepo, name: &str) {
        repo.git(&["branch", name]);
    }

    /// A branch carrying its own commit, so it is NOT an ancestor of the default
    /// branch; leaves the repo back on `main`.
    fn diverged_branch(repo: &TestRepo, name: &str) {
        repo.git(&["checkout", "-q", "-b", name]);
        repo.write(&format!("{name}.txt"), "x\n");
        repo.commit_all("diverge");
        repo.git(&["checkout", "-q", "main"]);
    }

    /// Configures an upstream for `name` whose tracking ref does not exist, so
    /// `upstream_of(...).is_gone` is true.
    fn give_gone_upstream(repo: &TestRepo, name: &str) {
        repo.git(&["config", &format!("branch.{name}.remote"), "origin"]);
        repo.git(&[
            "config",
            &format!("branch.{name}.merge"),
            &format!("refs/heads/{name}"),
        ]);
    }

    /// Creates a worktree on `branch` and commits in it so the branch diverges
    /// from main — i.e. it is not merged.
    fn make_unmerged_wt(repo: &TestRepo, branch: &str) {
        make_wt(repo, branch);
        let wt = wt_dir(repo, branch);
        std::fs::write(wt.join("change.txt"), "x\n").unwrap();
        let dir = wt.to_string_lossy().into_owned();
        repo.git(&["-C", &dir, "add", "-A"]);
        repo.git(&["-C", &dir, "commit", "-q", "-m", "unmerged change"]);
    }

    #[test]
    fn requires_a_mode_flag() {
        let repo = TestRepo::init();
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        let err =
            super::run(&mut t.cx, &prune_args(false, false, false, false), false).unwrap_err();
        assert_eq!(err.exit_code(), 2);
    }

    #[test]
    fn dry_run_reports_merged_candidates_without_removing() {
        let repo = TestRepo::init();
        make_wt(&repo, "merged-wt"); // merged into main (no new commits)
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &prune_args(true, false, true, false), false).unwrap();
        assert!(t.out.contents().contains("would remove merged-wt"));
        // Still present (dry-run).
        assert!(repo.git(&["worktree", "list"]).contains("merged-wt"));
    }

    #[test]
    fn dry_run_reports_nothing_when_no_candidates() {
        let repo = TestRepo::init();
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &prune_args(true, false, true, false), false).unwrap();
        // A dry-run that finds nothing says so on stderr; stdout stays empty.
        assert!(t.err.contents().contains("nothing to prune"));
        assert!(t.out.contents().is_empty());
    }

    #[test]
    fn force_prunes_merged_worktree_and_branch() {
        let repo = TestRepo::init();
        make_wt(&repo, "merged-wt");
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &prune_args(true, false, false, true), false).unwrap();
        assert!(!repo.git(&["worktree", "list"]).contains("merged-wt"));
        assert!(
            repo.git(&["branch", "--list", "merged-wt"])
                .trim()
                .is_empty()
        );
    }

    /// Prune's removal loop deletes worktrees, branches, and `wt.*` metadata,
    /// so it runs under the advisory repo lock (issue #99). A concurrent holder
    /// blocks it outright rather than letting it interleave — and nothing is
    /// removed when it does.
    #[test]
    fn prune_is_excluded_by_a_concurrent_lock_holder() {
        let repo = TestRepo::init();
        make_wt(&repo, "merged-wt");
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        let ws = crate::worktree::Workspace::discover(repo.root(), &t.cx.env, &RealGit).unwrap();
        let held = ws.lock().unwrap();
        let err = super::run(&mut t.cx, &prune_args(true, false, false, true), false).unwrap_err();
        drop(held);
        assert!(matches!(err, Error::LockUnavailable { .. }), "{err:?}");
        assert!(repo.git(&["worktree", "list"]).contains("merged-wt"));
    }

    #[test]
    fn confirmation_yes_prunes() {
        let repo = TestRepo::init();
        make_wt(&repo, "merged-wt");
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        t.cx.input = Box::new(CannedInput::new(&["y"]));
        super::run(&mut t.cx, &prune_args(true, false, false, false), false).unwrap();
        assert!(t.err.contents().contains("Proceed?"));
        assert!(!repo.git(&["worktree", "list"]).contains("merged-wt"));
    }

    /// `--yes` answers the prompt but is not `--force`: a dirty worktree is still
    /// skipped. Keeping the two separable is what makes `-y` safe in a script.
    #[test]
    fn assume_yes_skips_prompt_but_not_the_dirty_guard() {
        let repo = TestRepo::init();
        make_wt(&repo, "clean-wt");
        make_wt(&repo, "dirty-wt");
        std::fs::write(wt_dir(&repo, "dirty-wt").join("README.md"), "dirty\n").unwrap();

        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        t.cx.assume_yes = true;
        // No CannedInput: reading stdin at all would return "" and abort.
        super::run(&mut t.cx, &prune_args(true, false, false, false), false).unwrap();

        assert!(t.err.contents().contains("Proceed? [y/N] y (--yes)"));
        assert!(
            t.err
                .contents()
                .contains("skipping dirty-wt: uncommitted changes; use --force")
        );
        let list = repo.git(&["worktree", "list"]);
        assert!(!list.contains("clean-wt"), "{list}");
        assert!(list.contains("dirty-wt"), "{list}");
    }

    #[test]
    fn confirmation_no_aborts() {
        let repo = TestRepo::init();
        make_wt(&repo, "merged-wt");
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        t.cx.input = Box::new(CannedInput::new(&["n"]));
        super::run(&mut t.cx, &prune_args(true, false, false, false), false).unwrap();
        assert!(t.err.contents().contains("aborted"));
        assert!(repo.git(&["worktree", "list"]).contains("merged-wt"));
    }

    #[test]
    fn gone_prunes_missing_worktrees() {
        let repo = TestRepo::init();
        make_wt(&repo, "goner");
        let repo_name = repo.root().file_name().unwrap().to_string_lossy();
        let wt_path = repo
            .root()
            .parent()
            .unwrap()
            .join(format!("{repo_name}.worktrees/{repo_name}-goner"));
        std::fs::remove_dir_all(&wt_path).unwrap();
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &prune_args(false, true, false, true), false).unwrap();
        assert!(!repo.git(&["worktree", "list"]).contains("goner"));
    }

    #[test]
    fn json_lists_candidates_without_removing() {
        let repo = TestRepo::init();
        make_wt(&repo, "merged-wt");
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &prune_args(true, false, false, false), true).unwrap();
        let out = t.out.contents();
        assert_eq!(out.lines().count(), 1);
        let v: serde_json::Value = serde_json::from_str(out.trim()).unwrap();
        assert_eq!(v["branch"], serde_json::json!("merged-wt"));
        assert_eq!(v["reason"], serde_json::json!("merged"));
        assert_eq!(v["schema_version"], serde_json::json!(1));
        // The row is the full listing row: the fields only enrichment fills.
        assert_eq!(v["dirty"], serde_json::json!(false));
        assert_eq!(v["has_untracked"], serde_json::json!(false));
        assert!(v["commit"]["hash"].is_string(), "{v}");
        // --json implies dry-run: still present.
        assert!(repo.git(&["worktree", "list"]).contains("merged-wt"));
    }

    #[test]
    fn a_remote_default_at_the_local_commit_is_one_target() {
        let repo = TestRepo::init();
        repo.git(&["update-ref", "refs/remotes/origin/main", "refs/heads/main"]);
        repo.git(&[
            "symbolic-ref",
            "refs/remotes/origin/HEAD",
            "refs/remotes/origin/main",
        ]);
        let r = crate::git::discover::Repo::discover(repo.root()).unwrap();
        assert_eq!(super::MergeTargets::resolve(&r).refs, ["refs/heads/main"]);
        // Once they differ, both count.
        repo.write("new.txt", "x\n");
        repo.commit_all("local only");
        let r = crate::git::discover::Repo::discover(repo.root()).unwrap();
        assert_eq!(
            super::MergeTargets::resolve(&r).refs,
            ["refs/heads/main", "refs/remotes/origin/main"]
        );
    }

    #[test]
    fn a_branch_pointing_at_a_tag_of_unpushed_work_is_unsafe() {
        // The tag object's own id is never printed by `rev-list`; only the
        // commit it peels to is, so that is what must be checked.
        let repo = TestRepo::init();
        diverged_branch(&repo, "work");
        repo.git(&["tag", "-a", "-m", "note", "v-work", "work"]);
        let tag = repo.git(&["rev-parse", "v-work"]).trim().to_string();
        // Porcelain refuses a tag on a branch; the ref file does not.
        std::fs::write(
            repo.root().join(".git/refs/heads/tagged"),
            format!("{tag}\n"),
        )
        .unwrap();
        repo.git(&["branch", "-D", "work"]);
        repo.git(&["tag", "-d", "v-work"]);
        let pushed = PruneArgs {
            pushed: true,
            ..prune_args(false, false, false, false)
        };
        let err = run_yes(&repo, &pushed);
        assert!(!err.contains("tagged"), "{err}");
        assert!(has_branch(&repo, "tagged"));
    }

    #[test]
    fn branch_skips_and_failures_are_reported_in_candidate_order() {
        // Three merged branches; while the prompt waits, the middle one is
        // moved onto work found nowhere else, so its re-check fails, and git
        // refuses to delete the other two.
        let repo = TestRepo::init();
        bare_branch(&repo, "a-stuck");
        bare_branch(&repo, "b-unsafe");
        bare_branch(&repo, "c-stuck");
        diverged_branch(&repo, "wip"); // selected by no mode
        let mut t = crate::testutil::test_cx_with_git(
            &[],
            repo.root().to_str().unwrap(),
            std::sync::Arc::new(Refuses(|args| {
                (args.first() == Some(&"branch") && args.iter().any(|a| a.ends_with("-stuck")))
                    .then_some("fatal: no")
            })),
        );
        t.cx.input = Box::new(git_then_confirm(
            &repo,
            &["branch", "-f", "b-unsafe", "wip"],
        ));
        super::run(&mut t.cx, &all_run(), false).unwrap();
        let err = t.err.contents();
        let at = |needle: &str| {
            err.find(needle)
                .unwrap_or_else(|| panic!("{needle}: {err}"))
        };
        assert!(at("could not delete a-stuck") < at("skipping b-unsafe (branch)"));
        assert!(at("skipping b-unsafe (branch)") < at("could not delete c-stuck"));
    }

    #[test]
    fn a_branch_that_moves_before_its_delete_is_kept() {
        // Stands in for a commit made by a git outside `wt` between the
        // safety check and the delete: the branch moves on the re-read.
        let repo = TestRepo::init();
        bare_branch(&repo, "old");
        let dir = repo.root().to_path_buf();
        let err = run_yes_on_tips_read(&repo, move |read| {
            if read == RE_READ {
                let tree = repo_git(&dir, &["rev-parse", "old^{tree}"]);
                let commit = repo_git(&dir, &["commit-tree", &tree, "-p", "old", "-m", "late"]);
                repo_git(&dir, &["update-ref", "refs/heads/old", &commit]);
            }
            false
        });
        assert!(
            err.contains("skipping old (branch): moved since it was checked"),
            "{err}"
        );
        assert!(has_branch(&repo, "old"));
    }

    #[test]
    fn a_branch_deleted_elsewhere_before_its_delete_is_skipped_quietly() {
        let repo = TestRepo::init();
        bare_branch(&repo, "old");
        let dir = repo.root().to_path_buf();
        let err = run_yes_on_tips_read(&repo, move |read| {
            if read == RE_READ {
                repo_git(&dir, &["branch", "-D", "old"]);
            }
            false
        });
        assert!(!err.contains("skipping old"), "{err}");
        assert!(!err.contains("could not delete"), "{err}");
        assert!(err.contains("pruned 0 item(s)"), "{err}");
    }

    #[test]
    fn an_unreadable_re_read_before_the_delete_deletes_nothing() {
        let repo = TestRepo::init();
        bare_branch(&repo, "old");
        let err = run_yes_on_tips_read(&repo, |read| read == RE_READ);
        assert!(
            err.contains("skipping old (branch): cannot read its git state"),
            "{err}"
        );
        assert!(err.contains("pruned 0 item(s)"), "{err}");
        assert!(has_branch(&repo, "old"));
    }

    #[test]
    fn a_branch_moved_onto_a_tag_of_a_tree_while_the_prompt_waits_is_kept() {
        // No commit to check, so nothing vouches for it: `rev-list` would
        // print nothing for a tree, which must not read as "recoverable".
        let repo = TestRepo::init();
        bare_branch(&repo, "old");
        repo.git(&["tag", "-a", "-m", "a tree", "v-tree", "HEAD^{tree}"]);
        let tag = repo.git(&["rev-parse", "v-tree"]).trim().to_string();
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        let root = repo.root().to_path_buf();
        t.cx.input = Box::new(ActsThenConfirms(Box::new(move || {
            std::fs::write(root.join(".git/refs/heads/old"), format!("{tag}\n")).unwrap();
        })));
        super::run(&mut t.cx, &prune_args(true, false, false, false), false).unwrap();
        let err = t.err.contents();
        assert!(
            err.contains("skipping old (branch): has work on no remote"),
            "{err}"
        );
        assert!(has_branch(&repo, "old"));
    }

    #[test]
    fn an_unreadable_read_back_asks_git_branch_by_branch() {
        // The batch deleted the branch, but listing what is left fails: each
        // branch is then asked after on its own, and counts once gone.
        let repo = TestRepo::init();
        bare_branch(&repo, "old");
        let err = run_yes_on_tips_read(&repo, |read| read == READ_BACK);
        assert!(err.contains("pruned 1 item(s)"), "{err}");
        assert!(!err.contains("could not delete"), "{err}");
        assert!(!has_branch(&repo, "old"));
    }

    /// The `for-each-ref` reads of the branch removal: under the lock, right
    /// before the delete, and after it.
    const RE_READ: usize = 1;
    const READ_BACK: usize = 2;

    /// `git` in `dir` with the fixtures' sandboxed environment (a pinned
    /// identity, no global config), trimmed stdout. For actions that cannot
    /// borrow the [`TestRepo`].
    fn repo_git(dir: &std::path::Path, args: &[&str]) -> String {
        crate::testutil::run_git(dir, args).trim().to_string()
    }

    /// Runs a real `--all -y` prune whose git calls `on_read(n)` before the
    /// `n`th `for-each-ref` (from 0); it returning `true` fails that read.
    /// Returns stderr.
    fn run_yes_on_tips_read(
        repo: &TestRepo,
        on_read: impl Fn(usize) -> bool + Send + Sync + 'static,
    ) -> String {
        let git = std::sync::Arc::new(OnTipsRead {
            reads: std::sync::atomic::AtomicUsize::new(0),
            on_read: Box::new(on_read),
        });
        let mut t = crate::testutil::test_cx_with_git(&[], repo.root().to_str().unwrap(), git);
        t.cx.assume_yes = true;
        super::run(&mut t.cx, &all_run(), false).unwrap();
        t.err.contents()
    }

    /// Real git that hands each `for-each-ref` to `on_read` first.
    struct OnTipsRead {
        reads: std::sync::atomic::AtomicUsize,
        on_read: Box<dyn Fn(usize) -> bool + Send + Sync>,
    }
    impl crate::git::cli::GitCli for OnTipsRead {
        fn run_raw(
            &self,
            repo: &std::path::Path,
            args: &[&str],
        ) -> crate::error::Result<crate::git::cli::GitOutput> {
            use std::sync::atomic::Ordering;
            if args.first() == Some(&"for-each-ref") {
                let read = self.reads.fetch_add(1, Ordering::SeqCst);
                if (self.on_read)(read) {
                    return Ok(crate::git::cli::GitOutput {
                        success: false,
                        stdout: String::new(),
                        stderr: "fatal: refs".into(),
                    });
                }
            }
            RealGit.run_raw(repo, args)
        }
    }

    #[test]
    fn merged_bare_branch_is_pruned() {
        let repo = TestRepo::init();
        bare_branch(&repo, "old"); // no worktree, merged into main
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &prune_args(true, false, false, true), false).unwrap();
        assert!(repo.git(&["branch", "--list", "old"]).trim().is_empty());
        // The default/current branch is never touched.
        assert!(repo.git(&["branch", "--list", "main"]).contains("main"));
    }

    #[test]
    fn gone_merged_bare_branch_is_pruned() {
        let repo = TestRepo::init();
        bare_branch(&repo, "old");
        give_gone_upstream(&repo, "old"); // merged AND upstream gone
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &prune_args(false, true, false, true), false).unwrap();
        assert!(repo.git(&["branch", "--list", "old"]).trim().is_empty());
    }

    #[test]
    fn gone_unmerged_branch_needs_force() {
        let repo = TestRepo::init();
        diverged_branch(&repo, "wip"); // not an ancestor of main
        give_gone_upstream(&repo, "wip");
        // Without --force the protected branch is skipped (confirmation says yes).
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        t.cx.input = Box::new(CannedInput::new(&["y"]));
        super::run(&mut t.cx, &prune_args(false, true, false, false), false).unwrap();
        assert!(t.err.contents().contains("use --force"));
        assert!(repo.git(&["branch", "--list", "wip"]).contains("wip"));
        // With --force it is force-deleted.
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &prune_args(false, true, false, true), false).unwrap();
        assert!(repo.git(&["branch", "--list", "wip"]).trim().is_empty());
    }

    #[test]
    fn all_selects_merged_and_gone() {
        let repo = TestRepo::init();
        bare_branch(&repo, "old"); // merged only
        diverged_branch(&repo, "wip"); // gone only, commits nowhere else
        give_gone_upstream(&repo, "wip");
        let (all, skips) = report_both(&repo, &all_dry_run());
        assert!(all.contains("would remove old (branch): merged"), "{all}");
        // The gone branch qualifies, but its commits exist nowhere else: the
        // preview says it will be skipped rather than promising its removal.
        assert!(!all.contains("wip"), "{all}");
        assert!(
            skips.contains(
                "skipping wip (branch): has work on no remote and could not confirm its \
                 changes are in the default branch; use --force"
            ),
            "{skips}"
        );
        // Same selection as `--merged --gone` here; each mode alone picks one.
        assert_eq!(all, report(&repo, &prune_args(true, true, true, false)));
        assert!(!report(&repo, &prune_args(true, false, true, false)).contains("wip"));
        assert!(!report(&repo, &prune_args(false, true, true, false)).contains("old"));
        // Nothing was removed.
        assert!(has_branch(&repo, "old"));
        assert!(has_branch(&repo, "wip"));
        // A real `--all` deletes the merged branch but keeps the gone branch whose
        // commits exist nowhere else.
        let err = run_yes(&repo, &all_run());
        assert!(err.contains("skipping wip"), "{err}");
        assert!(!has_branch(&repo, "old"));
        assert!(has_branch(&repo, "wip"));
    }

    #[test]
    fn all_selects_merged_and_missing_worktrees() {
        // `--all` covers both worktree paths: a merged worktree, and a missing
        // one whose branch is unmerged (so only the `--gone` path selects it).
        let repo = TestRepo::init();
        make_wt(&repo, "done");
        make_unmerged_wt(&repo, "lost");
        std::fs::remove_dir_all(wt_dir(&repo, "lost")).unwrap();
        let all = report(&repo, &all_dry_run());
        assert!(all.contains("would remove done: merged\n"), "{all}");
        assert!(all.contains("would remove lost: missing\n"), "{all}");
        assert!(!report(&repo, &prune_args(true, false, true, false)).contains("lost"));
        assert!(!report(&repo, &prune_args(false, true, true, false)).contains("done"));
    }

    #[test]
    fn pushed_branch_is_selected_by_pushed_and_all_only() {
        // Diverged from main but every commit is on origin: neither merged nor
        // gone, yet deleting it loses nothing.
        let repo = TestRepo::init();
        diverged_branch(&repo, "feat");
        give_upstream(&repo, "feat");
        diverged_branch(&repo, "local"); // commits exist only here
        let pushed = report(&repo, &pushed_dry_run());
        assert!(pushed.contains("would remove feat (branch)"), "{pushed}");
        assert!(!pushed.contains("local"), "{pushed}");
        let all = report(&repo, &all_dry_run());
        assert!(all.contains("would remove feat (branch)"), "{all}");
        assert!(!all.contains("local"), "{all}");
        assert!(!report(&repo, &prune_args(true, true, true, false)).contains("feat"));
        // Deleted without --force; the local-only branch is untouched.
        let err = run_yes(&repo, &all_run());
        assert!(!err.contains("skipping"), "{err}");
        assert!(!has_branch(&repo, "feat"));
        assert!(has_branch(&repo, "local"));
    }

    #[test]
    fn pushed_branch_without_upstream_is_selected() {
        // Pushed without `-u`: no upstream, but origin holds the tip.
        let repo = TestRepo::init();
        diverged_branch(&repo, "feat");
        push_tip(&repo, "feat", "feat");
        let pushed = report(&repo, &pushed_dry_run());
        assert!(pushed.contains("would remove feat (branch)"), "{pushed}");
    }

    #[test]
    fn pushed_branch_that_moved_since_push_is_not_selected() {
        let repo = TestRepo::init();
        diverged_branch(&repo, "feat");
        give_upstream(&repo, "feat");
        repo.git(&["checkout", "-q", "feat"]);
        repo.write("more.txt", "x\n");
        repo.commit_all("unpushed");
        repo.git(&["checkout", "-q", "main"]);
        assert!(!report(&repo, &pushed_dry_run()).contains("feat"));
    }

    #[test]
    fn merged_counts_the_remote_default_branch() {
        // Merged on origin while local main lags behind: `--merged` sees it via
        // origin/HEAD's target.
        let repo = TestRepo::init();
        diverged_branch(&repo, "feat");
        repo.git(&["update-ref", "refs/remotes/origin/main", "refs/heads/feat"]);
        repo.git(&[
            "symbolic-ref",
            "refs/remotes/origin/HEAD",
            "refs/remotes/origin/main",
        ]);
        let merged = report(&repo, &prune_args(true, false, true, false));
        assert!(merged.contains("would remove feat (branch)"), "{merged}");
        // Deleted for real without --force.
        run_yes(&repo, &prune_args(true, false, false, false));
        assert!(!has_branch(&repo, "feat"));
        assert!(has_branch(&repo, "main"));
    }

    #[test]
    fn gone_branch_whose_commits_survive_needs_no_force() {
        // Upstream deleted, but the commits live on under another remote ref.
        let repo = TestRepo::init();
        diverged_branch(&repo, "shipped");
        give_gone_upstream(&repo, "shipped");
        push_tip(&repo, "shipped", "release");
        let err = run_yes(&repo, &prune_args(false, true, false, false));
        assert!(!err.contains("skipping"), "{err}");
        assert!(!has_branch(&repo, "shipped"));
    }

    #[test]
    fn all_keeps_the_worktree_of_a_live_pushed_branch() {
        // Pushed and live (upstream present): the branch is recoverable, but the
        // checkout is active work, so `--all` touches neither.
        let repo = TestRepo::init();
        make_unmerged_wt(&repo, "live");
        give_upstream(&repo, "live");
        let all = report(&repo, &all_dry_run());
        assert!(!all.contains("live"), "{all}");
    }

    #[test]
    fn all_removes_a_gone_worktree_and_its_recoverable_branch_in_one_pass() {
        let repo = TestRepo::init();
        make_unmerged_wt(&repo, "shipped");
        give_gone_upstream(&repo, "shipped");
        push_tip(&repo, "shipped", "release");
        let all = report(&repo, &all_dry_run());
        assert!(
            all.contains("would remove shipped: upstream gone\n"),
            "{all}"
        );
        assert!(
            all.contains("would remove shipped (branch): upstream gone"),
            "{all}"
        );
        // `--gone` alone removes the worktree and keeps the (unmerged) branch.
        assert!(!report(&repo, &prune_args(false, true, true, false)).contains("(branch)"));
        let err = run_yes(&repo, &all_run());
        assert!(err.contains("pruned 2 item(s)"), "{err}");
        assert!(!repo.git(&["worktree", "list"]).contains("shipped"));
        assert!(!has_branch(&repo, "shipped"));
    }

    #[test]
    fn all_removes_a_merged_worktree_and_branch_without_noise() {
        // The merged branch goes with its worktree; the branch candidate then
        // finds it already gone and skips quietly.
        let repo = TestRepo::init();
        make_wt(&repo, "done");
        let err = run_yes(&repo, &all_run());
        assert!(!err.contains("could not delete"), "{err}");
        assert!(!repo.git(&["worktree", "list"]).contains("done"));
        assert!(!has_branch(&repo, "done"));
    }

    #[test]
    fn all_deletes_the_branch_of_a_missing_worktree_in_one_pass() {
        // The missing worktree is still registered until Git reconciles its
        // metadata; the branch delete must not trip over that.
        let repo = TestRepo::init();
        make_wt(&repo, "done");
        std::fs::remove_dir_all(wt_dir(&repo, "done")).unwrap();
        let err = run_yes(&repo, &all_run());
        assert!(!err.contains("could not delete"), "{err}");
        assert!(!repo.git(&["worktree", "list"]).contains("done"));
        assert!(!has_branch(&repo, "done"));
    }

    #[test]
    fn pushed_alone_never_selects_worktrees() {
        let repo = TestRepo::init();
        make_unmerged_wt(&repo, "live");
        give_upstream(&repo, "live");
        std::fs::remove_dir_all(wt_dir(&repo, "live")).unwrap(); // even a missing one
        assert!(!report(&repo, &pushed_dry_run()).contains("live"));
    }

    #[test]
    fn all_keeps_the_branch_of_a_skipped_dirty_worktree() {
        let repo = TestRepo::init();
        make_unmerged_wt(&repo, "busy");
        give_gone_upstream(&repo, "busy");
        push_tip(&repo, "busy", "release");
        std::fs::write(wt_dir(&repo, "busy").join("README.md"), "dirty\n").unwrap();
        let err = run_yes(&repo, &all_run());
        assert!(err.contains("skipping busy: uncommitted changes"), "{err}");
        assert!(!err.contains("could not delete"), "{err}");
        assert!(has_branch(&repo, "busy"));
    }

    #[test]
    fn a_failed_recoverability_check_counts_as_unsafe() {
        let repo = TestRepo::init();
        // A tip that does not resolve, or a `rev-list` that fails (here on a
        // commit the repository lacks), must never read as "safe to delete".
        let args = all_dry_run();
        with_assessor(&repo, &args, |assessor| {
            assert!(!assessor.recoverable("refs/heads/no-such-branch"));
            let main = repo.git(&["rev-parse", "main"]).trim().to_string();
            let unknown = "0123456789abcdef0123456789abcdef01234567".to_string();
            // One bad commit fails the batch; each is then checked alone, so
            // only the bad one loses its answer (`main` keeps itself).
            assert_eq!(
                assessor.recoverable_now(&[main.clone(), unknown]),
                std::collections::HashSet::from([main])
            );
        });
    }

    /// Runs `f` with an [`super::Assessor`] over `repo` for `args`.
    fn with_assessor(repo: &TestRepo, args: &PruneArgs, f: impl FnOnce(&super::Assessor<'_>)) {
        with_assessor_git(repo, args, &RealGit, f);
    }

    fn with_assessor_git(
        repo: &TestRepo,
        args: &PruneArgs,
        git: &dyn crate::git::cli::GitCli,
        f: impl FnOnce(&super::Assessor<'_>),
    ) {
        let r = crate::git::discover::Repo::discover(repo.root()).unwrap();
        let targets = super::MergeTargets::resolve(&r);
        let assessor = super::Assessor::new(git, repo.root(), &r, args, &targets);
        f(&assessor);
    }

    #[test]
    fn pushed_alone_satisfies_the_mode_requirement() {
        let repo = TestRepo::init();
        let err = run_yes(&repo, &pushed_dry_run());
        assert!(err.contains("nothing to prune"), "{err}");
    }

    /// A clone-like repo: `main` and `feat` pushed to a bare `origin`, with
    /// `feat` tracking `origin/feat`. Returns (local, remote).
    fn repo_with_remote() -> (TestRepo, TestRepo) {
        let remote = TestRepo::init_bare();
        let repo = TestRepo::init();
        repo.git(&["remote", "add", "origin", remote.root().to_str().unwrap()]);
        diverged_branch(&repo, "feat");
        repo.git(&["push", "-q", "-u", "origin", "main", "feat"]);
        repo.git(&["remote", "set-head", "origin", "main"]);
        (repo, remote)
    }

    fn json_branch(repo: &TestRepo, args: &PruneArgs, name: &str) -> Option<serde_json::Value> {
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, args, true).unwrap();
        t.out
            .contents()
            .lines()
            .map(|l| serde_json::from_str::<serde_json::Value>(l).unwrap())
            .find(|v| v["branch"] == serde_json::json!(name))
    }

    #[test]
    fn fetch_refreshes_remote_refs_before_judging_safety() {
        // The branch was deleted on origin since the last fetch. The stale
        // tracking ref would vouch for its commits; the fetch shows they are
        // gone, so the branch is no longer safe to delete.
        let (repo, remote) = repo_with_remote();
        remote.git(&["branch", "-D", "feat"]);
        let offline = PruneArgs {
            no_fetch: true,
            ..all_dry_run()
        };
        let stale = json_branch(&repo, &offline, "feat").expect("selected offline");
        assert_eq!(stale["safe"], serde_json::json!(true));
        assert_eq!(stale["reason"], serde_json::json!("pushed"));
        // Fresh, it is gone and unsafe: `--json` lists only what would be
        // removed, so it drops out, and the text preview says why.
        assert!(json_branch(&repo, &all_dry_run(), "feat").is_none());
        let (_, skips) = report_both(&repo, &all_dry_run());
        assert!(
            skips.contains("skipping feat (branch): has work on no remote"),
            "{skips}"
        );
        // With --force it would be removed, and says it is unsafe.
        let forced = PruneArgs {
            force: true,
            ..all_dry_run()
        };
        let fresh = json_branch(&repo, &forced, "feat").expect("selected as gone");
        assert_eq!(fresh["safe"], serde_json::json!(false));
        assert_eq!(fresh["reason"], serde_json::json!("upstream gone"));
        assert!(has_branch(&repo, "feat"));
    }

    #[test]
    fn failed_fetch_aborts_unless_no_fetch() {
        let repo = TestRepo::init();
        repo.git(&[
            "remote",
            "add",
            "origin",
            "/nonexistent/wt-prune-remote.git",
        ]);
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        let err = super::run(&mut t.cx, &all_dry_run(), false).unwrap_err();
        assert!(err.to_string().contains("--no-fetch"), "{err}");
        // `--merged` alone reads no remote state, so it never fetches.
        report(&repo, &prune_args(true, false, true, false));
        let offline = PruneArgs {
            no_fetch: true,
            ..all_dry_run()
        };
        report(&repo, &offline);
    }

    #[test]
    fn default_and_current_never_deleted() {
        let repo = TestRepo::init(); // only `main` (default + current)
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &prune_args(true, true, false, true), false).unwrap();
        assert!(t.err.contents().contains("nothing to prune"));
        assert!(repo.git(&["branch", "--list", "main"]).contains("main"));
    }

    #[test]
    fn merged_only_skips_unmerged_worktree() {
        // A worktree whose branch is not merged into main must never be a
        // `--merged` prune candidate — a guard against pruning live work.
        let repo = TestRepo::init();
        make_unmerged_wt(&repo, "wip");
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &prune_args(true, false, true, false), false).unwrap();
        assert!(t.err.contents().contains("nothing to prune"));
    }

    #[test]
    fn dry_run_lists_bare_branch_without_deleting() {
        let repo = TestRepo::init();
        bare_branch(&repo, "old");
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &prune_args(true, false, true, false), false).unwrap();
        assert!(t.out.contents().contains("would remove old (branch)"));
        assert!(repo.git(&["branch", "--list", "old"]).contains("old"));
    }

    #[test]
    fn branch_with_worktree_uses_worktree_path() {
        let repo = TestRepo::init();
        make_wt(&repo, "merged-wt"); // branch + worktree
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &prune_args(true, false, false, true), false).unwrap();
        // Pruned once via the worktree path — not double-counted as a bare branch.
        assert!(!repo.git(&["worktree", "list"]).contains("merged-wt"));
        assert!(
            repo.git(&["branch", "--list", "merged-wt"])
                .trim()
                .is_empty()
        );
        assert!(t.err.contents().contains("pruned 1 item(s)"));
    }

    #[test]
    fn json_lists_bare_branch() {
        let repo = TestRepo::init();
        bare_branch(&repo, "old");
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &prune_args(true, false, false, false), true).unwrap();
        let out = t.out.contents();
        let v: serde_json::Value = serde_json::from_str(out.trim()).unwrap();
        assert_eq!(v["branch"], serde_json::json!("old"));
        assert_eq!(v["kind"], serde_json::json!("branch"));
        assert_eq!(v["merged"], serde_json::json!(true));
        assert_eq!(v["safe"], serde_json::json!(true));
        assert_eq!(v["reason"], serde_json::json!("merged"));
        // --json implies dry-run: still present.
        assert!(repo.git(&["branch", "--list", "old"]).contains("old"));
    }

    /// Adds a detached worktree named `detached-<name>` (beside the repo) at
    /// `rev`, returning its path.
    fn detached_wt(repo: &TestRepo, name: &str, rev: &str) -> std::path::PathBuf {
        let path = repo
            .root()
            .parent()
            .unwrap()
            .join(format!("detached-{name}"));
        repo.git(&[
            "worktree",
            "add",
            "-q",
            "--detach",
            path.to_str().unwrap(),
            rev,
        ]);
        path
    }

    /// Commits a new file in the worktree at `path`, returning the new HEAD.
    fn commit_in(repo: &TestRepo, path: &std::path::Path, file: &str) -> String {
        std::fs::write(path.join(file), "x\n").unwrap();
        let dir = path.to_string_lossy().into_owned();
        repo.git(&["-C", &dir, "add", "-A"]);
        repo.git(&["-C", &dir, "commit", "-q", "-m", file]);
        repo.git(&["-C", &dir, "rev-parse", "HEAD"])
            .trim()
            .to_string()
    }

    fn worktree_listed(repo: &TestRepo, needle: &str) -> bool {
        repo.git(&["worktree", "list"]).contains(needle)
    }

    /// Squash-merges `branch` into `main` (checked out in the primary worktree).
    fn squash_into_main(repo: &TestRepo, branch: &str) {
        repo.git(&["merge", "-q", "--squash", branch]);
        repo.git(&["commit", "-q", "-m", &format!("squash {branch}")]);
    }

    #[test]
    fn a_detached_worktree_on_merged_work_is_pruned_as_merged() {
        let repo = TestRepo::init();
        detached_wt(&repo, "merged", "main");
        let merged = report(&repo, &prune_args(true, false, true, false));
        assert!(merged.contains("detached-merged: merged\n"), "{merged}");
        run_yes(&repo, &prune_args(true, false, false, false));
        assert!(!worktree_listed(&repo, "detached-merged"));
    }

    #[test]
    fn a_detached_worktree_is_pushed_only_when_its_head_is_on_a_remote() {
        let repo = TestRepo::init();
        let pushed = detached_wt(&repo, "pushed", "main");
        let head = commit_in(&repo, &pushed, "pr.txt");
        repo.git(&["update-ref", "refs/remotes/origin/pr-head", &head]);
        let local = detached_wt(&repo, "local", "main");
        commit_in(&repo, &local, "wip.txt");

        let report_pushed = report(&repo, &pushed_dry_run());
        assert!(
            report_pushed.contains("detached-pushed: pushed\n"),
            "{report_pushed}"
        );
        assert!(!report_pushed.contains("detached-local"), "{report_pushed}");
        // Not merged, so `--merged` leaves both.
        assert!(!report(&repo, &prune_args(true, false, true, false)).contains("detached-"));
        let err = run_yes(&repo, &all_run());
        assert!(err.contains("pruned 1 item(s)"), "{err}");
        assert!(!worktree_listed(&repo, "detached-pushed"));
        assert!(worktree_listed(&repo, "detached-local"));
    }

    #[test]
    fn a_dirty_detached_worktree_is_skipped_and_says_so() {
        let repo = TestRepo::init();
        let path = detached_wt(&repo, "dirty", "main");
        std::fs::write(path.join("README.md"), "edited\n").unwrap();
        let (out, err) = report_both(&repo, &all_dry_run());
        assert!(!out.contains("detached-dirty"), "{out}");
        assert!(err.contains("detached-dirty: uncommitted changes"), "{err}");
        run_yes(&repo, &all_run());
        assert!(worktree_listed(&repo, "detached-dirty"));
    }

    #[test]
    fn a_worktree_mid_rebase_is_kept_even_with_force() {
        // Mid-rebase a worktree is detached and may look merged; the rebase is
        // still someone's work in flight.
        let repo = TestRepo::init();
        let path = detached_wt(&repo, "rebasing", "main");
        let admin = repo.git(&[
            "-C",
            path.to_str().unwrap(),
            "rev-parse",
            "--absolute-git-dir",
        ]);
        std::fs::create_dir(std::path::Path::new(admin.trim()).join("rebase-merge")).unwrap();
        let forced = PruneArgs {
            all: true,
            ..prune_args(false, false, false, true)
        };
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &forced, false).unwrap();
        let err = t.err.contents();
        assert!(
            err.contains("detached-rebasing: rebase in progress"),
            "{err}"
        );
        assert!(worktree_listed(&repo, "detached-rebasing"));
    }

    #[test]
    fn a_squash_merged_worktree_with_a_live_upstream_is_merged_by_content() {
        // Pushed, upstream still present, and its work squashed into main under
        // another SHA: no ancestry, not gone, and `--pushed` skips checkouts.
        let repo = TestRepo::init();
        make_unmerged_wt(&repo, "chore");
        give_upstream(&repo, "chore");
        squash_into_main(&repo, "chore");
        let merged = report(&repo, &prune_args(true, false, true, false));
        assert!(
            merged.contains("would remove chore: merged by content"),
            "{merged}"
        );
        assert!(!report(&repo, &pushed_dry_run()).contains("chore"));
        let err = run_yes(&repo, &all_run());
        assert!(!err.contains("skipping"), "{err}");
        assert!(!err.contains("could not"), "{err}");
        assert!(!worktree_listed(&repo, "chore"));
        assert!(!has_branch(&repo, "chore"));
    }

    #[test]
    fn merged_alone_removes_a_squash_merged_worktree_and_its_branch() {
        // Not `--all`: the branch is never a bare candidate here, so only the
        // worktree removal's own cleanup can delete it — which must count a
        // squash merge as merged, like the selection did.
        let repo = TestRepo::init();
        make_unmerged_wt(&repo, "squashed");
        squash_into_main(&repo, "squashed");
        let err = run_yes(&repo, &prune_args(true, false, false, false));
        assert!(err.contains("squashed: merged by content"), "{err}");
        assert!(err.contains("pruned 1 item(s)"), "{err}");
        assert!(!worktree_listed(&repo, "squashed"));
        assert!(!has_branch(&repo, "squashed"));
    }

    /// Answers the prompt `y`, after running its action — standing in for
    /// something done while the prompt waited.
    struct ActsThenConfirms(Box<dyn FnMut() + Send>);
    impl crate::cx::Input for ActsThenConfirms {
        fn read_line(&mut self) -> crate::error::Result<String> {
            (self.0)();
            Ok("y\n".into())
        }
    }

    /// [`ActsThenConfirms`] running `git <args>` in `repo`.
    fn git_then_confirm(repo: &TestRepo, args: &'static [&'static str]) -> ActsThenConfirms {
        let dir = repo.root().to_path_buf();
        ActsThenConfirms(Box::new(move || {
            repo_git(&dir, args);
        }))
    }

    #[test]
    fn a_branch_moved_onto_a_nested_tag_while_the_prompt_waits_is_unsafe() {
        // Under the lock the tip is a tag of a tag of work found nowhere
        // else; it must be peeled all the way to that commit.
        let repo = TestRepo::init();
        bare_branch(&repo, "old");
        diverged_branch(&repo, "work");
        repo.git(&["tag", "-a", "-m", "inner", "v-inner", "work"]);
        repo.git(&["tag", "-a", "-m", "outer", "v-outer", "v-inner"]);
        let outer = repo.git(&["rev-parse", "v-outer"]).trim().to_string();
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        let root = repo.root().to_path_buf();
        t.cx.input = Box::new(ActsThenConfirms(Box::new(move || {
            // Porcelain refuses a tag on a branch; the ref file does not.
            std::fs::write(root.join(".git/refs/heads/old"), format!("{outer}\n")).unwrap();
            repo_git(&root, &["branch", "-D", "work"]);
            repo_git(&root, &["tag", "-d", "v-inner", "v-outer"]);
        })));
        super::run(&mut t.cx, &prune_args(true, false, false, false), false).unwrap();
        let err = t.err.contents();
        assert!(
            err.contains("skipping old (branch): has work on no remote"),
            "{err}"
        );
        assert!(has_branch(&repo, "old"));
    }

    #[test]
    fn unreadable_metadata_is_cleared_for_every_deleted_branch() {
        let repo = TestRepo::init();
        bare_branch(&repo, "old");
        crate::config::wtconfig::mark_created_by_wt(&RealGit, repo.root(), "old").unwrap();
        let err = run_yes_with(
            &repo,
            Refuses(|args| {
                (args.first() == Some(&"config") && args.contains(&"--get-regexp"))
                    .then_some("fatal: config")
            }),
        );
        assert!(err.contains("pruned 1 item(s)"), "{err}");
        let r = crate::git::discover::Repo::discover(repo.root()).unwrap();
        assert!(!crate::config::wtconfig::read_meta(r.gix(), "old").created_by_wt);
    }

    #[test]
    fn a_squash_merge_dropped_while_the_prompt_waits_keeps_the_branch() {
        // Selected as merged by content; main then drops the squash commit
        // (a revert would not do: the squash commit would still hold the
        // work), so the branch's work exists nowhere else. The re-check under
        // the lock must see the new main, not the tree selection read.
        let repo = TestRepo::init();
        diverged_branch(&repo, "feat");
        squash_into_main(&repo, "feat");
        let merged = report(&repo, &prune_args(true, false, true, false));
        assert!(
            merged.contains("feat (branch): merged by content"),
            "{merged}"
        );
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        t.cx.input = Box::new(git_then_confirm(
            &repo,
            &["reset", "-q", "--hard", "HEAD~1"],
        ));
        super::run(&mut t.cx, &prune_args(true, false, false, false), false).unwrap();
        let err = t.err.contents();
        assert!(
            err.contains("skipping feat (branch): has work on no remote"),
            "{err}"
        );
        assert!(has_branch(&repo, "feat"));
    }

    #[test]
    fn a_gone_squash_merged_branch_main_edited_since_is_pruned() {
        // Issue #113: main squashed the branch in, then rewrote its line, so
        // merging it conflicts; the squash commit still holds its tree.
        let repo = TestRepo::init();
        diverged_branch(&repo, "feat");
        give_gone_upstream(&repo, "feat");
        squash_into_main(&repo, "feat");
        repo.write("feat.txt", "edited\n");
        repo.commit_all("main edits feat.txt");
        let all = report(&repo, &all_dry_run());
        assert!(
            all.contains("would remove feat (branch): merged by content"),
            "{all}"
        );
    }

    #[test]
    fn a_merge_only_branch_without_upstream_is_merged_by_content() {
        // An integration branch never pushed, holding only merges of work that
        // later reached main through squashes: its SHAs exist nowhere else, its
        // content is all in main.
        let repo = TestRepo::init();
        diverged_branch(&repo, "x");
        diverged_branch(&repo, "y");
        repo.git(&["checkout", "-q", "-b", "integration"]);
        repo.git(&["merge", "-q", "--no-ff", "-m", "merge x", "x"]);
        repo.git(&["merge", "-q", "--no-ff", "-m", "merge y", "y"]);
        repo.git(&["checkout", "-q", "main"]);
        assert!(!report(&repo, &all_dry_run()).contains("integration"));
        squash_into_main(&repo, "x");
        squash_into_main(&repo, "y");
        let all = report(&repo, &all_dry_run());
        assert!(
            all.contains("would remove integration (branch): merged by content"),
            "{all}"
        );
        let err = run_yes(&repo, &all_run());
        assert!(!err.contains("skipping"), "{err}");
        assert!(!has_branch(&repo, "integration"));
    }

    #[test]
    fn a_gone_branch_whose_changes_landed_needs_no_force() {
        // `--gone` alone never ran the content check for selection, but safety
        // still counts a squash-merged branch as losing nothing.
        let repo = TestRepo::init();
        diverged_branch(&repo, "shipped");
        give_gone_upstream(&repo, "shipped");
        squash_into_main(&repo, "shipped");
        let err = run_yes(&repo, &prune_args(false, true, false, false));
        assert!(!err.contains("skipping"), "{err}");
        assert!(!has_branch(&repo, "shipped"));
    }

    #[test]
    fn the_current_worktree_is_never_pruned() {
        let repo = TestRepo::init();
        // Like a clone: without `origin/HEAD` the default branch falls back to
        // the current one, which inside the worktree would be `here` itself.
        repo.git(&["update-ref", "refs/remotes/origin/main", "refs/heads/main"]);
        repo.git(&[
            "symbolic-ref",
            "refs/remotes/origin/HEAD",
            "refs/remotes/origin/main",
        ]);
        make_wt(&repo, "here");
        let inside = wt_dir(&repo, "here");
        let mut t = crate::testutil::test_cx(&[], inside.to_str().unwrap());
        super::run(&mut t.cx, &prune_args(true, false, false, true), false).unwrap();
        let err = t.err.contents();
        assert!(
            err.contains("skipping here: it is the current worktree"),
            "{err}"
        );
        assert!(worktree_listed(&repo, "here"));
        assert!(has_branch(&repo, "here"));
    }

    #[test]
    fn a_locked_worktree_is_skipped_unless_locked_is_passed() {
        let repo = TestRepo::init();
        make_wt(&repo, "agent");
        let path = wt_dir(&repo, "agent");
        repo.git(&[
            "worktree",
            "lock",
            "--reason",
            "claimed by agent",
            path.to_str().unwrap(),
        ]);
        let (out, err) = report_both(&repo, &all_dry_run());
        assert!(!out.contains("agent"), "{out}");
        assert!(
            err.contains("skipping agent: locked (claimed by agent); use --locked"),
            "{err}"
        );
        // `--force` is not an override for a lock.
        let forced = PruneArgs {
            all: true,
            ..prune_args(false, false, false, true)
        };
        run_yes(&repo, &forced);
        assert!(worktree_listed(&repo, "agent"));
        assert!(has_branch(&repo, "agent"));
        let unlocked = PruneArgs {
            locked: true,
            ..all_run()
        };
        let err = run_yes(&repo, &unlocked);
        assert!(!err.contains("could not"), "{err}");
        assert!(!worktree_listed(&repo, "agent"));
        assert!(!has_branch(&repo, "agent"));
    }

    #[test]
    fn a_missing_locked_worktree_is_reconciled_with_locked() {
        let repo = TestRepo::init();
        make_wt(&repo, "ghost");
        let path = wt_dir(&repo, "ghost");
        repo.git(&["worktree", "lock", path.to_str().unwrap()]);
        std::fs::remove_dir_all(&path).unwrap();
        let err = run_yes(&repo, &all_run());
        assert!(
            err.contains("skipping ghost: locked; use --locked"),
            "{err}"
        );
        assert!(worktree_listed(&repo, "ghost"));
        let unlocked = PruneArgs {
            locked: true,
            ..all_run()
        };
        run_yes(&repo, &unlocked);
        assert!(!worktree_listed(&repo, "ghost"));
        assert!(!has_branch(&repo, "ghost"));
    }

    /// Real git, except `worktree remove` is refused.
    struct RefusesRemove;
    impl crate::git::cli::GitCli for RefusesRemove {
        fn run_raw(
            &self,
            repo: &std::path::Path,
            args: &[&str],
        ) -> crate::error::Result<crate::git::cli::GitOutput> {
            if args.starts_with(&["worktree", "remove"]) {
                return Ok(crate::git::cli::GitOutput {
                    success: false,
                    stdout: String::new(),
                    stderr: "fatal: refused".into(),
                });
            }
            RealGit.run_raw(repo, args)
        }
    }

    /// Real git that records each call's subcommand.
    #[derive(Default)]
    struct Counting(std::sync::Mutex<Vec<String>>);
    impl crate::git::cli::GitCli for Counting {
        fn run_raw(
            &self,
            repo: &std::path::Path,
            args: &[&str],
        ) -> crate::error::Result<crate::git::cli::GitOutput> {
            let verb = args
                .iter()
                .find(|a| !a.starts_with('-') && !a.contains('='))
                .unwrap_or(&"");
            self.0.lock().unwrap().push(verb.to_string());
            RealGit.run_raw(repo, args)
        }
    }

    /// The subcommands `args` spawns, per subcommand, when prune runs over a
    /// repository with `branches` merged bare branches (and a merged worktree).
    fn spawns(branches: usize, args: &PruneArgs) -> std::collections::BTreeMap<String, usize> {
        let repo = TestRepo::init();
        make_wt(&repo, "done");
        for i in 0..branches {
            bare_branch(&repo, &format!("old{i}"));
        }
        let git = std::sync::Arc::new(Counting::default());
        let mut t =
            crate::testutil::test_cx_with_git(&[], repo.root().to_str().unwrap(), git.clone());
        t.cx.assume_yes = true;
        super::run(&mut t.cx, args, false).unwrap();
        let err = t.err.contents();
        if !args.dry_run {
            assert!(
                err.contains(&format!("pruned {} item(s)", branches + 1)),
                "{err}"
            );
        }
        let mut counts = std::collections::BTreeMap::new();
        for verb in git.0.lock().unwrap().iter() {
            *counts.entry(verb.clone()).or_insert(0) += 1;
        }
        counts
    }

    /// Issue #116: what prune spawns does not grow with the number of
    /// branches, selecting or deleting.
    #[test]
    fn git_spawns_do_not_grow_with_the_branch_count() {
        let few = spawns(2, &all_dry_run());
        assert_eq!(few, spawns(12, &all_dry_run()));
        assert_eq!(few.get("rev-list"), Some(&1), "{few:?}");
        // Nothing reads a worktree's status that selection does not need.
        assert_eq!(few.get("status"), Some(&1), "{few:?}");

        let few = spawns(2, &all_run());
        assert_eq!(few, spawns(12, &all_run()));
        // One batch delete for every bare branch; the worktree's own branch
        // goes with it.
        assert_eq!(few.get("branch"), Some(&2), "{few:?}");
        // Only the worktree `wt` created has metadata to clear.
        assert_eq!(few.get("config").copied().unwrap_or(0), 2, "{few:?}");
    }

    /// Real git, except as `refuse` says: given an argv, `Some(stderr)` fails
    /// that call.
    struct Refuses(fn(&[&str]) -> Option<&'static str>);
    impl crate::git::cli::GitCli for Refuses {
        fn run_raw(
            &self,
            repo: &std::path::Path,
            args: &[&str],
        ) -> crate::error::Result<crate::git::cli::GitOutput> {
            if let Some(stderr) = (self.0)(args) {
                return Ok(crate::git::cli::GitOutput {
                    success: false,
                    stdout: String::new(),
                    stderr: stderr.into(),
                });
            }
            RealGit.run_raw(repo, args)
        }
    }

    /// Runs a real `--all -y` prune with `git`, returning stderr.
    fn run_yes_with(repo: &TestRepo, git: Refuses) -> String {
        let mut t = crate::testutil::test_cx_with_git(
            &[],
            repo.root().to_str().unwrap(),
            std::sync::Arc::new(git),
        );
        t.cx.assume_yes = true;
        super::run(&mut t.cx, &all_run(), false).unwrap();
        t.err.contents()
    }

    #[test]
    fn a_branch_the_batch_delete_leaves_is_retried_alone() {
        // The batched `branch -D` fails outright; each branch then goes on
        // its own, and counts.
        let repo = TestRepo::init();
        bare_branch(&repo, "one");
        bare_branch(&repo, "two");
        let err = run_yes_with(
            &repo,
            Refuses(|args| {
                (args.first() == Some(&"branch") && args.len() > 3).then_some("fatal: batch")
            }),
        );
        assert!(err.contains("pruned 2 item(s)"), "{err}");
        assert!(!err.contains("could not delete"), "{err}");
        assert!(!has_branch(&repo, "one"));
        assert!(!has_branch(&repo, "two"));
    }

    #[test]
    fn a_branch_git_will_not_delete_is_reported_on_its_own() {
        let repo = TestRepo::init();
        bare_branch(&repo, "stuck");
        bare_branch(&repo, "fine");
        let err = run_yes_with(
            &repo,
            Refuses(|args| {
                (args.first() == Some(&"branch") && args.contains(&"stuck")).then_some("fatal: no")
            }),
        );
        assert!(err.contains("could not delete stuck: fatal: no"), "{err}");
        assert!(!err.contains("could not delete fine"), "{err}");
        assert!(err.contains("pruned 1 item(s)"), "{err}");
        assert!(has_branch(&repo, "stuck"));
        assert!(!has_branch(&repo, "fine"));
    }

    #[test]
    fn unreadable_branch_tips_under_the_lock_delete_no_branch() {
        // Selection reads refs through gix; only the removal's `for-each-ref`
        // fails, so which branch is where is unknown and none is deleted.
        let repo = TestRepo::init();
        bare_branch(&repo, "old");
        let err = run_yes_with(
            &repo,
            Refuses(|args| (args.first() == Some(&"for-each-ref")).then_some("fatal: refs")),
        );
        assert!(
            err.contains("skipping old (branch): cannot read its git state"),
            "{err}"
        );
        assert!(err.contains("pruned 0 item(s)"), "{err}");
        assert!(has_branch(&repo, "old"));
    }

    #[test]
    fn a_refused_worktree_removal_is_reported_and_not_counted() {
        let repo = TestRepo::init();
        make_wt(&repo, "stuck");
        let mut t = crate::testutil::test_cx_with_git(
            &[],
            repo.root().to_str().unwrap(),
            std::sync::Arc::new(RefusesRemove),
        );
        t.cx.assume_yes = true;
        super::run(&mut t.cx, &all_run(), false).unwrap();
        let err = t.err.contents();
        assert!(err.contains("could not remove stuck: "), "{err}");
        assert!(err.contains("fatal: refused"), "{err}");
        assert!(err.contains("pruned 0 item(s)"), "{err}");
        // Its branch stays with it rather than failing a "checked out" delete.
        assert!(!err.contains("could not delete"), "{err}");
        assert!(worktree_listed(&repo, "stuck"));
        assert!(has_branch(&repo, "stuck"));
    }

    #[test]
    fn a_worktree_dirtied_after_the_prompt_is_kept() {
        let repo = TestRepo::init();
        make_wt(&repo, "late");
        let path = wt_dir(&repo, "late");
        // Stands in for an edit made while the prompt waited: selection saw it
        // clean, the removal re-reads it.
        let row = row_for(&repo, "late");
        let args = all_run();
        with_assessor(&repo, &args, |assessor| {
            assert_eq!(super::changed_since_assessed(assessor, &row, None), None);
        });
        std::fs::write(path.join("README.md"), "late edit\n").unwrap();
        with_assessor(&repo, &args, |assessor| {
            let why = super::changed_since_assessed(assessor, &row, None).unwrap();
            assert!(why.contains("uncommitted changes"), "{why}");
        });
    }

    #[test]
    fn an_untracked_file_added_after_the_prompt_keeps_the_worktree() {
        let repo = TestRepo::init();
        make_wt(&repo, "late-new");
        let path = wt_dir(&repo, "late-new");
        let row = row_for(&repo, "late-new");
        let args = all_run();
        std::fs::write(path.join("new.rs"), "fn main() {}\n").unwrap();
        with_assessor(&repo, &args, |assessor| {
            let why = super::changed_since_assessed(assessor, &row, None).unwrap();
            assert!(why.contains("uncommitted changes"), "{why}");
        });
    }

    #[test]
    fn untracked_files_keep_a_selected_worktree_whatever_the_config() {
        // `remove.untracked_blocks` defaults to false, but removal passes
        // `--force`: prune's own guard is the only thing between git and these
        // files, for every way a worktree can qualify. The repository also
        // hides untracked files from `git status`, which must not matter.
        let repo = TestRepo::init();
        repo.git(&["config", "status.showUntrackedFiles", "no"]);
        let detached = detached_wt(&repo, "fresh", "main");
        std::fs::write(detached.join("newfile.rs"), "wip\n").unwrap();
        make_unmerged_wt(&repo, "squashed");
        give_upstream(&repo, "squashed");
        squash_into_main(&repo, "squashed");
        std::fs::write(wt_dir(&repo, "squashed").join("notes.md"), "wip\n").unwrap();
        make_wt(&repo, "held");
        let held = wt_dir(&repo, "held");
        std::fs::write(held.join("scratch.txt"), "wip\n").unwrap();
        repo.git(&["worktree", "lock", held.to_str().unwrap()]);

        let (out, err) = report_both(
            &repo,
            &PruneArgs {
                locked: true,
                ..all_dry_run()
            },
        );
        for name in ["detached-fresh", "squashed", "held"] {
            assert!(!out.contains(name), "{out}");
            assert!(
                err.contains(&format!("{name}: uncommitted changes")),
                "{err}"
            );
        }
        let unlocked = PruneArgs {
            locked: true,
            ..all_run()
        };
        run_yes(&repo, &unlocked);
        assert!(detached.join("newfile.rs").exists());
        assert!(wt_dir(&repo, "squashed").join("notes.md").exists());
        assert!(held.join("scratch.txt").exists());

        // `--force` is the explicit override.
        let forced = PruneArgs {
            all: true,
            locked: true,
            ..prune_args(false, false, false, true)
        };
        run_yes(&repo, &forced);
        assert!(!worktree_listed(&repo, "detached-fresh"));
        assert!(!worktree_listed(&repo, "squashed"));
        assert!(!worktree_listed(&repo, "held"));
    }

    /// The worktree row whose path ends with `suffix`.
    fn row_for(repo: &TestRepo, suffix: &str) -> crate::model::Worktree {
        crate::worktree::build_worktrees(
            &crate::git::discover::Repo::discover(repo.root()).unwrap(),
            &RealGit,
        )
        .unwrap()
        .into_iter()
        .find(|w| w.path.to_string_lossy().ends_with(suffix))
        .unwrap()
    }

    #[test]
    fn a_missing_worktree_that_reappeared_after_the_prompt_is_kept() {
        // Assessed while its drive was unmounted; back by the time removal runs.
        // `worktree remove --force` would delete it, uncommitted edits and all.
        let repo = TestRepo::init();
        make_wt(&repo, "remounted");
        let path = wt_dir(&repo, "remounted");
        let mut row = row_for(&repo, "remounted");
        row.is_missing = true;
        let args = all_run();
        with_assessor(&repo, &args, |assessor| {
            let why = super::changed_since_assessed(assessor, &row, None).unwrap();
            assert!(why.contains("reappeared"), "{why}");
        });
        std::fs::remove_dir_all(&path).unwrap();
        with_assessor(&repo, &args, |assessor| {
            assert_eq!(super::changed_since_assessed(assessor, &row, None), None);
        });
    }

    #[test]
    fn a_branch_worktree_that_detached_after_the_prompt_is_kept() {
        let repo = TestRepo::init();
        make_wt(&repo, "hopper");
        let path = wt_dir(&repo, "hopper");
        let row = row_for(&repo, "hopper");
        let dir = path.to_string_lossy().into_owned();
        repo.git(&["-C", &dir, "checkout", "-q", "--detach"]);
        commit_in(&repo, &path, "stray.txt");
        let args = all_run();
        with_assessor(&repo, &args, |assessor| {
            let why = super::changed_since_assessed(assessor, &row, None).unwrap();
            assert!(why.contains("HEAD moved"), "{why}");
        });
    }

    #[test]
    fn a_detached_worktree_that_committed_after_the_prompt_is_kept() {
        // Clean both times, but its HEAD — the only holder of the new commit —
        // moved off the commit that was judged safe.
        let repo = TestRepo::init();
        let path = detached_wt(&repo, "busy-agent", "main");
        let assessed = repo.git(&["rev-parse", "main"]).trim().to_string();
        let row = row_for(&repo, "detached-busy-agent");
        let args = all_run();
        with_assessor(&repo, &args, |assessor| {
            assert_eq!(
                super::changed_since_assessed(assessor, &row, Some(&assessed)),
                None
            );
        });
        commit_in(&repo, &path, "late.txt");
        with_assessor(&repo, &args, |assessor| {
            let why = super::changed_since_assessed(assessor, &row, Some(&assessed)).unwrap();
            assert!(why.contains("HEAD moved"), "{why}");
        });
    }

    #[test]
    fn a_worktree_that_started_a_rebase_after_the_prompt_is_kept() {
        let repo = TestRepo::init();
        make_wt(&repo, "rebasing");
        let row = row_for(&repo, "rebasing");
        let admin = repo.git(&[
            "-C",
            wt_dir(&repo, "rebasing").to_str().unwrap(),
            "rev-parse",
            "--absolute-git-dir",
        ]);
        std::fs::create_dir(std::path::Path::new(admin.trim()).join("rebase-merge")).unwrap();
        let args = all_run();
        with_assessor(&repo, &args, |assessor| {
            let why = super::changed_since_assessed(assessor, &row, None).unwrap();
            assert_eq!(why, "rebase in progress");
        });
    }

    #[test]
    fn a_missing_detached_worktree_holding_the_only_copy_needs_force() {
        let repo = TestRepo::init();
        let path = detached_wt(&repo, "orphan", "main");
        commit_in(&repo, &path, "only-here.txt");
        std::fs::remove_dir_all(&path).unwrap();
        let err = run_yes(&repo, &all_run());
        assert!(
            err.contains("detached-orphan: has work on no remote"),
            "{err}"
        );
        assert!(worktree_listed(&repo, "detached-orphan"));
        let forced = PruneArgs {
            all: true,
            ..prune_args(false, false, false, true)
        };
        run_yes(&repo, &forced);
        assert!(!worktree_listed(&repo, "detached-orphan"));
    }

    #[test]
    fn a_missing_worktree_no_mode_selected_is_left_registered() {
        // `--merged` does not select a missing, unmerged worktree, and prune no
        // longer runs a blanket `git worktree prune` that would drop it anyway.
        let repo = TestRepo::init();
        make_unmerged_wt(&repo, "offline");
        std::fs::remove_dir_all(wt_dir(&repo, "offline")).unwrap();
        make_wt(&repo, "done"); // one real candidate, so the removal loop runs
        let err = run_yes(&repo, &prune_args(true, false, false, false));
        assert!(err.contains("pruned 1 item(s)"), "{err}");
        assert!(worktree_listed(&repo, "offline"));
        // The empty case is just as hands-off.
        run_yes(&repo, &prune_args(true, false, false, false));
        assert!(worktree_listed(&repo, "offline"));
    }

    #[test]
    fn a_missing_detached_worktree_whose_head_survives_is_pruned() {
        let repo = TestRepo::init();
        let path = detached_wt(&repo, "spent", "main");
        std::fs::remove_dir_all(&path).unwrap();
        let err = run_yes(&repo, &all_run());
        assert!(!err.contains("skipping"), "{err}");
        assert!(!worktree_listed(&repo, "detached-spent"));
    }

    /// Real git, except that a worktree whose path ends in `blind` cannot
    /// resolve its admin directory — its in-progress state is unreadable.
    struct BlindAdminDir;
    impl crate::git::cli::GitCli for BlindAdminDir {
        fn run_raw(
            &self,
            repo: &std::path::Path,
            args: &[&str],
        ) -> crate::error::Result<crate::git::cli::GitOutput> {
            if args == ["rev-parse", "--absolute-git-dir"]
                && repo.to_string_lossy().ends_with("blind")
            {
                return Ok(crate::git::cli::GitOutput {
                    success: false,
                    stdout: String::new(),
                    stderr: "fatal: unreadable".into(),
                });
            }
            RealGit.run_raw(repo, args)
        }
    }

    #[test]
    fn a_worktree_whose_state_turns_unreadable_after_the_prompt_is_kept() {
        let repo = TestRepo::init();
        make_wt(&repo, "blind");
        let row = row_for(&repo, "blind");
        let args = all_run();
        with_assessor(&repo, &args, |assessor| {
            assert_eq!(super::changed_since_assessed(assessor, &row, None), None);
        });
        with_assessor_git(&repo, &args, &BlindAdminDir, |assessor| {
            let why = super::changed_since_assessed(assessor, &row, None);
            assert_eq!(why, Some(super::Block::Unreadable.message()));
        });
    }

    #[test]
    fn a_missing_worktree_whose_path_cannot_be_checked_is_kept() {
        // `git worktree remove --force` would delete whatever is at the path,
        // so a path whose existence cannot be read is not treated as gone.
        let repo = TestRepo::init();
        let scratch = tempfile::tempdir().unwrap();
        let path = scratch.path().join("mount").join("offline");
        repo.git(&[
            "worktree",
            "add",
            "-q",
            "-b",
            "offline",
            path.to_str().unwrap(),
        ]);
        let mut row = row_for(&repo, "offline");
        let parent = row.path.parent().unwrap().to_path_buf();
        std::fs::remove_dir_all(&parent).unwrap();
        row.is_missing = true;
        let args = all_run();
        with_assessor(&repo, &args, |assessor| {
            assert_eq!(super::changed_since_assessed(assessor, &row, None), None);
        });
        // A file where a directory should be: the lookup fails with ENOTDIR,
        // not NotFound (and unlike a permission error, even for root).
        std::fs::write(&parent, "not a directory\n").unwrap();
        with_assessor(&repo, &args, |assessor| {
            assert_eq!(
                super::changed_since_assessed(assessor, &row, None),
                Some(super::Block::Unreadable.message())
            );
        });
    }

    #[test]
    fn an_unreadable_worktree_keeps_every_bare_branch() {
        // The branch its rebase or bisect would return to is unknown, so no
        // bare branch is deleted on the strength of git refusing the held one.
        let repo = TestRepo::init();
        make_wt(&repo, "blind");
        repo.git(&["branch", "done"]);
        let mut t = crate::testutil::test_cx_with_git(
            &[],
            repo.root().to_str().unwrap(),
            std::sync::Arc::new(BlindAdminDir),
        );
        t.cx.assume_yes = true;
        super::run(&mut t.cx, &all_run(), false).unwrap();
        let err = t.err.contents();
        assert!(
            err.contains("skipping done (branch): cannot read the rebase or bisect state of blind"),
            "{err}"
        );
        assert!(has_branch(&repo, "done"));
        assert!(worktree_listed(&repo, "blind"));
    }

    #[test]
    fn a_worktree_without_a_porcelain_record_is_unreadable() {
        let repo = TestRepo::init();
        make_wt(&repo, "unlisted");
        let row = row_for(&repo, "unlisted");
        let args = all_dry_run();
        with_assessor(&repo, &args, |assessor| {
            let verdict = assessor.worktree(1, &row, None).expect("merged");
            assert_eq!(verdict.block, Some(super::Block::Unreadable));
        });
    }

    #[test]
    fn a_branch_being_rebased_is_kept_and_says_so() {
        // Mid-rebase its worktree is detached and names no branch, but the
        // branch is still in use: deleting it would strand the rebase.
        let repo = TestRepo::init();
        rebase_stopped_wt(&repo, "feat");
        give_upstream(&repo, "feat"); // pushed, so `--pushed` would pick it bare
        let holder = wt_dir(&repo, "feat");
        let skip = format!(
            "skipping feat (branch): being rebased in {}",
            holder.display()
        );
        let (all, err) = report_both(&repo, &all_dry_run());
        assert!(!all.contains("feat (branch)"), "{all}");
        assert!(err.lines().any(|l| l == skip), "{err}");
        // Never in `--json`, which lists only candidates.
        assert!(json_branch(&repo, &all_dry_run(), "feat").is_none());
        let forced = PruneArgs {
            all: true,
            ..prune_args(false, false, false, true)
        };
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &forced, false).unwrap();
        assert!(t.err.contents().lines().any(|l| l == skip));
        assert!(has_branch(&repo, "feat"));
    }

    #[test]
    fn a_branch_being_bisected_is_kept_and_says_so() {
        let repo = TestRepo::init();
        make_wt(&repo, "hunt"); // merged, so `--merged` would pick it bare
        let holder = wt_dir(&repo, "hunt");
        for n in 1..=3 {
            repo.write("a.txt", &format!("{n}\n"));
            repo.commit_all(&format!("c{n}"));
        }
        // Wide enough that the bisect checks out a midpoint, detaching HEAD.
        let dir = holder.to_string_lossy().into_owned();
        repo.git(&["-C", &dir, "bisect", "start", "main", "main~3"]);
        let skip = format!(
            "skipping hunt (branch): being bisected in {}",
            holder.display()
        );
        let merged_dry_run = prune_args(true, false, true, false);
        let (out, err) = report_both(&repo, &merged_dry_run);
        assert!(!out.contains("hunt (branch)"), "{out}");
        assert!(err.lines().any(|l| l == skip), "{err}");
        let err = run_yes(&repo, &prune_args(true, false, false, true));
        assert!(err.lines().any(|l| l == skip), "{err}");
        assert!(has_branch(&repo, "hunt"));
    }

    #[test]
    fn a_held_branch_no_mode_selects_is_not_mentioned() {
        // Unmerged and unpushed: `--merged` would not pick it bare anyway.
        let repo = TestRepo::init();
        rebase_stopped_wt(&repo, "feat");
        let (_, err) = report_both(&repo, &prune_args(true, false, true, false));
        assert!(!err.contains("feat (branch)"), "{err}");
    }

    /// Creates a wt worktree on `branch` and leaves it stopped mid-rebase onto
    /// a conflicting `main` (detached, as a real rebase leaves it).
    fn rebase_stopped_wt(repo: &TestRepo, branch: &str) {
        make_unmerged_wt(repo, branch);
        repo.write("change.txt", "main\n");
        repo.commit_all("main conflicts");
        let out =
            crate::git::cli::GitCli::run_raw(&RealGit, &wt_dir(repo, branch), &["rebase", "main"])
                .unwrap();
        assert!(!out.success, "the rebase should stop on the conflict");
    }

    #[test]
    fn a_missing_worktree_mid_rebase_is_kept_with_its_branch() {
        // Its directory is gone, but its admin entry still holds the rebase —
        // and the branch it will return to.
        let repo = TestRepo::init();
        rebase_stopped_wt(&repo, "stalled");
        std::fs::remove_dir_all(wt_dir(&repo, "stalled")).unwrap();
        make_wt(&repo, "lost");
        std::fs::remove_dir_all(wt_dir(&repo, "lost")).unwrap();
        let forced = PruneArgs {
            all: true,
            ..prune_args(false, false, false, true)
        };
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        super::run(&mut t.cx, &forced, false).unwrap();
        let err = t.err.contents();
        assert!(
            err.lines().any(|l| l.starts_with("skipping")
                && l.contains("stalled")
                && l.ends_with(": rebase in progress")),
            "{err}"
        );
        assert!(worktree_listed(&repo, "stalled"));
        assert!(has_branch(&repo, "stalled"));
        // A plain missing worktree is still removed, branch and all.
        assert!(!worktree_listed(&repo, "lost"), "{err}");
        assert!(!has_branch(&repo, "lost"));
    }

    #[test]
    fn merged_is_reported_the_same_whatever_the_mode() {
        // A pushed branch whose work was squashed into main: `--pushed` picks it,
        // and still reports it merged.
        let repo = TestRepo::init();
        diverged_branch(&repo, "feat");
        give_upstream(&repo, "feat");
        squash_into_main(&repo, "feat");
        let pushed = json_branch(&repo, &pushed_dry_run(), "feat").expect("pushed");
        assert_eq!(pushed["reason"], serde_json::json!("pushed"));
        assert_eq!(pushed["merged"], serde_json::json!(true));
        let all = json_branch(&repo, &all_dry_run(), "feat").expect("merged");
        assert_eq!(all["merged"], serde_json::json!(true));
    }
}