worktrunk 0.40.0

A CLI for Git worktree management, designed for parallel AI agent workflows
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
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
use crate::common::{
    BareRepoTest, TestRepo, TestRepoBase, configure_directive_files, directive_files,
    make_snapshot_cmd, repo, repo_with_remote, setup_snapshot_settings,
    setup_temp_snapshot_settings, wt_command,
};
use ansi_str::AnsiStr;
use insta::assert_snapshot;
use insta_cmd::assert_cmd_snapshot;
use path_slash::PathExt as _;
use rstest::rstest;
use std::time::Duration; // For absence checks (SLEEP_FOR_ABSENCE_CHECK pattern)

#[rstest]
fn test_remove_already_on_default(repo: TestRepo) {
    // Already on main branch
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &[], None));
}

#[rstest]
fn test_remove_switch_to_default(repo: TestRepo) {
    // Create and switch to a feature branch in the main repo
    repo.run_git(&["switch", "-c", "feature"]);

    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &[], None));
}

#[rstest]
fn test_remove_from_worktree(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-wt");

    // Run remove from within the worktree
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &[],
        Some(&worktree_path)
    ));
}

#[rstest]
fn test_remove_internal_mode(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-internal");

    // Directive file guards must live through command execution
    let (cd_path, exec_path, _guard) = directive_files();
    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(&repo, "remove", &[], Some(&worktree_path));
        configure_directive_files(&mut cmd, &cd_path, &exec_path);
        cmd
    });
}

///
/// When git runs a subcommand, it sets `GIT_EXEC_PATH` in the environment.
/// Shell integration cannot work in this case because cd directives cannot
/// propagate through git's subprocess to the parent shell.
#[rstest]
fn test_remove_as_git_subcommand(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-git-subcmd");

    // Remove with GIT_EXEC_PATH set (simulating `git wt remove ...`)
    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "remove", &[], Some(&worktree_path));
        cmd.env("GIT_EXEC_PATH", "/usr/lib/git-core");
        assert_cmd_snapshot!("remove_as_git_subcommand", cmd);
    });
}

#[rstest]
fn test_remove_dirty_working_tree(repo: TestRepo) {
    // Create a dirty file
    std::fs::write(repo.root_path().join("dirty.txt"), "uncommitted changes").unwrap();

    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &[], None));
}

#[rstest]
fn test_remove_locked_worktree(mut repo: TestRepo) {
    // Create a worktree and lock it
    let _worktree_path = repo.add_worktree("locked-feature");
    repo.lock_worktree("locked-feature", Some("Testing lock"));

    // Try to remove the locked worktree - should fail with helpful error
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["locked-feature"],
        None
    ));
}

#[rstest]
fn test_remove_locked_worktree_no_reason(mut repo: TestRepo) {
    // Create a worktree and lock it without a reason
    let _worktree_path = repo.add_worktree("locked-no-reason");
    repo.lock_worktree("locked-no-reason", None);

    // Try to remove - should show error without parenthesized reason
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["locked-no-reason"],
        None
    ));
}

#[rstest]
fn test_remove_locked_current_worktree(mut repo: TestRepo) {
    // Create a worktree, switch to it, and lock it
    let worktree_path = repo.add_worktree("locked-current");
    repo.lock_worktree("locked-current", Some("Do not remove"));

    // Try to remove current (locked) worktree - should fail
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &[],
        Some(&worktree_path)
    ));
}

#[rstest]
fn test_remove_locked_detached_worktree(mut repo: TestRepo) {
    // Create a worktree, detach HEAD, and lock it
    let worktree_path = repo.add_worktree("locked-detached");
    repo.detach_head_in_worktree("locked-detached");
    repo.lock_worktree("locked-detached", Some("Detached and locked"));

    // Try to remove from within the locked detached worktree - should fail
    // This exercises the RemoveTarget::Current path for locked worktrees
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &[],
        Some(&worktree_path)
    ));
}

#[rstest]
fn test_remove_locked_detached_multi(mut repo: TestRepo) {
    // Test multi-remove where current worktree (@ target) is locked and detached
    let _other_worktree = repo.add_worktree("other");
    let _locked_worktree = repo.add_worktree("locked-detached");
    repo.detach_head_in_worktree("locked-detached");
    repo.lock_worktree("locked-detached", Some("Locked detached"));

    // From the locked detached worktree, try to remove @ and other
    // The @ resolves to current (locked-detached) which is locked
    let locked_path = repo.worktree_path("locked-detached");
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["@", "other"],
        Some(locked_path)
    ));
}

#[rstest]
fn test_remove_by_name_from_main(mut repo: TestRepo) {
    // Create a worktree
    let _worktree_path = repo.add_worktree("feature-a");

    // Remove it by name from main repo
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &["feature-a"], None));
}

#[rstest]
fn test_remove_by_name_from_other_worktree(mut repo: TestRepo) {
    // Create two worktrees
    let worktree_a = repo.add_worktree("feature-a");
    let _worktree_b = repo.add_worktree("feature-b");

    // From worktree A, remove worktree B by name
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-b"],
        Some(&worktree_a)
    ));
}

#[rstest]
fn test_remove_current_by_name(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-current");

    // Remove current worktree by specifying its name
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-current"],
        Some(&worktree_path)
    ));
}

#[rstest]
fn test_remove_nonexistent_worktree(repo: TestRepo) {
    // Try to remove a worktree that doesn't exist
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &["nonexistent"], None));
}

///
/// Regression test for bug where `wt remove npm` would show "Cannot create worktree for npm"
/// when the expected path was occupied. The fix uses `OperationMode::Remove` which skips
/// the path occupation check entirely, correctly treating this as a branch-only removal.
///
/// Setup:
/// - Branch `npm` exists but has no worktree
/// - The expected path for `npm` (repo.npm) is occupied by a different branch's worktree
///
/// Expected behavior:
/// - Warning: "No worktree found for branch npm"
/// - Success: Branch deleted (same commit as main)
#[rstest]
fn test_remove_branch_no_worktree_path_occupied(mut repo: TestRepo) {
    // Create branch `npm` without a worktree
    repo.git_command().args(["branch", "npm"]).run().unwrap();

    // Create a worktree for a different branch at the path where `npm` worktree would be
    // (the path template puts worktrees at ../repo.branch, so ../repo.npm would be npm's path)
    let _other_worktree = repo.add_worktree("other");

    // Manually move the worktree to occupy npm's expected path
    // First, get the expected path for npm
    let npm_expected_path = repo.root_path().parent().unwrap().join(format!(
        "{}.npm",
        repo.root_path().file_name().unwrap().to_str().unwrap()
    ));
    let other_path = repo.root_path().parent().unwrap().join(format!(
        "{}.other",
        repo.root_path().file_name().unwrap().to_str().unwrap()
    ));

    // Remove the worktree metadata and move the directory
    repo.git_command()
        .args([
            "worktree",
            "remove",
            "--force",
            other_path.to_str().unwrap(),
        ])
        .run()
        .unwrap();

    // Create worktree at npm's expected path but for the "other" branch
    repo.git_command()
        .args([
            "worktree",
            "add",
            npm_expected_path.to_str().unwrap(),
            "other",
        ])
        .run()
        .unwrap();

    // Now: branch `npm` exists, no worktree for it, but npm's expected path has `other` branch
    // Running `wt remove npm` should show "No worktree found" NOT "Cannot create worktree"
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &["npm"], None));
}

#[rstest]
fn test_remove_multiple_nonexistent_force(repo: TestRepo) {
    // Try to force-remove multiple branches that don't exist
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["-D", "foo", "bar", "baz"],
        None
    ));
}

#[rstest]
fn test_remove_remote_only_branch(#[from(repo_with_remote)] repo: TestRepo) {
    // Create a remote-only branch by pushing a branch then deleting it locally
    repo.run_git(&["branch", "remote-feature"]);
    repo.run_git(&["push", "origin", "remote-feature"]);
    repo.run_git(&["branch", "-D", "remote-feature"]);
    repo.run_git(&["fetch", "origin"]);

    // Try to remove a branch that only exists on remote - should get helpful error
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["remote-feature"],
        None
    ));
}

#[rstest]
fn test_remove_nonexistent_branch(repo: TestRepo) {
    // Try to remove a branch that doesn't exist at all
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &["nonexistent"], None));
}

#[rstest]
fn test_remove_partial_success(mut repo: TestRepo) {
    // Create one valid worktree
    let _feature_path = repo.add_worktree("feature");

    // Try to remove both the valid worktree and a nonexistent one
    // The valid one should be removed; error for nonexistent; exit with failure
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature", "nonexistent"],
        None
    ));

    // Verify the valid worktree was actually removed
    let worktrees_dir = repo.root_path().parent().unwrap();
    assert!(
        !worktrees_dir.join("feature").exists(),
        "feature worktree should have been removed despite partial failure"
    );
}

#[rstest]
fn test_remove_by_name_dirty_target(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-dirty");

    // Create a dirty file in the target worktree
    std::fs::write(worktree_path.join("dirty.txt"), "uncommitted changes").unwrap();

    // Try to remove it by name from main repo
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &["feature-dirty"], None));
}

/// --force allows removal of dirty worktrees (issue #658)
/// This test: untracked files, branch at same commit as main
#[rstest]
fn test_remove_force_with_untracked_files(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-untracked");

    // Create an untracked file (like devbox.lock, .env, build artifacts)
    std::fs::write(worktree_path.join("devbox.lock"), "untracked content").unwrap();

    // Verify git sees it as untracked only
    let status = repo
        .git_command()
        .args(["status", "--porcelain"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();
    let status_output = String::from_utf8_lossy(&status.stdout);
    assert!(
        status_output.contains("?? devbox.lock"),
        "File should be untracked"
    );

    // Remove with --force should succeed
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--force", "feature-untracked"],
        None
    ));
}

/// --force allows removal of dirty worktrees (issue #658)
/// This test: modified tracked file, branch ahead of main (unmerged)
#[rstest]
fn test_remove_force_with_modified_files(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-modified");

    // Add a file to the worktree and commit it first
    std::fs::write(worktree_path.join("tracked.txt"), "original content").unwrap();
    repo.git_command()
        .args(["add", "tracked.txt"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Add tracked file"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();

    // Now modify the tracked file
    std::fs::write(worktree_path.join("tracked.txt"), "modified content").unwrap();

    // --force passes through to git, which allows this
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--force", "feature-modified"],
        None
    ));
}

/// --force allows removal of dirty worktrees (issue #658)
/// This test: staged (uncommitted) file, branch at same commit as main
#[rstest]
fn test_remove_force_with_staged_files(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-staged");

    // Create and stage a new file (but don't commit)
    std::fs::write(worktree_path.join("staged.txt"), "staged content").unwrap();
    repo.git_command()
        .args(["add", "staged.txt"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();

    // --force passes through to git, which allows this
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--force", "feature-staged"],
        None
    ));
}

/// --force + -D: dirty worktree AND unmerged branch
#[rstest]
fn test_remove_force_with_force_delete(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-dirty-unmerged");

    // Make a commit so the branch is ahead of main (unmerged)
    repo.git_command()
        .args(["commit", "--allow-empty", "-m", "feature commit"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();

    // Add untracked file to make the worktree dirty
    std::fs::write(worktree_path.join("untracked.txt"), "dirty").unwrap();

    // --force (dirty worktree) + -D (force delete unmerged branch)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--force", "-D", "feature-dirty-unmerged"],
        None
    ));
}

/// Regression test for issue #839: untracked files not deleted on Windows.
/// Verifies the worktree directory is actually removed, not just that the command succeeds.
#[rstest]
fn test_remove_force_actually_deletes_directory_with_untracked(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-untracked-delete");

    // Make a commit so the branch is ahead of main (unmerged)
    repo.git_command()
        .args(["commit", "--allow-empty", "-m", "feature commit"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();

    // Create untracked files (the scenario from issue #839)
    std::fs::write(worktree_path.join("untracked.txt"), "untracked content").unwrap();
    std::fs::create_dir_all(worktree_path.join("untracked_dir")).unwrap();
    std::fs::write(
        worktree_path.join("untracked_dir/nested.txt"),
        "nested untracked",
    )
    .unwrap();

    // Verify worktree exists before removal
    assert!(
        worktree_path.exists(),
        "Worktree should exist before removal"
    );

    // Remove with --force -D (the flags from issue #839)
    let output = repo
        .wt_command()
        .args([
            "remove",
            "--force",
            "-D",
            "--foreground",
            "feature-untracked-delete",
        ])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "wt remove --force -D should succeed, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // The critical assertion: directory must actually be gone
    assert!(
        !worktree_path.exists(),
        "Worktree directory should be deleted after `wt remove --force -D`, but it still exists"
    );

    // Verify branch is also deleted
    let branch_list = repo
        .git_command()
        .args(["branch", "--list", "feature-untracked-delete"])
        .run()
        .unwrap();
    assert!(
        String::from_utf8_lossy(&branch_list.stdout)
            .trim()
            .is_empty(),
        "Branch should be deleted with -D flag"
    );
}

#[rstest]
fn test_remove_multiple_worktrees(mut repo: TestRepo) {
    // Create three worktrees
    let _worktree_a = repo.add_worktree("feature-a");
    let _worktree_b = repo.add_worktree("feature-b");
    let _worktree_c = repo.add_worktree("feature-c");

    // Remove all three at once from main repo
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-a", "feature-b", "feature-c"],
        None
    ));
}

#[rstest]
fn test_remove_multiple_including_current(mut repo: TestRepo) {
    // Create three worktrees
    let worktree_a = repo.add_worktree("feature-a");
    let _worktree_b = repo.add_worktree("feature-b");
    let _worktree_c = repo.add_worktree("feature-c");

    // From worktree A, remove all three (including current)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-a", "feature-b", "feature-c"],
        Some(&worktree_a)
    ));
}

#[rstest]
fn test_remove_branch_not_fully_merged(mut repo: TestRepo) {
    // Create a worktree with an unmerged commit
    let worktree_path = repo.add_worktree("feature-unmerged");

    // Add a commit to the feature branch that's not in main
    std::fs::write(worktree_path.join("feature.txt"), "new feature").unwrap();
    repo.git_command()
        .args(["add", "feature.txt"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Add feature"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();

    // Try to remove it from the main repo
    // Branch deletion should fail but worktree removal should succeed
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-unmerged"],
        None
    ));
}

#[rstest]
fn test_remove_foreground(mut repo: TestRepo) {
    // Create a worktree
    let _worktree_path = repo.add_worktree("feature-fg");

    // Remove it with --foreground flag from main repo
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--foreground", "feature-fg"],
        None
    ));
}

/// Tests that --force-delete and --no-delete-branch are mutually exclusive
#[rstest]
fn test_remove_conflicting_branch_flags(repo: TestRepo) {
    // Try to use both --force-delete (-D) and --no-delete-branch together
    // This should fail with an error
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["-D", "--no-delete-branch", "nonexistent"],
        None
    ));
}

#[rstest]
fn test_remove_foreground_unmerged(mut repo: TestRepo) {
    // Create a worktree with an unmerged commit
    let worktree_path = repo.add_worktree("feature-unmerged-fg");

    // Add a commit to the feature branch that's not in main
    std::fs::write(worktree_path.join("feature.txt"), "new feature").unwrap();
    repo.git_command()
        .args(["add", "feature.txt"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Add feature"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();

    // Remove it with --foreground flag from main repo
    // Branch deletion should fail but worktree removal should succeed
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--foreground", "feature-unmerged-fg"],
        None
    ));
}

/// Tests foreground removal with --no-delete-branch on an integrated branch.
/// The hint should show "Branch integrated (reason); retained with --no-delete-branch"
#[rstest]
fn test_remove_foreground_no_delete_branch(mut repo: TestRepo) {
    // Create a worktree (integrated - same commit as main)
    let _worktree_path = repo.add_worktree("feature-fg-keep");

    // Remove with both --foreground and --no-delete-branch
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--foreground", "--no-delete-branch", "feature-fg-keep"],
        None
    ));
}

/// Tests foreground removal with --no-delete-branch on an unmerged branch.
/// No hint needed since the flag had no effect (branch wouldn't be deleted anyway).
#[rstest]
fn test_remove_foreground_no_delete_branch_unmerged(mut repo: TestRepo) {
    // Create a worktree with an unmerged commit
    let worktree_path = repo.add_worktree("feature-fg-unmerged-keep");

    // Add a commit to the feature branch that's not in main
    std::fs::write(worktree_path.join("feature.txt"), "new feature").unwrap();
    repo.git_command()
        .args(["add", "feature.txt"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Add feature"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();

    // Go back to main
    repo.git_command().args(["checkout", "main"]).run().unwrap();

    // Remove with both --foreground and --no-delete-branch
    // No hint because:
    // - Branch is unmerged (wouldn't be deleted anyway)
    // - --no-delete-branch had no effect
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &[
            "--foreground",
            "--no-delete-branch",
            "feature-fg-unmerged-keep",
        ],
        None
    ));
}

#[rstest]
fn test_remove_no_delete_branch(mut repo: TestRepo) {
    // Create a worktree (integrated - same commit as main)
    let _worktree_path = repo.add_worktree("feature-keep");

    // Remove worktree but keep the branch using --no-delete-branch flag
    // Since branch is integrated, the flag has an effect - hint explains this
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--no-delete-branch", "feature-keep"],
        None
    ));
}

#[rstest]
fn test_remove_no_delete_branch_unmerged(mut repo: TestRepo) {
    // Create a worktree with an unmerged commit
    let worktree_path = repo.add_worktree("feature-unmerged-keep");

    // Add a commit to the feature branch that's not in main
    std::fs::write(worktree_path.join("feature.txt"), "new feature").unwrap();
    repo.git_command()
        .args(["add", "feature.txt"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Add feature"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();

    // Go back to main before removing
    repo.git_command().args(["checkout", "main"]).run().unwrap();

    // Remove worktree with --no-delete-branch flag
    // Since branch is unmerged, the flag has no effect - no hint shown
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--no-delete-branch", "feature-unmerged-keep"],
        None
    ));
}

#[rstest]
fn test_remove_branch_only_merged(repo: TestRepo) {
    // Create a branch from main without a worktree (already merged)
    repo.git_command()
        .args(["branch", "feature-merged"])
        .run()
        .unwrap();

    // Remove the branch (no worktree exists)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-merged"],
        None
    ));
}

#[rstest]
fn test_remove_branch_only_unmerged(repo: TestRepo) {
    // Create a branch with a unique commit (not in main)
    repo.git_command()
        .args(["branch", "feature-unmerged"])
        .run()
        .unwrap();

    // Add a commit to the branch that's not in main
    repo.git_command()
        .args(["checkout", "feature-unmerged"])
        .run()
        .unwrap();
    std::fs::write(repo.root_path().join("feature.txt"), "new feature").unwrap();
    repo.git_command()
        .args(["add", "feature.txt"])
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Add feature"])
        .run()
        .unwrap();
    repo.git_command().args(["checkout", "main"]).run().unwrap();

    // Try to remove the branch (no worktree exists, branch not merged)
    // Branch deletion should fail but not error
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-unmerged"],
        None
    ));
}

#[rstest]
fn test_remove_branch_only_force_delete(repo: TestRepo) {
    // Create a branch with a unique commit (not in main)
    repo.git_command()
        .args(["branch", "feature-force"])
        .run()
        .unwrap();

    // Add a commit to the branch that's not in main
    repo.git_command()
        .args(["checkout", "feature-force"])
        .run()
        .unwrap();
    std::fs::write(repo.root_path().join("feature.txt"), "new feature").unwrap();
    repo.git_command()
        .args(["add", "feature.txt"])
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Add feature"])
        .run()
        .unwrap();
    repo.git_command().args(["checkout", "main"]).run().unwrap();

    // Force delete the branch (no worktree exists)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--force-delete", "feature-force"],
        None
    ));
}

///
/// When in detached HEAD, we should still be able to remove the current worktree
/// using path-based removal (no branch deletion).
#[rstest]
fn test_remove_from_detached_head_in_worktree(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-detached");

    // Detach HEAD in the worktree
    repo.detach_head_in_worktree("feature-detached");

    // Run remove from within the detached worktree (should still work)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &[],
        Some(&worktree_path)
    ));
}

///
/// Covers the foreground detached HEAD code path in handlers.rs.
/// The output should be "✓ Removed worktree (detached HEAD, no branch to delete)".
///
/// Ignored on Windows: subprocess tests stay in the worktree, causing file locking errors.
#[rstest]
#[cfg_attr(windows, ignore)]
fn test_remove_foreground_detached_head(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-detached-fg");

    // Detach HEAD in the worktree
    repo.detach_head_in_worktree("feature-detached-fg");

    // Run foreground remove from within the detached worktree
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--foreground"],
        Some(&worktree_path)
    ));
}

///
/// This should behave identically to `wt remove` (no args) - path-based removal
/// without branch deletion. The `@` symbol refers to the current worktree.
#[rstest]
fn test_remove_at_from_detached_head_in_worktree(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-detached-at");

    // Detach HEAD in the worktree
    repo.detach_head_in_worktree("feature-detached-at");

    // Run `wt remove @` from within the detached worktree (should behave same as no args)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["@"],
        Some(&worktree_path)
    ));
}

///
/// This simulates a squash merge workflow where:
/// - Feature branch has commits ahead of main
/// - Main is updated (e.g., via squash merge on GitHub) with the same content
/// - Branch is NOT an ancestor of main, but tree SHAs match
/// - Branch should be deleted because content is integrated
#[rstest]
fn test_remove_branch_matching_tree_content(repo: TestRepo) {
    // Create a feature branch from main
    repo.git_command()
        .args(["branch", "feature-squashed"])
        .run()
        .unwrap();

    // On feature branch: add a file
    repo.git_command()
        .args(["checkout", "feature-squashed"])
        .run()
        .unwrap();
    std::fs::write(repo.root_path().join("feature.txt"), "squash content").unwrap();
    repo.git_command()
        .args(["add", "feature.txt"])
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Add feature (on feature branch)"])
        .run()
        .unwrap();

    // On main: add the same file with same content (simulates squash merge result)
    repo.git_command().args(["checkout", "main"]).run().unwrap();
    std::fs::write(repo.root_path().join("feature.txt"), "squash content").unwrap();
    repo.git_command()
        .args(["add", "feature.txt"])
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Add feature (squash merged)"])
        .run()
        .unwrap();

    // Verify the setup: feature-squashed is NOT an ancestor of main (different commits)
    let is_ancestor = repo
        .git_command()
        .args(["merge-base", "--is-ancestor", "feature-squashed", "main"])
        .run()
        .unwrap();
    assert!(
        !is_ancestor.status.success(),
        "feature-squashed should NOT be an ancestor of main"
    );

    // Verify: tree SHAs should match
    let feature_tree = String::from_utf8(
        repo.git_command()
            .args(["rev-parse", "feature-squashed^{tree}"])
            .run()
            .unwrap()
            .stdout,
    )
    .unwrap();
    let main_tree = String::from_utf8(
        repo.git_command()
            .args(["rev-parse", "main^{tree}"])
            .run()
            .unwrap()
            .stdout,
    )
    .unwrap();
    assert_eq!(
        feature_tree.trim(),
        main_tree.trim(),
        "Tree SHAs should match (same content)"
    );

    // Remove the branch - should succeed because tree content matches main
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-squashed"],
        None
    ));
}
///
/// This test documents the expected behavior:
/// 1. Linked worktrees can be removed (whether from within them or from elsewhere)
/// 2. The main worktree cannot be removed under any circumstances
/// 3. This is true regardless of which branch is checked out in the main worktree
///
/// Skipped on Windows: Tests run as subprocesses which can't change directory via shell
/// integration. Real users are fine - shell integration cds to main before removing.
/// But subprocess tests stay in the worktree, causing Windows file locking errors.
#[rstest]
#[cfg_attr(windows, ignore)]
fn test_remove_main_worktree_vs_linked_worktree(mut repo: TestRepo) {
    // Create a linked worktree
    let linked_wt_path = repo.add_worktree("feature");

    // Part 1: Verify linked worktree CAN be removed (from within it)
    // Use --foreground to ensure removal completes before creating next worktree
    assert_cmd_snapshot!(
        "remove_main_vs_linked__from_linked_succeeds",
        make_snapshot_cmd(&repo, "remove", &["--foreground"], Some(&linked_wt_path))
    );

    // Part 2: Recreate the linked worktree for the next test
    let _linked_wt_path = repo.add_worktree("feature2");

    // Part 3: Verify linked worktree CAN be removed (from main, by name)
    assert_cmd_snapshot!(
        "remove_main_vs_linked__from_main_by_name_succeeds",
        make_snapshot_cmd(&repo, "remove", &["feature2"], None)
    );

    // Part 4: Verify main worktree CANNOT be removed (from main, on default branch)
    assert_cmd_snapshot!(
        "remove_main_vs_linked__main_on_default_fails",
        make_snapshot_cmd(&repo, "remove", &[], None)
    );

    // Part 5: Create a feature branch IN the main worktree, verify STILL cannot remove
    repo.run_git(&["switch", "-c", "feature-in-main"]);

    assert_cmd_snapshot!(
        "remove_main_vs_linked__main_on_feature_fails",
        make_snapshot_cmd(&repo, "remove", &[], None)
    );

    // Part 6: Verify main worktree CANNOT be removed by name from a linked worktree
    // Switch back to main branch in main worktree, then create a new linked worktree
    repo.run_git(&["switch", "main"]);

    let linked_for_test = repo.add_worktree("test-from-linked");
    assert_cmd_snapshot!(
        "remove_main_vs_linked__main_by_name_from_linked_fails",
        make_snapshot_cmd(&repo, "remove", &["main"], Some(&linked_for_test))
    );
}

/// Removing the default branch worktree should be refused — the default branch
/// is the integration target, not something to remove.
///
/// This requires a bare repo setup since you can't have a linked worktree for the default
/// branch in a normal repo (the main worktree already has it checked out).
#[test]
fn test_remove_default_branch_refused() {
    let test = BareRepoTest::new();

    // Create worktrees for main and feature branches
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit on main");
    let feature_worktree = test.create_worktree("feature", "feature");

    let settings = setup_temp_snapshot_settings(test.temp_path());

    // Without -D: should fail
    settings.bind(|| {
        let mut cmd = test.wt_command();
        cmd.args(["remove", "--foreground", "main"])
            .current_dir(&feature_worktree);

        assert_cmd_snapshot!("remove_default_branch_refused", cmd);
    });

    // With -D: should succeed (user explicitly force-deletes)
    settings.bind(|| {
        let mut cmd = test.wt_command();
        cmd.args(["remove", "--foreground", "-D", "main"])
            .current_dir(&feature_worktree);

        assert_cmd_snapshot!("remove_default_branch_force_delete", cmd);
    });
}

/// BranchOnly path: when the default branch has no worktree (directory deleted),
/// removal should be refused without -D, and allowed with -D.
#[test]
fn test_remove_default_branch_branch_only() {
    let test = BareRepoTest::new();

    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit on main");
    let feature_worktree = test.create_worktree("feature", "feature");

    // Delete main worktree directory so it becomes a BranchOnly removal
    std::fs::remove_dir_all(&main_worktree).unwrap();

    let settings = setup_temp_snapshot_settings(test.temp_path());

    // Without -D: should be refused
    settings.bind(|| {
        let mut cmd = test.wt_command();
        cmd.args(["remove", "main"]).current_dir(&feature_worktree);

        assert_cmd_snapshot!("remove_default_branch_branch_only_refused", cmd);
    });

    // With -D: should succeed (force-delete the default branch)
    settings.bind(|| {
        let mut cmd = test.wt_command();
        cmd.args(["remove", "-D", "main"])
            .current_dir(&feature_worktree);

        assert_cmd_snapshot!("remove_default_branch_branch_only_force_delete", cmd);
    });
}

///
/// This tests the scenario:
/// 1. Create feature branch from main and make changes (file A)
/// 2. Squash-merge feature into main (main now has A via squash commit)
/// 3. Main advances with more commits (file B)
/// 4. Try to remove feature
///
/// The branch should be detected as integrated because its content (A) is
/// already in main, even though main has additional content (B).
///
/// This is detected via merge simulation: `git merge-tree --write-tree main feature`
/// produces the same tree as main, meaning merging feature would add nothing.
#[rstest]
fn test_remove_squash_merged_then_main_advanced(repo: TestRepo) {
    // Create feature branch
    repo.git_command()
        .args(["checkout", "-b", "feature-squash"])
        .run()
        .unwrap();

    // Make changes on feature branch (file A)
    std::fs::write(repo.root_path().join("feature-a.txt"), "feature content").unwrap();
    repo.git_command()
        .args(["add", "feature-a.txt"])
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Add feature A"])
        .run()
        .unwrap();

    // Go back to main
    repo.git_command().args(["checkout", "main"]).run().unwrap();

    // Squash merge feature into main (simulating GitHub squash merge)
    // This creates a NEW commit on main with the same content changes
    std::fs::write(repo.root_path().join("feature-a.txt"), "feature content").unwrap();
    repo.git_command()
        .args(["add", "feature-a.txt"])
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Add feature A (squash merged)"])
        .run()
        .unwrap();

    // Main advances with another commit (file B)
    std::fs::write(repo.root_path().join("main-b.txt"), "main content").unwrap();
    repo.git_command()
        .args(["add", "main-b.txt"])
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Main advances with B"])
        .run()
        .unwrap();

    // Verify setup: feature-squash is NOT an ancestor of main (squash creates different SHAs)
    let is_ancestor = repo
        .git_command()
        .args(["merge-base", "--is-ancestor", "feature-squash", "main"])
        .run()
        .unwrap();
    assert!(
        !is_ancestor.status.success(),
        "feature-squash should NOT be an ancestor of main (squash merge)"
    );

    // Verify setup: trees don't match (main has file B that feature doesn't)
    let feature_tree = String::from_utf8(
        repo.git_command()
            .args(["rev-parse", "feature-squash^{tree}"])
            .run()
            .unwrap()
            .stdout,
    )
    .unwrap();
    let main_tree = String::from_utf8(
        repo.git_command()
            .args(["rev-parse", "main^{tree}"])
            .run()
            .unwrap()
            .stdout,
    )
    .unwrap();
    assert_ne!(
        feature_tree.trim(),
        main_tree.trim(),
        "Tree SHAs should differ (main has file B that feature doesn't)"
    );

    // Remove the feature branch - should succeed because content is integrated
    // (detected via merge simulation using git merge-tree)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-squash"],
        None
    ));
}

/// Squash merge where target later modifies the SAME files (#1818).
///
/// This is the scenario from issue #1818:
///   1. Branch modifies file A
///   2. Squash-merge lands on main (file A matches branch content)
///   3. Main later modifies file A again (advancing past the squash merge)
///   4. `wt remove` should still detect integration
///
/// Previous behavior: `git merge-tree --write-tree` conflicts on file A because
/// both sides changed it, and the code conservatively treats conflicts as
/// "not integrated". The fix uses patch-id matching as a fallback.
#[rstest]
fn test_remove_squash_merged_then_same_files_modified(repo: TestRepo) {
    // Create feature branch
    repo.git_command()
        .args(["checkout", "-b", "feature-squash-conflict"])
        .run()
        .unwrap();

    // Make changes on feature branch (file A)
    std::fs::write(repo.root_path().join("feature-a.txt"), "feature content").unwrap();
    repo.git_command()
        .args(["add", "feature-a.txt"])
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Add feature A"])
        .run()
        .unwrap();

    // Go back to main
    repo.git_command().args(["checkout", "main"]).run().unwrap();

    // Squash merge feature into main (simulating GitHub squash merge)
    std::fs::write(repo.root_path().join("feature-a.txt"), "feature content").unwrap();
    repo.git_command()
        .args(["add", "feature-a.txt"])
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Add feature A (squash merged)"])
        .run()
        .unwrap();

    // Main advances by modifying the SAME file (the key difference from the previous test)
    std::fs::write(
        repo.root_path().join("feature-a.txt"),
        "feature content\nplus more changes on main",
    )
    .unwrap();
    repo.git_command()
        .args(["add", "feature-a.txt"])
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Main advances same file"])
        .run()
        .unwrap();

    // Verify setup: merge-tree would conflict (this is the scenario from #1818)
    let merge_tree_result = repo
        .git_command()
        .args([
            "merge-tree",
            "--write-tree",
            "main",
            "feature-squash-conflict",
        ])
        .run()
        .unwrap();
    assert!(
        !merge_tree_result.status.success(),
        "merge-tree should report conflicts (both sides modified feature-a.txt)"
    );

    // Remove the feature branch - should succeed because content is integrated
    // (detected via patch-id fallback when merge-tree conflicts)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-squash-conflict"],
        None
    ));
}

/// Simulate a GitHub squash merge: push feature to origin, squash-merge on
/// the remote side (via a temporary clone), fetch locally, then `wt remove`.
///
/// This is the exact workflow that users hit:
///   1. Create worktree, commit, push, open PR
///   2. Squash-merge on GitHub
///   3. `git fetch` locally
///   4. `wt remove <branch>` — should detect integration via origin/main
///
/// The integration detection must use `effective_integration_target()` to check
/// against `origin/main` (which is ahead of local `main` after fetch).
#[rstest]
fn test_remove_squash_merged_on_remote(#[from(repo_with_remote)] repo: TestRepo) {
    let remote_path = repo.remote_path().unwrap();

    // Create a feature branch with multiple commits (realistic PR)
    repo.run_git(&["checkout", "-b", "feature-remote-squash"]);
    std::fs::write(repo.root_path().join("feature.txt"), "initial").unwrap();
    repo.run_git(&["add", "feature.txt"]);
    repo.run_git(&["commit", "-m", "Add feature file"]);
    std::fs::write(repo.root_path().join("feature.txt"), "revised").unwrap();
    repo.run_git(&["add", "feature.txt"]);
    repo.run_git(&["commit", "-m", "Revise feature"]);
    std::fs::write(repo.root_path().join("feature.txt"), "final version").unwrap();
    repo.run_git(&["add", "feature.txt"]);
    repo.run_git(&["commit", "-m", "Finalize feature"]);
    repo.run_git(&["push", "-u", "origin", "feature-remote-squash"]);

    // Go back to main locally (don't pull — local main stays behind)
    repo.run_git(&["checkout", "main"]);

    // Simulate GitHub squash merge: clone the bare remote into a temp dir,
    // squash-merge there, push back to the bare remote
    let github_sim = repo.home_path().join("github-sim");
    repo.run_git_in(
        repo.home_path(),
        &["clone", remote_path.to_str().unwrap(), "github-sim"],
    );
    // Squash merge feature into main (like GitHub's "Squash and merge" button)
    repo.run_git_in(
        &github_sim,
        &["merge", "--squash", "origin/feature-remote-squash"],
    );
    repo.run_git_in(&github_sim, &["commit", "-m", "Add feature (#1)"]);
    // Push the squash merge back to the bare remote
    repo.run_git_in(&github_sim, &["push", "origin", "main"]);

    // Fetch locally — origin/main now has the squash merge, local main does not
    repo.run_git(&["fetch", "origin"]);

    // Verify setup: local main is behind origin/main
    let local_main = repo.git_output(&["rev-parse", "main"]);
    let origin_main = repo.git_output(&["rev-parse", "origin/main"]);
    assert_ne!(
        local_main, origin_main,
        "local main should be behind origin/main"
    );

    // Remove the feature branch — should detect as integrated via origin/main
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-remote-squash"],
        None
    ));
}

/// Like `test_remove_squash_merged_on_remote`, but local `main` also advances
/// with a local-only commit after the fetch. Integration should still be
/// detected via `origin/main`.
#[rstest]
fn test_remove_squash_merged_on_remote_when_local_main_diverged(
    #[from(repo_with_remote)] repo: TestRepo,
) {
    let remote_path = repo.remote_path().unwrap();

    repo.run_git(&["checkout", "-b", "feature-remote-squash-diverged"]);
    std::fs::write(repo.root_path().join("feature-diverged.txt"), "initial").unwrap();
    repo.run_git(&["add", "feature-diverged.txt"]);
    repo.run_git(&["commit", "-m", "Add diverged feature"]);
    std::fs::write(
        repo.root_path().join("feature-diverged.txt"),
        "final version",
    )
    .unwrap();
    repo.run_git(&["add", "feature-diverged.txt"]);
    repo.run_git(&["commit", "-m", "Finalize diverged feature"]);
    repo.run_git(&["push", "-u", "origin", "feature-remote-squash-diverged"]);
    repo.run_git(&["checkout", "main"]);

    // Simulate a remote squash merge.
    let github_sim = repo.home_path().join("github-sim-diverged");
    repo.run_git_in(
        repo.home_path(),
        &[
            "clone",
            remote_path.to_str().unwrap(),
            "github-sim-diverged",
        ],
    );
    repo.run_git_in(
        &github_sim,
        &["merge", "--squash", "origin/feature-remote-squash-diverged"],
    );
    repo.run_git_in(&github_sim, &["commit", "-m", "Add diverged feature (#3)"]);
    repo.run_git_in(&github_sim, &["push", "origin", "main"]);

    // Fetch the remote squash merge, then create a local-only commit on main so
    // local and upstream diverge.
    repo.run_git(&["fetch", "origin"]);
    std::fs::write(repo.root_path().join("local-only.txt"), "local only").unwrap();
    repo.run_git(&["add", "local-only.txt"]);
    repo.run_git(&["commit", "-m", "Local-only main commit"]);

    let local_main = repo.git_output(&["rev-parse", "main"]);
    let origin_main = repo.git_output(&["rev-parse", "origin/main"]);
    assert_ne!(
        local_main, origin_main,
        "local main should diverge from origin/main"
    );

    let local_behind_remote = repo
        .git_command()
        .args(["merge-base", "--is-ancestor", "main", "origin/main"])
        .run()
        .unwrap();
    assert!(
        !local_behind_remote.status.success(),
        "local main should not be an ancestor of origin/main in diverged state"
    );

    let remote_behind_local = repo
        .git_command()
        .args(["merge-base", "--is-ancestor", "origin/main", "main"])
        .run()
        .unwrap();
    assert!(
        !remote_behind_local.status.success(),
        "origin/main should not be an ancestor of local main in diverged state"
    );

    let output = make_snapshot_cmd(&repo, "remove", &["feature-remote-squash-diverged"], None)
        .output()
        .unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr)
        .ansi_strip()
        .into_owned();

    assert!(
        stderr.contains("Removed branch feature-remote-squash-diverged"),
        "expected branch to be removed once origin/main contains the squash merge\nstderr:\n{stderr}",
    );
    assert!(
        stderr.contains("origin/main"),
        "expected remove output to mention origin/main as the integration target\nstderr:\n{stderr}",
    );

    let branch_still_exists = repo
        .git_command()
        .args([
            "rev-parse",
            "--verify",
            "--quiet",
            "refs/heads/feature-remote-squash-diverged",
        ])
        .run()
        .unwrap();
    assert!(
        !branch_still_exists.status.success(),
        "feature branch should be deleted after successful remove"
    );
}

/// Like `test_remove_squash_merged_on_remote`, but main advances on the
/// remote after the squash merge.
/// Tests that `MergeAddsNothing` detection works through origin/main.
#[rstest]
fn test_remove_squash_merged_on_remote_then_advanced(#[from(repo_with_remote)] repo: TestRepo) {
    let remote_path = repo.remote_path().unwrap();

    // Create a feature branch with multiple commits (realistic PR)
    repo.run_git(&["checkout", "-b", "feature-remote-squash2"]);
    std::fs::write(repo.root_path().join("feature2.txt"), "draft").unwrap();
    repo.run_git(&["add", "feature2.txt"]);
    repo.run_git(&["commit", "-m", "WIP: start feature 2"]);
    std::fs::write(repo.root_path().join("feature2.txt"), "done").unwrap();
    repo.run_git(&["add", "feature2.txt"]);
    repo.run_git(&["commit", "-m", "Complete feature 2"]);
    repo.run_git(&["push", "-u", "origin", "feature-remote-squash2"]);

    // Go back to main locally
    repo.run_git(&["checkout", "main"]);

    // Simulate GitHub: squash merge, then main advances with another commit
    let github_sim = repo.home_path().join("github-sim2");
    repo.run_git_in(
        repo.home_path(),
        &["clone", remote_path.to_str().unwrap(), "github-sim2"],
    );
    repo.run_git_in(
        &github_sim,
        &["merge", "--squash", "origin/feature-remote-squash2"],
    );
    repo.run_git_in(&github_sim, &["commit", "-m", "Add feature 2 (#2)"]);
    // Main advances with another commit after the squash merge
    std::fs::write(github_sim.join("other.txt"), "other content").unwrap();
    repo.run_git_in(&github_sim, &["add", "other.txt"]);
    repo.run_git_in(&github_sim, &["commit", "-m", "Unrelated commit"]);
    repo.run_git_in(&github_sim, &["push", "origin", "main"]);

    // Fetch locally
    repo.run_git(&["fetch", "origin"]);

    // Verify setup: local main is behind origin/main
    let local_main = repo.git_output(&["rev-parse", "main"]);
    let origin_main = repo.git_output(&["rev-parse", "origin/main"]);
    assert_ne!(
        local_main, origin_main,
        "local main should be behind origin/main"
    );

    // Remove the feature branch — should detect as integrated via origin/main
    // even though origin/main has advanced past the squash merge
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-remote-squash2"],
        None
    ));
}

/// Like `test_remove_squash_merged_on_remote`, but with a **worktree** (not just
/// a branch). Tests that the `RemovedWorktree` path displays the effective target
/// (`origin/main`) rather than the local default branch when upstream is ahead.
#[rstest]
fn test_remove_worktree_squash_merged_on_remote(#[from(repo_with_remote)] mut repo: TestRepo) {
    let remote_path = repo.remote_path().unwrap().to_path_buf();

    // Create a worktree for the feature branch
    let _wt_path = repo.add_worktree("feature-wt-squash");
    let wt_path = repo.worktrees["feature-wt-squash"].clone();
    std::fs::write(wt_path.join("feature-wt.txt"), "feature content").unwrap();
    repo.run_git_in(&wt_path, &["add", "feature-wt.txt"]);
    repo.run_git_in(&wt_path, &["commit", "-m", "Add feature"]);
    repo.run_git_in(&wt_path, &["push", "-u", "origin", "feature-wt-squash"]);

    // Simulate GitHub squash merge on the remote
    let github_sim = repo.home_path().join("github-sim-wt");
    repo.run_git_in(
        repo.home_path(),
        &["clone", remote_path.to_str().unwrap(), "github-sim-wt"],
    );
    repo.run_git_in(
        &github_sim,
        &["merge", "--squash", "origin/feature-wt-squash"],
    );
    repo.run_git_in(&github_sim, &["commit", "-m", "Add feature (#1)"]);
    repo.run_git_in(&github_sim, &["push", "origin", "main"]);

    // Fetch locally — origin/main now has the squash merge, local main does not
    repo.run_git(&["fetch", "origin"]);

    // Remove the worktree — should show origin/main as the integration target
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-wt-squash"],
        None
    ));
}

// ============================================================================
// Pre-Remove Hook Tests
// ============================================================================

#[rstest]
fn test_pre_remove_hook_executes(mut repo: TestRepo) {
    // Create project config with pre-remove hook
    repo.write_project_config(r#"pre-remove = "echo 'About to remove worktree'""#);
    repo.commit("Add config");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo 'About to remove worktree'"]
"#,
    );

    // Create a worktree to remove
    let _worktree_path = repo.add_worktree("feature-hook");

    // Remove with --foreground to ensure synchronous execution
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--foreground", "feature-hook"],
        None
    ));
}

#[rstest]
fn test_pre_remove_hook_template_variables(mut repo: TestRepo) {
    // Create project config with template variables
    repo.write_project_config(
        r#"pre-remove = [
    {branch = "echo 'Branch: {{ branch }}'"},
    {worktree = "echo 'Worktree: {{ worktree_path }}'"},
    {worktree_name = "echo 'Name: {{ worktree_name }}'"},
]
"#,
    );
    repo.commit("Add config with templates");

    // Pre-approve the commands (templates match what's shown in prompts)
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = [
    "echo 'Branch: {{ branch }}'",
    "echo 'Worktree: {{ worktree_path }}'",
    "echo 'Name: {{ worktree_name }}'",
]
"#,
    );

    // Create a worktree to remove
    let _worktree_path = repo.add_worktree("feature-templates");

    // Remove with --foreground
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--foreground", "feature-templates"],
        None
    ));
}

#[rstest]
fn test_pre_remove_hook_runs_in_background_mode(mut repo: TestRepo) {
    use crate::common::wait_for_file;

    // Create a marker file that the hook will create
    let marker_file = repo.root_path().join("hook-ran.txt");

    // Create project config with hook that creates a file
    repo.write_project_config(&format!(
        r#"pre-remove = "echo 'hook ran' > {}""#,
        marker_file.to_slash_lossy()
    ));
    repo.commit("Add config");

    // Pre-approve the command
    repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
    repo.write_test_approvals(&format!(
        r#"[projects."../origin"]
approved-commands = ["echo 'hook ran' > {}"]
"#,
        marker_file.to_slash_lossy()
    ));

    // Create a worktree to remove
    let _worktree_path = repo.add_worktree("feature-bg");

    // Remove in background mode (default)
    let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_wt"));
    repo.configure_wt_cmd(&mut cmd);
    cmd.current_dir(repo.root_path())
        .args(["remove", "feature-bg"])
        .output()
        .unwrap();

    // Wait for the hook to create the marker file
    wait_for_file(&marker_file);

    // Marker file SHOULD exist - pre-remove hooks run before background removal starts
    assert!(
        marker_file.exists(),
        "Pre-remove hook should run even in background mode"
    );
}

#[rstest]
fn test_pre_remove_hook_failure_aborts(mut repo: TestRepo) {
    // Create project config with failing hook
    repo.write_project_config(r#"pre-remove = "exit 1""#);
    repo.commit("Add config");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["exit 1"]
"#,
    );

    // Create a worktree to remove
    let worktree_path = repo.add_worktree("feature-fail");

    // Remove - should FAIL due to hook failure
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--foreground", "feature-fail"],
        None
    ));

    // Verify worktree was NOT removed (hook failure aborted removal)
    assert!(
        worktree_path.exists(),
        "Worktree should NOT be removed when hook fails"
    );
}

/// Pre-remove hook failure should NOT write cd directive.
/// Bug: cd directive was written before pre-remove hooks ran, so if hooks failed,
/// the shell would still cd to main_path even though the worktree wasn't removed.
#[rstest]
fn test_pre_remove_hook_failure_no_cd_directive(mut repo: TestRepo) {
    // Create project config with failing hook
    repo.write_project_config(r#"pre-remove = "exit 1""#);
    repo.commit("Add config");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["exit 1"]
"#,
    );

    // Create a worktree to remove
    let worktree_path = repo.add_worktree("feature-cd-test");

    // Set up directive files
    let (cd_path, exec_path, _guard) = directive_files();

    // Run remove from within the worktree (which would trigger cd to main if it worked)
    let mut cmd = repo.wt_command();
    cmd.args(["remove", "--foreground"]);
    cmd.current_dir(&worktree_path);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    let output = cmd.output().unwrap();

    // Command should have failed (hook failure)
    assert!(
        !output.status.success(),
        "Remove should fail when pre-remove hook fails"
    );

    // CD file should be empty (no path written when hook fails)
    let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
    assert!(
        cd_content.trim().is_empty(),
        "CD file should be empty when hook fails, got: {}",
        cd_content
    );

    // Worktree should still exist
    assert!(
        worktree_path.exists(),
        "Worktree should NOT be removed when hook fails"
    );
}

#[rstest]
fn test_pre_remove_hook_not_for_branch_only(repo: TestRepo) {
    // Create a marker file that the hook would create
    let marker_file = repo.root_path().join("branch-only-hook.txt");

    // Create project config with hook
    repo.write_project_config(&format!(
        r#"pre-remove = "echo 'hook ran' > {}""#,
        marker_file.to_slash_lossy()
    ));
    repo.commit("Add config");

    // Pre-approve the command
    repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
    repo.write_test_approvals(&format!(
        r#"[projects."../origin"]
approved-commands = ["echo 'hook ran' > {}"]
"#,
        marker_file.to_slash_lossy()
    ));

    // Create a branch without a worktree
    repo.git_command()
        .args(["branch", "branch-only"])
        .run()
        .unwrap();

    // Remove the branch (no worktree)
    let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_wt"));
    repo.configure_wt_cmd(&mut cmd);
    cmd.current_dir(repo.root_path())
        .args(["remove", "branch-only"])
        .output()
        .unwrap();

    // Marker file should NOT exist - pre-remove hooks only run for worktree removal
    assert!(
        !marker_file.exists(),
        "Pre-remove hook should NOT run for branch-only removal"
    );
}

#[rstest]
fn test_pre_remove_hook_skipped_with_no_hooks(mut repo: TestRepo) {
    use std::thread;

    // Create a marker file that the hook would create
    let marker_file = repo.root_path().join("should-not-exist.txt");

    // Create project config with hook that creates a file
    repo.write_project_config(&format!(
        r#"pre-remove = "echo 'hook ran' > {}""#,
        marker_file.to_slash_lossy()
    ));
    repo.commit("Add config");

    // Pre-approve the command (even though it shouldn't run)
    repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
    repo.write_test_approvals(&format!(
        r#"[projects."../origin"]
approved-commands = ["echo 'hook ran' > {}"]
"#,
        marker_file.to_slash_lossy()
    ));

    // Create a worktree to remove
    let worktree_path = repo.add_worktree("feature-skip");

    // Remove with --no-hooks to skip hooks
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--foreground", "--no-hooks", "feature-skip"],
        None
    ));

    // Wait for any potential hook execution (absence check - can't poll, use 500ms per guidelines)
    thread::sleep(Duration::from_millis(500));

    // Marker file should NOT exist - --no-hooks skips the hook
    assert!(
        !marker_file.exists(),
        "Pre-remove hook should NOT run with --no-hooks"
    );

    // Worktree should be removed (removal itself succeeds)
    assert!(
        !worktree_path.exists(),
        "Worktree should be removed even with --no-hooks"
    );
}

///
/// Even when a worktree is in detached HEAD state (no branch), the pre-remove
/// hook should still execute.
///
/// Skipped on Windows: Tests run as subprocesses which can't change directory via shell
/// integration. Real users are fine - shell integration cds to main before removing.
/// But subprocess tests stay in the worktree, causing Windows file locking errors.
#[rstest]
#[cfg_attr(windows, ignore)]
fn test_pre_remove_hook_runs_for_detached_head(mut repo: TestRepo) {
    // Create marker file path in the repo root
    // Use short filename to avoid terminal line-wrapping differences between platforms
    // (macOS temp paths are ~60 chars vs Linux ~20 chars, affecting wrap points)
    let marker_file = repo.root_path().join("m.txt");
    let marker_path = marker_file.to_slash_lossy();

    // Create project config with pre-remove hook that creates a marker file
    repo.write_project_config(&format!(r#"pre-remove = "touch {marker_path}""#,));
    repo.commit("Add config");

    // Pre-approve the command
    repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
    repo.write_test_approvals(&format!(
        r#"[projects."../origin"]
approved-commands = ["touch {marker_path}"]
"#,
    ));

    // Create a worktree and detach HEAD
    let worktree_path = repo.add_worktree("feature-detached-hook");
    repo.detach_head_in_worktree("feature-detached-hook");

    // Remove with --foreground to ensure synchronous execution
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--foreground"],
        Some(&worktree_path)
    ));

    // Marker file should exist - hook ran
    assert!(
        marker_file.exists(),
        "Pre-remove hook should run for detached HEAD worktrees"
    );
}

///
/// This complements `test_pre_remove_hook_runs_for_detached_head` by verifying
/// the hook also runs when removal happens in background (the default).
#[rstest]
fn test_pre_remove_hook_runs_for_detached_head_background(mut repo: TestRepo) {
    // Create marker file path in the repo root
    let marker_file = repo.root_path().join("detached-bg-hook-marker.txt");

    // Create project config with pre-remove hook that creates a marker file
    let marker_path = marker_file.to_slash_lossy();
    repo.write_project_config(&format!(r#"pre-remove = "touch {marker_path}""#,));
    repo.commit("Add config");

    // Pre-approve the commands
    repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
    repo.write_test_approvals(&format!(
        r#"[projects."../origin"]
approved-commands = ["touch {marker_path}"]
"#,
    ));

    // Create a worktree and detach HEAD
    let worktree_path = repo.add_worktree("feature-detached-bg");
    repo.detach_head_in_worktree("feature-detached-bg");

    // Remove in background mode (default)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &[],
        Some(&worktree_path)
    ));

    // Marker file should exist - hook ran before background spawn
    assert!(
        marker_file.exists(),
        "Pre-remove hook should run for detached HEAD worktrees in background mode"
    );
}

///
/// This is a non-snapshot test to avoid cross-platform line-wrapping differences
/// (macOS temp paths are ~60 chars vs Linux ~20 chars). The snapshot version
/// of this test (`test_pre_remove_hook_runs_for_detached_head`) verifies the hook runs;
/// this test verifies the specific template expansion behavior.
///
/// Skipped on Windows: Tests run as subprocesses which can't change directory via shell
/// integration. Real users are fine - shell integration cds to main before removing.
/// But subprocess tests stay in the worktree, causing Windows file locking errors.
#[rstest]
#[cfg_attr(windows, ignore)]
fn test_pre_remove_hook_branch_expansion_detached_head(mut repo: TestRepo) {
    // Create a file where the hook will write the branch template expansion
    let branch_file = repo.root_path().join("branch-expansion.txt");
    let branch_path = branch_file.to_slash_lossy();

    // Create project config with hook that writes {{ branch }} to file
    repo.write_project_config(&format!(
        r#"pre-remove = "echo 'branch={{{{ branch }}}}' > {branch_path}""#,
    ));
    repo.commit("Add config");

    // Pre-approve the command
    repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
    repo.write_test_approvals(&format!(
        r#"[projects."../origin"]
approved-commands = ["echo 'branch={{{{ branch }}}}' > {branch_path}"]
"#,
    ));

    // Create a worktree and detach HEAD
    let worktree_path = repo.add_worktree("feature-branch-test");
    repo.detach_head_in_worktree("feature-branch-test");

    // Run wt remove (not a snapshot test - just verify behavior)
    let output = wt_command()
        .args(["remove", "--foreground"])
        .current_dir(&worktree_path)
        .env("WORKTRUNK_CONFIG_PATH", repo.test_config_path())
        .env("WORKTRUNK_APPROVALS_PATH", repo.test_approvals_path())
        .output()
        .expect("Failed to execute wt remove");

    assert!(
        output.status.success(),
        "wt remove should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Verify {{ branch }} expanded to "HEAD" (fallback for detached HEAD state)
    let content =
        std::fs::read_to_string(&branch_file).expect("Hook should have created the branch file");
    assert_eq!(
        content.trim(),
        "branch=HEAD",
        "{{ branch }} should expand to 'HEAD' for detached HEAD worktrees"
    );
}

///
/// When a worktree is created at a path that doesn't match the config template,
/// `wt remove` should show a warning about the path mismatch.
#[rstest]
fn test_remove_path_mismatch_warning(repo: TestRepo) {
    // Create a worktree at a non-standard path using raw git
    // (wt switch --create would put it at the expected path)
    let unexpected_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join("weird-path-for-feature");

    repo.git_command()
        .args([
            "worktree",
            "add",
            unexpected_path.to_str().unwrap(),
            "-b",
            "feature",
        ])
        .run()
        .unwrap();

    // Remove the worktree - should show path mismatch warning
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &["feature"], None));
}

#[rstest]
fn test_remove_path_mismatch_warning_foreground(repo: TestRepo) {
    // Create a worktree at a non-standard path using raw git
    let unexpected_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join("another-weird-path");

    repo.git_command()
        .args([
            "worktree",
            "add",
            unexpected_path.to_str().unwrap(),
            "-b",
            "feature-fg",
        ])
        .run()
        .unwrap();

    // Remove in foreground mode - should show path mismatch warning
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--foreground", "feature-fg"],
        None
    ));
}

#[rstest]
fn test_remove_detached_worktree_in_multi(mut repo: TestRepo) {
    // Create two worktrees
    let _feature_a = repo.add_worktree("feature-a");
    let _feature_b = repo.add_worktree("feature-b");

    // Detach HEAD in feature-b
    repo.detach_head_in_worktree("feature-b");

    // From main, try to multi-remove both
    // feature-a should succeed, feature-b should fail (detached HEAD)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-a", "feature-b"],
        None
    ));
}

/// Reproduces #1661: "(detached)" is not a valid branch name — verify it fails.
#[rstest]
fn test_remove_detached_by_name_fails(mut repo: TestRepo) {
    repo.add_worktree("feature-detached");
    repo.detach_head_in_worktree("feature-detached");

    // "(detached)" is not a branch name — this should fail
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &["(detached)"], None));
}

/// Verify that detached worktrees can be removed by absolute path (#1661).
/// This ensures the CLI supports the same operation the picker uses.
#[rstest]
fn test_remove_detached_worktree_by_path(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-detached");
    repo.detach_head_in_worktree("feature-detached");

    assert!(worktree_path.exists());

    let worktree_str = worktree_path.to_string_lossy().to_string();
    let output = repo
        .wt_command()
        .args(["remove", &worktree_str, "--foreground", "--yes"])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "wt remove should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        !worktree_path.exists(),
        "Worktree directory should be removed"
    );
}

/// Verify that detached worktrees can be removed by relative path.
/// This tests resolve_worktree_arg's CWD-relative path resolution for Remove context.
#[rstest]
fn test_remove_detached_worktree_by_relative_path(mut repo: TestRepo) {
    repo.add_worktree("feature-detached");
    repo.detach_head_in_worktree("feature-detached");

    // From the main worktree (repo/), the relative path resolves against CWD
    let relative_path = "../repo.feature-detached";
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &[relative_path, "--foreground", "--yes"],
        None,
    ));
}

/// Test that resolve_worktree("@") works when the worktree is accessed via a symlink.
///
/// This tests the path normalization fix where:
/// - `root()` returns a canonicalized path (symlinks resolved)
/// - `wt.path` from git is the raw path (symlinks not resolved)
///
/// Without proper canonicalization, comparison fails on systems with symlinks
/// (e.g., macOS /var -> /private/var).
#[cfg(unix)]
#[rstest]
fn test_remove_at_symbol_via_symlink(mut repo: TestRepo) {
    use std::os::unix::fs::symlink;

    let worktree_path = repo.add_worktree("feature-symlink");

    // Create a symlink pointing to the worktree
    let symlink_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join("symlink-to-feature");
    symlink(&worktree_path, &symlink_path).expect("Failed to create symlink");

    // Verify symlink was created
    assert!(
        symlink_path.is_symlink(),
        "Symlink should exist at {:?}",
        symlink_path
    );

    // Run `wt remove @` from the symlinked path
    // This tests that resolve_worktree("@") properly handles symlinked paths
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["@"],
        Some(&symlink_path)
    ));
}

// ============================================================================
// Pruned Worktree Tests
// ============================================================================

/// When a worktree's directory is deleted externally (e.g., `rm -rf`), the git
/// metadata becomes stale. `wt remove` should prune this stale metadata and
/// proceed with branch deletion, rather than erroring.
///
/// This makes `wt remove` more idempotent - it puts the repository into the
/// correct end state regardless of whether the directory exists.
#[rstest]
fn test_remove_pruned_worktree_directory_missing(mut repo: TestRepo) {
    // Create a worktree
    let worktree_path = repo.add_worktree("feature-pruned");

    // Verify the worktree exists
    assert!(worktree_path.exists(), "Worktree should exist initially");

    // Externally delete the worktree directory (simulating user running `rm -rf`)
    std::fs::remove_dir_all(&worktree_path).expect("Failed to remove worktree directory");
    assert!(
        !worktree_path.exists(),
        "Worktree directory should be deleted"
    );

    // Verify git still thinks the worktree exists (stale metadata)
    let list_output = repo
        .git_command()
        .args(["worktree", "list", "--porcelain"])
        .run()
        .unwrap();
    let list_str = String::from_utf8_lossy(&list_output.stdout);
    assert!(
        list_str.contains("feature-pruned"),
        "Git should still list the stale worktree"
    );

    // `wt remove feature-pruned` should prune the stale metadata and delete the branch
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-pruned"],
        None
    ));

    // Verify the stale worktree metadata is cleaned up
    let list_after = repo
        .git_command()
        .args(["worktree", "list", "--porcelain"])
        .run()
        .unwrap();
    let list_after_str = String::from_utf8_lossy(&list_after.stdout);
    assert!(
        !list_after_str.contains("feature-pruned"),
        "Stale worktree should be pruned"
    );

    // Verify the branch is deleted
    let branch_exists = repo
        .git_command()
        .args(["branch", "--list", "feature-pruned"])
        .run()
        .unwrap();
    assert!(
        String::from_utf8_lossy(&branch_exists.stdout)
            .trim()
            .is_empty(),
        "Branch should be deleted"
    );
}

/// Test pruning with --no-delete-branch: should prune metadata but keep the branch
#[rstest]
fn test_remove_pruned_worktree_keep_branch(mut repo: TestRepo) {
    // Create a worktree
    let worktree_path = repo.add_worktree("feature-pruned-keep");

    // Delete the worktree directory externally
    std::fs::remove_dir_all(&worktree_path).expect("Failed to remove worktree directory");

    // Remove with --no-delete-branch
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["--no-delete-branch", "feature-pruned-keep"],
        None
    ));

    // Verify the branch still exists
    let branch_exists = repo
        .git_command()
        .args(["branch", "--list", "feature-pruned-keep"])
        .run()
        .unwrap();
    assert!(
        !String::from_utf8_lossy(&branch_exists.stdout)
            .trim()
            .is_empty(),
        "Branch should still exist"
    );
}

/// Test pruning a stale worktree with an unmerged branch: should prune metadata,
/// retain branch, and show hint to force-delete
#[rstest]
fn test_remove_pruned_worktree_unmerged_branch(mut repo: TestRepo) {
    // Create a worktree with a real change (unmerged with main)
    let worktree_path = repo.add_worktree("feature-pruned-unmerged");
    std::fs::write(worktree_path.join("unmerged.txt"), "unmerged work\n").unwrap();
    repo.git_command()
        .args(["add", "unmerged.txt"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "unmerged work"])
        .current_dir(&worktree_path)
        .run()
        .unwrap();

    // Delete the worktree directory externally (simulating user running `rm -rf`)
    std::fs::remove_dir_all(&worktree_path).expect("Failed to remove worktree directory");

    // Remove: should prune stale metadata but retain the unmerged branch
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "remove",
        &["feature-pruned-unmerged"],
        None
    ));

    // Verify the branch still exists (retained because unmerged)
    let branch_exists = repo
        .git_command()
        .args(["branch", "--list", "feature-pruned-unmerged"])
        .run()
        .unwrap();
    assert!(
        !String::from_utf8_lossy(&branch_exists.stdout)
            .trim()
            .is_empty(),
        "Unmerged branch should be retained"
    );
}

// ============================================================================
// Instant Removal Tests (move-then-delete optimization)
// ============================================================================

/// Background removal should make the original worktree path unavailable immediately.
///
/// This tests the move-then-delete optimization: the worktree directory is renamed
/// to a staging path synchronously, so the original path is gone before wt returns.
/// The actual deletion (rm -rf) happens in the background.
#[rstest]
fn test_remove_background_path_gone_immediately(mut repo: TestRepo) {
    // Create a worktree
    let worktree_path = repo.add_worktree("feature-instant");

    // Verify the worktree exists
    assert!(worktree_path.exists(), "Worktree should exist initially");

    // Remove in background mode (default) - NOT using snapshot since we need to check state after
    let output = repo
        .wt_command()
        .args(["remove", "feature-instant"])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "wt remove should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // The worktree contents should be gone IMMEDIATELY (moved to .git/wt/trash/).
    // No placeholder created because this is a non-current worktree removal.
    assert!(!worktree_path.exists(), "Worktree should be fully removed");
}

/// Background removal should prune git worktree metadata synchronously.
///
/// After removal, `git worktree list` should NOT show the removed worktree,
/// even before the background rm -rf completes.
#[rstest]
fn test_remove_background_git_metadata_pruned(mut repo: TestRepo) {
    // Create a worktree
    let _worktree_path = repo.add_worktree("feature-prune-test");

    // Verify git knows about the worktree
    let list_before = repo
        .git_command()
        .args(["worktree", "list", "--porcelain"])
        .run()
        .unwrap();
    assert!(
        String::from_utf8_lossy(&list_before.stdout).contains("feature-prune-test"),
        "Git should list the worktree before removal"
    );

    // Remove in background mode
    let output = repo
        .wt_command()
        .args(["remove", "feature-prune-test"])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "wt remove should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Git worktree metadata should be pruned IMMEDIATELY
    let list_after = repo
        .git_command()
        .args(["worktree", "list", "--porcelain"])
        .run()
        .unwrap();
    assert!(
        !String::from_utf8_lossy(&list_after.stdout).contains("feature-prune-test"),
        "Git should NOT list the worktree after removal (metadata should be pruned)"
    );
}

/// Background removal should delete the branch synchronously when it's merged.
///
/// On the fast path (rename-then-prune), the branch is deleted synchronously
/// after pruning git metadata, before the background `rm -rf` runs.
/// This prevents races where the user creates a new worktree with the same
/// branch name before the background process completes.
#[rstest]
fn test_remove_background_deletes_merged_branch(mut repo: TestRepo) {
    // Create a worktree with the branch already merged to main (same commit)
    let _worktree_path = repo.add_worktree("feature-merged");

    // Verify branch exists before removal
    let branches_before = repo
        .git_command()
        .args(["branch", "--list", "feature-merged"])
        .run()
        .unwrap();
    assert!(
        !String::from_utf8_lossy(&branches_before.stdout)
            .trim()
            .is_empty(),
        "Branch should exist before removal"
    );

    // Remove in background mode (default)
    let output = repo
        .wt_command()
        .args(["remove", "feature-merged"])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "wt remove should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Branch should be deleted IMMEDIATELY (synchronously, not in background)
    let branches_after = repo
        .git_command()
        .args(["branch", "--list", "feature-merged"])
        .run()
        .unwrap();
    assert!(
        String::from_utf8_lossy(&branches_after.stdout)
            .trim()
            .is_empty(),
        "Branch should be deleted synchronously after wt remove returns"
    );
}

/// Test that worktree paths containing special characters are handled correctly.
///
/// This tests that the `rm -rf -- <path>` command correctly handles paths
/// that might be misinterpreted as options.
#[rstest]
fn test_remove_worktree_with_special_path_chars(mut repo: TestRepo) {
    // Create a worktree with special characters in the branch name
    // (which becomes part of the path)
    let _worktree_path = repo.add_worktree("feature--double-dash");

    // Verify worktree exists
    let list_before = repo
        .git_command()
        .args(["worktree", "list", "--porcelain"])
        .run()
        .unwrap();
    assert!(
        String::from_utf8_lossy(&list_before.stdout).contains("feature--double-dash"),
        "Worktree should exist before removal"
    );

    // Remove the worktree
    let output = repo
        .wt_command()
        .args(["remove", "feature--double-dash"])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "wt remove should succeed for path with special chars: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Poll for background worktree removal
    crate::common::wait_for("worktree with special chars removed", || {
        let list = repo
            .git_command()
            .args(["worktree", "list", "--porcelain"])
            .run()
            .unwrap();
        !String::from_utf8_lossy(&list.stdout).contains("feature--double-dash")
    });
}

/// Test that background removal falls back to legacy git worktree remove
/// when the instant rename fails.
///
/// This tests the fallback path: when std::fs::rename() fails (e.g., cross-filesystem,
/// permissions, or in this case a blocking file), we fall back to the legacy
/// `git worktree remove` command which handles cleanup properly.
#[rstest]
fn test_remove_background_fallback_on_rename_failure(mut repo: TestRepo) {
    // Create a worktree
    let worktree_path = repo.add_worktree("feature-fallback");

    // Calculate the expected staged path that the rename would use.
    // The path is: <git-common-dir>/wt/trash/<name>-<TEST_EPOCH>
    // Since WT_TEST_EPOCH is set by the test harness, the timestamp is deterministic.
    let git_common_dir = crate::common::resolve_git_common_dir(repo.root_path());
    let trash_dir = git_common_dir.join("wt/trash");
    std::fs::create_dir_all(&trash_dir).unwrap();
    let staged_path = trash_dir.join(format!(
        "{}-{}",
        worktree_path.file_name().unwrap().to_string_lossy(),
        crate::common::TEST_EPOCH
    ));

    // Create a regular file at the staged path to block the rename.
    // On POSIX systems, you cannot rename a directory to an existing file.
    std::fs::write(&staged_path, "blocking file").unwrap();

    // Verify worktree exists before removal
    assert!(
        worktree_path.exists(),
        "Worktree should exist before removal"
    );

    // Remove in background mode - should fall back to legacy removal
    let output = repo
        .wt_command()
        .args(["remove", "feature-fallback"])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "wt remove should succeed even when instant rename fails: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Poll for legacy background removal (includes 1-second sleep before git worktree remove)
    crate::common::wait_for("worktree removed by legacy fallback", || {
        !worktree_path.exists()
    });

    // Poll for branch deletion (happens after worktree removal in background command)
    crate::common::wait_for("branch deleted by legacy fallback", || {
        let branches = repo
            .git_command()
            .args(["branch", "--list", "feature-fallback"])
            .run()
            .unwrap();
        String::from_utf8_lossy(&branches.stdout).trim().is_empty()
    });

    // Clean up the blocking file
    let _ = std::fs::remove_file(&staged_path);
}

/// Stale staging directories from crashed removals are contained in `.git/wt/trash/`.
///
/// If `wt remove` is killed after `fs::rename()` succeeds but before the background
/// `rm -rf` spawns, the staging directory is left behind inside `.git/wt/trash/`.
/// Unlike the old sibling-path approach, these are hidden from the user's workspace.
/// When the same worktree is re-created and removed again, the new staging path uses
/// a fresh timestamp so there is no collision.
#[rstest]
fn test_remove_stale_staging_dir_from_crashed_removal(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-crash");

    // Calculate the deterministic staging path (TEST_EPOCH is fixed in tests)
    let git_common_dir = crate::common::resolve_git_common_dir(repo.root_path());
    let trash_dir = git_common_dir.join("wt/trash");
    std::fs::create_dir_all(&trash_dir).unwrap();
    let staged_path = trash_dir.join(format!(
        "{}-{}",
        worktree_path.file_name().unwrap().to_string_lossy(),
        crate::common::TEST_EPOCH
    ));

    // Simulate a crashed removal: rename the worktree to the staging path manually,
    // then prune git metadata — but never run the background rm -rf.
    std::fs::rename(&worktree_path, &staged_path).unwrap();
    repo.run_git(&["worktree", "prune"]);

    // Verify the crash state: original path gone, stale staging dir remains in .git/wt/trash/
    assert!(!worktree_path.exists());
    assert!(staged_path.exists());

    // The stale dir is inside .git/ — invisible to the user, unlike the old
    // sibling-path approach that left confusingly-named dirs in the workspace.
    assert!(
        staged_path.starts_with(&git_common_dir),
        "Stale staging dir should be inside .git/"
    );
}

/// `wt remove` sweeps `.git/wt/trash/` entries older than 24 hours.
///
/// Each run of `wt remove` fires a detached `rm -rf` on trash entries whose
/// encoded timestamp is more than a day in the past. This provides eventual
/// cleanup for directories orphaned when a previous background removal was
/// interrupted. Fresh entries (from recent or in-flight removals) are left
/// alone so concurrent removals don't race.
#[rstest]
fn test_remove_sweeps_stale_trash_entries(mut repo: TestRepo) {
    let git_common_dir = crate::common::resolve_git_common_dir(repo.root_path());
    let trash_dir = git_common_dir.join("wt/trash");
    std::fs::create_dir_all(&trash_dir).unwrap();

    // Pre-populate the trash directory with a stale entry (2 days old) and a
    // fresh entry (just created). The stale entry should be swept; the fresh
    // entry should survive.
    let day = 24 * 60 * 60;
    let stale_timestamp = crate::common::TEST_EPOCH - 2 * day;
    let stale_entry = trash_dir.join(format!("orphan-stale-{stale_timestamp}"));
    let fresh_entry = trash_dir.join(format!("orphan-fresh-{}", crate::common::TEST_EPOCH));
    std::fs::create_dir(&stale_entry).unwrap();
    std::fs::write(stale_entry.join("marker"), "leftover").unwrap();
    std::fs::create_dir(&fresh_entry).unwrap();
    std::fs::write(fresh_entry.join("marker"), "recent").unwrap();

    // Create and remove a real worktree to trigger the sweep, which runs after
    // the primary `wt remove` output has been printed.
    let _ = repo.add_worktree("feature-sweep");
    let output = repo
        .wt_command()
        .args(["remove", "feature-sweep"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "wt remove should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // The stale entry is removed by a detached `rm -rf` — poll for absence.
    crate::common::wait_for("stale trash entry swept", || !stale_entry.exists());

    // The fresh entry must survive — only entries older than 24 hours are swept.
    assert!(
        fresh_entry.exists(),
        "fresh trash entry (age 0) must not be swept"
    );
}

/// Tests that foreground removal shows remaining directory entries when
/// `git worktree remove` fails because a directory can't be deleted.
///
/// Uses Unix permissions (non-writable directory) to prevent deletion of
/// a gitignored directory with a non-writable subdirectory. The fast path
/// (rename to trash) handles this gracefully — the entire worktree directory
/// is renamed atomically regardless of internal permissions.
#[rstest]
#[cfg(unix)]
fn test_remove_foreground_succeeds_with_stuck_directory(mut repo: TestRepo) {
    use std::fs::{self, Permissions};
    use std::os::unix::fs::PermissionsExt;

    let worktree_path = repo.add_worktree("feature-stuck");

    // Add .gitignore so the stuck directory passes the clean check
    fs::write(worktree_path.join(".gitignore"), "stuck/\n").unwrap();
    repo.run_git_in(&worktree_path, &["add", ".gitignore"]);
    repo.run_git_in(&worktree_path, &["commit", "-m", "Add gitignore"]);

    // Create gitignored directory with a non-writable file inside
    let stuck_dir = worktree_path.join("stuck");
    fs::create_dir_all(&stuck_dir).unwrap();
    fs::write(stuck_dir.join("file.txt"), "content").unwrap();
    fs::set_permissions(&stuck_dir, Permissions::from_mode(0o555)).unwrap();

    // Check if permissions actually restrict us (skip if running as root)
    let test_file = stuck_dir.join("test_write");
    if fs::write(&test_file, "test").is_ok() {
        let _ = fs::remove_file(&test_file);
        fs::set_permissions(&stuck_dir, Permissions::from_mode(0o755)).unwrap();
        eprintln!("Skipping - running with elevated privileges");
        return;
    }

    let output = repo
        .wt_command()
        .args(["remove", "--foreground", "feature-stuck"])
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Restore permissions in trash dir so TempDir cleanup works
    let git_dir = repo.root_path().join(".git");
    let trash_dir = git_dir.join("wt").join("trash");
    if trash_dir.exists() {
        for entry in fs::read_dir(&trash_dir).unwrap().flatten() {
            restore_dir_permissions(&entry.path());
        }
    }

    assert!(
        output.status.success(),
        "Remove should succeed via fast path, got: {stderr}"
    );
    assert!(!worktree_path.exists(), "Worktree directory should be gone");
}

/// Same as above but for the detached HEAD code path.
#[rstest]
#[cfg(unix)]
fn test_remove_foreground_succeeds_with_stuck_directory_detached(mut repo: TestRepo) {
    use std::fs::{self, Permissions};
    use std::os::unix::fs::PermissionsExt;

    let worktree_path = repo.add_worktree("feature-stuck-detached");

    // Commit .gitignore, then detach HEAD
    fs::write(worktree_path.join(".gitignore"), "stuck/\n").unwrap();
    repo.run_git_in(&worktree_path, &["add", ".gitignore"]);
    repo.run_git_in(&worktree_path, &["commit", "-m", "Add gitignore"]);
    repo.detach_head_in_worktree("feature-stuck-detached");

    // Create gitignored directory with a non-writable file inside
    let stuck_dir = worktree_path.join("stuck");
    fs::create_dir_all(&stuck_dir).unwrap();
    fs::write(stuck_dir.join("file.txt"), "content").unwrap();
    fs::set_permissions(&stuck_dir, Permissions::from_mode(0o555)).unwrap();

    // Skip if running as root
    let test_file = stuck_dir.join("test_write");
    if fs::write(&test_file, "test").is_ok() {
        let _ = fs::remove_file(&test_file);
        fs::set_permissions(&stuck_dir, Permissions::from_mode(0o755)).unwrap();
        eprintln!("Skipping - running with elevated privileges");
        return;
    }

    let output = repo
        .wt_command()
        .args(["remove", "--foreground"])
        .current_dir(&worktree_path)
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Restore permissions in trash dir so TempDir cleanup works
    let git_dir = repo.root_path().join(".git");
    let trash_dir = git_dir.join("wt").join("trash");
    if trash_dir.exists() {
        for entry in fs::read_dir(&trash_dir).unwrap().flatten() {
            restore_dir_permissions(&entry.path());
        }
    }

    assert!(
        output.status.success(),
        "Remove should succeed via fast path, got: {stderr}"
    );
    assert!(!worktree_path.exists(), "Worktree directory should be gone");
}

/// Worktrees with initialized git submodules should be removable.
///
/// Git refuses `git worktree remove` when submodules are initialized,
/// requiring `--force`. This test verifies that `wt remove --foreground`
/// handles this automatically (retries with `--force`).
///
/// Regression test for <https://github.com/max-sixty/worktrunk/issues/1194>.
#[rstest]
fn test_remove_foreground_with_submodules(mut repo: TestRepo) {
    // Create a local repo to use as a submodule source
    let sub_source = repo.root_path().parent().unwrap().join("sub-source");
    std::fs::create_dir_all(&sub_source).unwrap();
    repo.run_git_in(&sub_source, &["init"]);
    std::fs::write(sub_source.join("sub.txt"), "submodule content").unwrap();
    repo.run_git_in(&sub_source, &["add", "sub.txt"]);
    repo.run_git_in(&sub_source, &["commit", "-m", "sub init"]);

    // Add submodule to the main repo (requires protocol.file.allow=always)
    let output = repo
        .git_command()
        .args([
            "-c",
            "protocol.file.allow=always",
            "submodule",
            "add",
            sub_source.to_str().unwrap(),
            "submod",
        ])
        .run()
        .unwrap();
    assert!(
        output.status.success(),
        "Failed to add submodule: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    repo.run_git(&["commit", "-m", "add submodule"]);

    // Create a worktree and initialize submodules in it
    let worktree_path = repo.add_worktree("feature-submod");
    let output = repo
        .git_command()
        .current_dir(&worktree_path)
        .args([
            "-c",
            "protocol.file.allow=always",
            "submodule",
            "update",
            "--init",
        ])
        .run()
        .unwrap();
    assert!(
        output.status.success(),
        "Failed to init submodule: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Verify the submodule is actually initialized
    assert!(
        worktree_path.join("submod").join("sub.txt").exists(),
        "Submodule should be initialized"
    );

    // Remove the worktree in foreground mode — should succeed despite submodules
    let output = repo
        .wt_command()
        .args(["remove", "--foreground", "feature-submod"])
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "Remove should succeed with submodules, got: {stderr}"
    );
    assert!(
        !worktree_path.exists(),
        "Worktree directory should be removed"
    );
}

/// Restore write permissions recursively so TempDir cleanup succeeds.
#[cfg(unix)]
fn restore_dir_permissions(dir: &std::path::Path) {
    use std::fs::{self, Permissions};
    use std::os::unix::fs::PermissionsExt;

    let _ = fs::set_permissions(dir, Permissions::from_mode(0o755));
    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            if entry.file_type().is_ok_and(|t| t.is_dir()) {
                restore_dir_permissions(&entry.path());
            }
        }
    }
}

// ============================================================================
// --format=json
// ============================================================================

#[rstest]
fn test_remove_json(mut repo: TestRepo) {
    repo.commit("initial");
    repo.add_worktree("feature");

    let output = repo
        .wt_command()
        .args([
            "remove",
            "feature",
            "--format=json",
            "--yes",
            "--foreground",
        ])
        .output()
        .unwrap();
    assert!(output.status.success());

    let mut settings = insta::Settings::clone_current();
    settings.add_filter(r#""path": "[^"]*""#, r#""path": "<PATH>""#);
    settings.bind(|| {
        assert_snapshot!(String::from_utf8_lossy(&output.stdout));
    });
}

#[cfg(not(target_os = "windows"))] // foreground removal with cwd inside the worktree hits directory locking
#[rstest]
fn test_remove_json_current(mut repo: TestRepo) {
    repo.commit("initial");
    let feature_wt = repo.add_worktree("feature");

    let output = repo
        .wt_command()
        .args(["remove", "--format=json", "--yes", "--foreground"])
        .current_dir(&feature_wt)
        .output()
        .unwrap();
    assert!(output.status.success());

    let mut settings = insta::Settings::clone_current();
    settings.add_filter(r#""path": "[^"]*""#, r#""path": "<PATH>""#);
    settings.bind(|| {
        assert_snapshot!(String::from_utf8_lossy(&output.stdout));
    });
}

#[rstest]
fn test_remove_json_branch_only(repo: TestRepo) {
    repo.commit("initial");
    // Create a branch without a worktree (already merged into main)
    repo.git_command()
        .args(["branch", "orphan-branch"])
        .run()
        .unwrap();

    let output = repo
        .wt_command()
        .args([
            "remove",
            "orphan-branch",
            "--format=json",
            "--yes",
            "--foreground",
        ])
        .output()
        .unwrap();
    assert!(output.status.success());

    assert_snapshot!(String::from_utf8_lossy(&output.stdout));
}

#[cfg(not(target_os = "windows"))]
#[rstest]
fn test_remove_json_multi_with_branch_only(mut repo: TestRepo) {
    repo.commit("initial");
    repo.add_worktree("wt-feature");
    // Create a branch without a worktree
    repo.git_command()
        .args(["branch", "orphan-branch"])
        .run()
        .unwrap();

    let output = repo
        .wt_command()
        .args([
            "remove",
            "wt-feature",
            "orphan-branch",
            "--format=json",
            "--yes",
            "--foreground",
        ])
        .output()
        .unwrap();
    assert!(output.status.success());

    let mut settings = insta::Settings::clone_current();
    settings.add_filter(r#""path": "[^"]*""#, r#""path": "<PATH>""#);
    settings.bind(|| {
        assert_snapshot!(String::from_utf8_lossy(&output.stdout));
    });
}

/// Multi-remove with current worktree in the target list exercises the
/// `plans.current` JSON path (deferred removal, last in output).
#[cfg(not(target_os = "windows"))]
#[rstest]
fn test_remove_json_multi_with_current(mut repo: TestRepo) {
    repo.commit("initial");
    repo.add_worktree("other-feature");
    let current_wt = repo.add_worktree("current-feature");

    let output = repo
        .wt_command()
        .args([
            "remove",
            "other-feature",
            "current-feature",
            "--format=json",
            "--yes",
            "--foreground",
        ])
        .current_dir(&current_wt)
        .output()
        .unwrap();
    assert!(output.status.success());

    let json: serde_json::Value =
        serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
    let items = json.as_array().unwrap();
    assert_eq!(items.len(), 2);

    // other-feature removed first (plans.others), current-feature last (plans.current)
    assert_eq!(items[0]["branch"], "other-feature");
    assert_eq!(items[0]["kind"], "worktree");
    assert_eq!(items[1]["branch"], "current-feature");
    assert_eq!(items[1]["kind"], "worktree");
}