worktrunk 0.42.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
use crate::common::{
    TestRepo, make_snapshot_cmd, merge_scenario,
    mock_commands::{create_mock_cargo, create_mock_llm_auth},
    repo, repo_with_alternate_primary, repo_with_feature_worktree, repo_with_main_worktree,
    repo_with_multi_commit_feature, setup_snapshot_settings, wait_for_file, wait_for_file_content,
};
use insta::assert_snapshot;
use insta_cmd::assert_cmd_snapshot;
use path_slash::PathExt as _;
use rstest::rstest;
use std::fs;
use std::path::{Path, PathBuf};

/// Create a PATH with the given mock bin directory prepended, preserving variable case.
///
/// Returns (variable_name, value) where variable_name preserves the case found
/// in the environment (important for Windows where env vars are case-insensitive
/// but Rust stores them case-sensitively - using "PATH" when the system has "Path"
/// creates a duplicate).
fn make_path_with_mock_bin(bin_dir: &Path) -> (String, String) {
    // Find the actual PATH variable name to avoid creating a duplicate with different case
    let (path_var_name, current_path) = std::env::vars_os()
        .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
        .map(|(k, v)| (k.to_string_lossy().into_owned(), Some(v)))
        .unwrap_or(("PATH".to_string(), None));

    let mut paths: Vec<PathBuf> = current_path
        .as_deref()
        .map(|p| std::env::split_paths(p).collect())
        .unwrap_or_default();
    paths.insert(0, bin_dir.to_path_buf());
    let new_path = std::env::join_paths(&paths)
        .unwrap()
        .to_string_lossy()
        .into_owned();

    (path_var_name, new_path)
}

fn snapshot_merge_with_env(
    test_name: &str,
    repo: &TestRepo,
    args: &[&str],
    cwd: Option<&Path>,
    env_vars: &[(&str, &str)],
) {
    let settings = setup_snapshot_settings(repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(repo, "merge", args, cwd);
        for (key, value) in env_vars {
            cmd.env(key, value);
        }
        assert_cmd_snapshot!(test_name, cmd);
    });
}

#[rstest]
fn test_merge_fast_forward(merge_scenario: (TestRepo, PathBuf)) {
    let (repo, feature_wt) = merge_scenario;

    // Merge feature into main
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

///
/// 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_merge_as_git_subcommand(merge_scenario: (TestRepo, PathBuf)) {
    let (repo, feature_wt) = merge_scenario;

    // Merge with GIT_EXEC_PATH set (simulating `git wt merge ...`)
    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(&repo, "merge", &["main"], Some(&feature_wt));
        cmd.env("GIT_EXEC_PATH", "/usr/lib/git-core");
        cmd
    });
}

#[rstest]
fn test_merge_primary_not_on_default_with_default_worktree(
    mut repo_with_alternate_primary: TestRepo,
) {
    let repo = &mut repo_with_alternate_primary;
    let feature_wt = repo.add_feature();

    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_with_no_remove_flag(merge_scenario: (TestRepo, PathBuf)) {
    let (repo, feature_wt) = merge_scenario;

    // Merge with --no-remove flag (should not finish worktree)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--no-remove"],
        Some(&feature_wt)
    ));
}

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

/// When `worktrunk.default-branch` points at a branch that no longer
/// resolves locally (user deleted it externally), `wt merge` without
/// `--target` surfaces `StaleDefaultBranch` with cache-reset hints rather
/// than the generic `BranchNotFound` "create it?" path.
#[rstest]
fn test_merge_with_stale_default_branch_cache(mut repo: TestRepo) {
    // Configure a cached default branch that doesn't exist locally
    repo.run_git(&["config", "worktrunk.default-branch", "nonexistent"]);
    let feature_wt = repo.add_feature();
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "merge", &[], Some(&feature_wt)));
}

#[rstest]
fn test_merge_from_primary_worktree_to_other_branch(mut repo: TestRepo) {
    // Create a feature branch with a commit, then merge from main worktree into it.
    // Main worktree can't be removed, so should show "primary worktree" preservation.
    let feature_wt = repo.add_feature();
    drop(feature_wt); // we don't need the path; we'll run from main
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "merge", &["feature"], None));
}

#[rstest]
fn test_merge_dirty_working_tree(mut repo: TestRepo) {
    // Create a feature worktree with uncommitted changes
    let feature_wt = repo.add_worktree("feature");
    std::fs::write(feature_wt.join("dirty.txt"), "uncommitted content").unwrap();

    // Try to merge (should fail due to dirty working tree)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_not_fast_forward(mut repo: TestRepo) {
    // Create commits in both branches
    // Add commit to main (repo root)
    std::fs::write(repo.root_path().join("main.txt"), "main content").unwrap();

    repo.run_git(&["add", "main.txt"]);
    repo.run_git(&["commit", "-m", "Add main file"]);

    // Create a feature worktree branching from before the main commit
    let feature_wt = repo.add_feature();

    // Try to merge (should fail or require actual merge)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

/// The --no-commit flag skips the rebase step, so the push fails with not-fast-forward error.
/// The hint should say "Run 'wt merge' again" (not "Use 'wt merge'").
#[rstest]
fn test_merge_no_commit_not_fast_forward(repo: TestRepo) {
    // Get the initial commit SHA to create feature branch from there
    let initial_sha = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["rev-parse", "HEAD"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    // Add commit to main (this advances main beyond the initial commit)
    std::fs::write(repo.root_path().join("main.txt"), "main content").unwrap();
    repo.run_git(&["add", "main.txt"]);
    repo.run_git(&["commit", "-m", "Add main file"]);

    // Create feature worktree from the INITIAL commit (before main advanced)
    let feature_path = repo.root_path().parent().unwrap().join("feature");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "feature",
        feature_path.to_str().unwrap(),
        &initial_sha,
    ]);

    // Add a commit on feature branch
    std::fs::write(feature_path.join("feature.txt"), "feature content").unwrap();
    repo.run_git_in(&feature_path, &["add", "feature.txt"]);
    repo.run_git_in(&feature_path, &["commit", "-m", "Add feature file"]);

    // Try to merge with --no-commit --no-remove (skips rebase, so push fails with not-fast-forward)
    // Main has "Add main file" commit that feature doesn't have as ancestor
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--no-commit", "--no-remove"],
        Some(&feature_path)
    ));
}

#[rstest]
fn test_merge_rebase_conflict(repo: TestRepo) {
    // Create a shared file
    std::fs::write(repo.root_path().join("shared.txt"), "initial content\n").unwrap();
    repo.run_git(&["add", "shared.txt"]);
    repo.commit("Add shared file");

    // Modify shared.txt in main branch (from the base commit)
    std::fs::write(repo.root_path().join("shared.txt"), "main version\n").unwrap();
    repo.run_git(&["add", "shared.txt"]);
    repo.run_git(&["commit", "-m", "Update shared.txt in main"]);

    // Create a feature worktree branching from before the main commit
    // We need to create it from the original commit, not current main
    let base_commit = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["rev-parse", "HEAD~1"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    let feature_wt = repo.root_path().parent().unwrap().join("repo.feature");
    repo.run_git(&[
        "worktree",
        "add",
        feature_wt.to_str().unwrap(),
        "-b",
        "feature",
        &base_commit,
    ]);

    // Modify the same file with conflicting content
    std::fs::write(feature_wt.join("shared.txt"), "feature version\n").unwrap();
    repo.run_git_in(&feature_wt, &["add", "shared.txt"]);
    repo.run_git_in(
        &feature_wt,
        &["commit", "-m", "Update shared.txt in feature"],
    );

    // Try to merge - should fail with rebase conflict
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_to_default_branch(merge_scenario: (TestRepo, PathBuf)) {
    let (repo, feature_wt) = merge_scenario;

    // Merge without specifying target (should use default branch)
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "merge", &[], Some(&feature_wt)));
}

#[rstest]
fn test_merge_with_caret_symbol(merge_scenario: (TestRepo, PathBuf)) {
    let (repo, feature_wt) = merge_scenario;

    // Merge using ^ symbol (should resolve to default branch)
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "merge", &["^"], Some(&feature_wt)));
}

#[rstest]
fn test_merge_error_detached_head(repo: TestRepo) {
    // Detach HEAD in the repo
    repo.detach_head();

    // Try to merge (should fail - detached HEAD)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main"],
        Some(repo.root_path())
    ));
}

#[rstest]
fn test_merge_squash_deterministic(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    // Create a feature worktree and make multiple commits
    let feature_wt = repo.add_worktree("feature");
    repo.commit_in_worktree(&feature_wt, "file1.txt", "content 1", "feat: add file 1");
    repo.commit_in_worktree(&feature_wt, "file2.txt", "content 2", "fix: update logic");
    repo.commit_in_worktree(&feature_wt, "file3.txt", "content 3", "docs: update readme");

    // Merge (squashing is now the default - no LLM configured, should use deterministic message)
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_squash_with_llm(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    // Create a feature worktree and make multiple commits
    let feature_wt = repo.add_worktree("feature");
    repo.commit_in_worktree(
        &feature_wt,
        "auth.txt",
        "auth module",
        "feat: add authentication",
    );
    repo.commit_in_worktree(
        &feature_wt,
        "auth.txt",
        "auth module updated",
        "fix: handle edge case",
    );

    // Configure mock LLM command via config file
    // Use sh -c to consume stdin and return a fixed message
    let worktrunk_config = r#"
[commit.generation]
command = "cat >/dev/null && echo 'feat: implement user authentication system'"
"#;
    fs::write(repo.test_config_path(), worktrunk_config).unwrap();

    // (squashing is now the default, no need for --squash flag)
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_squash_llm_command_not_found(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    // Create a feature worktree and make multiple commits
    let feature_wt = repo.add_worktree("feature");
    repo.commit_in_worktree(&feature_wt, "file1.txt", "content 1", "feat: new feature");
    repo.commit_in_worktree(&feature_wt, "file2.txt", "content 2", "fix: bug fix");

    // Configure LLM command that doesn't exist - should error
    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(repo, "merge", &["main"], Some(&feature_wt));
        cmd.env(
            "WORKTRUNK_COMMIT__GENERATION__COMMAND",
            "nonexistent-llm-command",
        );
        cmd
    });
}

#[rstest]
fn test_merge_squash_llm_error(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    // Test that LLM command errors show proper gutter formatting with full command

    // Create a feature worktree and make commits
    let feature_wt = repo.add_worktree("feature");
    repo.commit_in_worktree(&feature_wt, "file1.txt", "content 1", "feat: new feature");
    repo.commit_in_worktree(&feature_wt, "file2.txt", "content 2", "fix: bug fix");

    // Configure LLM command via config file with command that will fail
    // This tests that:
    // 1. The full command is shown in the error header
    // 2. The error output appears in a gutter
    // Note: We consume stdin first to avoid race condition where stdin write fails
    // before stderr is captured (broken pipe if process exits before reading stdin)
    let worktrunk_config = r#"
[commit.generation]
command = "cat > /dev/null; echo 'Error: connection refused' >&2 && exit 1"
"#;
    fs::write(repo.test_config_path(), worktrunk_config).unwrap();

    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_squash_single_commit(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    // Create a feature worktree with only one commit
    let feature_wt =
        repo.add_worktree_with_commit("feature", "file1.txt", "content", "feat: single commit");

    // Merge (squashing is default) - should skip squashing since there's only one commit
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_no_squash(repo_with_multi_commit_feature: TestRepo) {
    let repo = &repo_with_multi_commit_feature;
    let feature_wt = &repo.worktrees["feature"];

    // Merge with --no-squash - should NOT squash the commits
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main", "--no-squash"],
        Some(feature_wt)
    ));
}

#[rstest]
fn test_merge_squash_empty_changes(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    // Create a feature worktree with commits that result in no net changes
    let feature_wt = repo.add_worktree("feature");

    // Get the initial content of file.txt (created by the initial commit)
    let file_path = feature_wt.join("file.txt");
    let initial_content = std::fs::read_to_string(&file_path).unwrap();

    // Commit 1: Modify file.txt
    repo.commit_in_worktree(&feature_wt, "file.txt", "change1", "Change 1");

    // Commit 2: Modify file.txt again
    repo.commit_in_worktree(&feature_wt, "file.txt", "change2", "Change 2");

    // Commit 3: Revert to original content
    repo.commit_in_worktree(
        &feature_wt,
        "file.txt",
        &initial_content,
        "Revert to initial",
    );

    // Merge (squashing is default) - should succeed even when commits result in no net changes
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_auto_commit_deterministic(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    // Create a feature worktree with a commit
    let feature_wt = repo.add_worktree_with_commit(
        "feature",
        "feature.txt",
        "initial content",
        "feat: initial feature",
    );

    // Now add uncommitted tracked changes
    std::fs::write(feature_wt.join("feature.txt"), "modified content").unwrap();

    // Merge - should auto-commit with deterministic message (no LLM configured)
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_auto_commit_with_llm(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    // Create a feature worktree with a commit
    let feature_wt = repo.add_worktree_with_commit(
        "feature",
        "auth.txt",
        "initial auth",
        "feat: add authentication",
    );

    // Now add uncommitted tracked changes
    std::fs::write(feature_wt.join("auth.txt"), "improved auth with validation").unwrap();

    // Configure mock LLM command via config file
    // Use sh -c to consume stdin and return a fixed message (must consume stdin for cross-platform compatibility)
    let worktrunk_config = r#"
[commit.generation]
command = "cat >/dev/null && echo 'fix: improve auth validation logic'"
"#;
    fs::write(repo.test_config_path(), worktrunk_config).unwrap();

    // Merge with LLM configured - should auto-commit with LLM commit message
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_auto_commit_and_squash(repo_with_multi_commit_feature: TestRepo) {
    let repo = &repo_with_multi_commit_feature;
    let feature_wt = &repo.worktrees["feature"];

    // Add uncommitted tracked changes
    std::fs::write(feature_wt.join("file1.txt"), "updated content 1").unwrap();

    // Configure mock LLM command via config file
    // Use sh -c to consume stdin and return a fixed message (must consume stdin for cross-platform compatibility)
    let worktrunk_config = r#"
[commit.generation]
command = "cat >/dev/null && echo 'fix: update file 1 content'"
"#;
    fs::write(repo.test_config_path(), worktrunk_config).unwrap();

    // Merge (squashing is default) - should stage uncommitted changes, then squash all commits including the staged changes
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main"],
        Some(feature_wt)
    ));
}

#[rstest]
fn test_merge_with_untracked_files(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    // Create a feature worktree with one commit
    let feature_wt =
        repo.add_worktree_with_commit("feature", "file1.txt", "content 1", "feat: add file 1");

    // Add untracked files
    std::fs::write(feature_wt.join("untracked1.txt"), "untracked content 1").unwrap();
    std::fs::write(feature_wt.join("untracked2.txt"), "untracked content 2").unwrap();

    // Merge - should show warning about untracked files
    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(repo, "merge", &["main"], Some(&feature_wt));
        cmd.env(
            "WORKTRUNK_COMMIT__GENERATION__COMMAND",
            "cat >/dev/null && echo 'fix: commit changes'",
        );
        cmd
    });
}

#[rstest]
fn test_merge_pre_merge_command_success(mut repo: TestRepo) {
    // Create project config with pre-merge command
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(config_dir.join("wt.toml"), r#"pre-merge = "exit 0""#).unwrap();

    repo.commit("Add config");

    let feature_wt = repo.add_feature();

    // Merge with --yes to skip approval prompts
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--yes"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_pre_merge_command_failure(mut repo: TestRepo) {
    // Create project config with failing pre-merge command
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(config_dir.join("wt.toml"), r#"pre-merge = "exit 1""#).unwrap();

    repo.commit("Add config");

    let feature_wt = repo.add_feature();

    // Merge with --yes - pre-merge command should fail and block merge
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--yes"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_pre_merge_command_no_hooks(mut repo: TestRepo) {
    // Create project config with failing pre-merge command
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(config_dir.join("wt.toml"), r#"pre-merge = "exit 1""#).unwrap();

    repo.commit("Add config");

    let feature_wt = repo.add_feature();

    // Merge with --no-hooks - should skip pre-merge commands and succeed
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--no-hooks"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_pre_merge_command_named(mut repo: TestRepo) {
    // Create project config with named pre-merge commands
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(
        config_dir.join("wt.toml"),
        r#"
pre-merge = [
    {format = "exit 0"},
    {lint = "exit 0"},
    {test = "exit 0"},
]
"#,
    )
    .unwrap();

    repo.commit("Add config");

    let feature_wt = repo.add_feature();

    // Merge with --yes - all pre-merge commands should pass
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--yes"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_post_merge_command_success(mut repo: TestRepo) {
    // Create project config with post-merge command that writes a marker file
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(
        config_dir.join("wt.toml"),
        r#"post-merge = "echo 'merged {{ branch }} to {{ target }}' > post-merge-ran.txt""#,
    )
    .unwrap();

    repo.commit("Add config");

    let feature_wt = repo.add_feature();

    // Merge with --yes
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--yes"],
        Some(&feature_wt)
    ));

    // Verify the command ran in the main worktree (not the feature worktree).
    // post-merge runs in the background, so poll for the file.
    let marker_file = repo.root_path().join("post-merge-ran.txt");
    wait_for_file_content(&marker_file);
    let content = fs::read_to_string(&marker_file).unwrap();
    assert!(
        content.contains("merged feature to main"),
        "Marker file should contain correct branch and target: {}",
        content
    );
}

#[rstest]
fn test_merge_post_merge_command_skipped_with_no_hooks(mut repo: TestRepo) {
    // Create project config with post-merge command that writes a marker file
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(
        config_dir.join("wt.toml"),
        r#"post-merge = "echo 'merged {{ branch }} to {{ target }}' > post-merge-ran.txt""#,
    )
    .unwrap();

    repo.commit("Add config");

    let feature_wt = repo.add_feature();

    // Merge with --no-hooks - hook should be skipped entirely
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--yes", "--no-hooks"],
        Some(&feature_wt)
    ));

    // Verify the command did not run in the main worktree
    let marker_file = repo.root_path().join("post-merge-ran.txt");
    assert!(
        !marker_file.exists(),
        "Post-merge command should not run when --no-hooks is set"
    );
}

#[rstest]
fn test_merge_no_verify_deprecated_still_works(mut repo: TestRepo) {
    let feature_wt = repo.add_feature();

    // --no-verify should still work but emit a deprecation warning
    let output = repo
        .wt_command()
        .args(["merge", "main", "--yes", "--no-verify"])
        .current_dir(&feature_wt)
        .output()
        .unwrap();
    assert!(output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("--no-verify is deprecated"),
        "Expected deprecation warning in stderr: {stderr}"
    );
    assert!(
        stderr.contains("--no-hooks"),
        "Expected --no-hooks suggestion in stderr: {stderr}"
    );
}

#[rstest]
fn test_merge_post_merge_command_failure(mut repo: TestRepo) {
    // Create project config with failing post-merge command
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(config_dir.join("wt.toml"), r#"post-merge = "exit 1""#).unwrap();

    repo.commit("Add config");

    let feature_wt = repo.add_feature();

    // Merge with --yes - post-merge command should fail but merge should complete.
    // Set PWD to repo root so CWD recovery consistently finds the test repo
    // (without this, $PWD is inherited from the test runner and recovery may
    // find a different repo in CI).
    let mut cmd = make_snapshot_cmd(&repo, "merge", &["main", "--yes"], Some(&feature_wt));
    cmd.env("PWD", repo.root_path());
    assert_cmd_snapshot!(cmd);
}

/// When the CWD is removed but the default branch can't be resolved,
/// the hint should suggest `wt list` instead of `wt switch ^`.
#[rstest]
fn test_merge_cwd_removed_hint_fallback_to_list(mut repo: TestRepo) {
    // Create project config with failing post-merge command
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(config_dir.join("wt.toml"), r#"post-merge = "exit 1""#).unwrap();

    repo.commit("Add config");

    // Set default branch to a nonexistent branch so `wt switch ^` won't resolve
    repo.run_git(&["config", "worktrunk.default-branch", "nonexistent"]);

    let feature_wt = repo.add_feature();

    // Set PWD to repo root so recovery finds the test repo after CWD deletion.
    // (Without this, $PWD is inherited from the test runner and recovery finds
    // the dev repo instead.)
    let mut cmd = make_snapshot_cmd(&repo, "merge", &["main", "--yes"], Some(&feature_wt));
    cmd.env("PWD", repo.root_path());
    assert_cmd_snapshot!(cmd);
}

/// When the CWD is removed and recovery can't find any repo,
/// the hint should show just the message with no command suggestion.
///
/// Windows-only skip: on Windows, `current_dir()` succeeds even after
/// directory deletion (process handle keeps it alive), so `Repository::current()`
/// works and the hint correctly suggests `wt switch ^` instead.
#[cfg(not(target_os = "windows"))]
#[rstest]
fn test_merge_cwd_removed_hint_no_recovery(mut repo: TestRepo) {
    // Create project config with failing post-merge command
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(config_dir.join("wt.toml"), r#"post-merge = "exit 1""#).unwrap();

    repo.commit("Add config");

    let feature_wt = repo.add_feature();

    // Set PWD to the feature worktree. After merge removes it, recovery walks up
    // from the deleted path but can't associate it with the repo (worktree was
    // properly cleaned up), so recovery fails.
    let mut cmd = make_snapshot_cmd(&repo, "merge", &["main", "--yes"], Some(&feature_wt));
    cmd.env("PWD", &feature_wt);
    assert_cmd_snapshot!(cmd);
}

#[rstest]
fn test_merge_post_merge_command_named(mut repo: TestRepo) {
    // Create project config with named post-merge commands
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(
        config_dir.join("wt.toml"),
        r#"
[post-merge]
notify = "echo 'Merge to {{ target }} complete' > notify.txt"
deploy = "echo 'Deploying branch {{ branch }}' > deploy.txt"
"#,
    )
    .unwrap();

    repo.commit("Add config");

    let feature_wt = repo.add_feature();

    // Merge with --yes
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--yes"],
        Some(&feature_wt)
    ));

    // Verify both commands ran (poll for background pipeline runner completion)
    let notify_file = repo.root_path().join("notify.txt");
    let deploy_file = repo.root_path().join("deploy.txt");
    wait_for_file(&notify_file);
    wait_for_file(&deploy_file);
}

#[rstest]
fn test_merge_post_merge_runs_with_nothing_to_merge(mut repo: TestRepo) {
    // Verify post-merge hooks run even when there's nothing to merge

    // Create project config with post-merge command
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(
        config_dir.join("wt.toml"),
        r#"post-merge = "echo 'post-merge ran' > post-merge-ran.txt""#,
    )
    .unwrap();

    repo.commit("Add config");

    // Create a worktree for main (destination for post-merge commands)

    // Create a feature worktree with NO commits (already up-to-date with main)
    let feature_wt = repo.add_worktree("feature");

    // Merge with --yes - nothing to merge but post-merge should still run
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--yes"],
        Some(&feature_wt)
    ));

    // Verify the post-merge command ran in the main worktree.
    // post-merge runs in the background, so poll for the file.
    let marker_file = repo.root_path().join("post-merge-ran.txt");
    wait_for_file(&marker_file);
}

#[rstest]
fn test_merge_post_merge_runs_from_main_branch(repo: TestRepo) {
    // Verify post-merge hooks run when merging from main to main (nothing to do)

    // Create project config with post-merge command
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(
        config_dir.join("wt.toml"),
        r#"post-merge = "echo 'post-merge ran from main' > post-merge-ran.txt""#,
    )
    .unwrap();

    repo.commit("Add config");

    // Run merge from main branch (repo root) - nothing to merge
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "merge", &["--yes"], None));

    // Verify the post-merge command ran.
    // post-merge runs in the background, so poll for the file.
    let marker_file = repo.root_path().join("post-merge-ran.txt");
    wait_for_file(&marker_file);
}

#[rstest]
fn test_merge_pre_commit_command_success(mut repo: TestRepo) {
    // Create project config with pre-commit command
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(
        config_dir.join("wt.toml"),
        r#"pre-commit = "echo 'Pre-commit check passed'""#,
    )
    .unwrap();

    repo.commit("Add config");

    // Create a feature worktree and make a change
    let feature_wt = repo.add_worktree("feature");
    fs::write(feature_wt.join("feature.txt"), "feature content").unwrap();

    // Merge with --yes (changes uncommitted, should trigger pre-commit hook)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--yes"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_pre_commit_command_failure(mut repo: TestRepo) {
    // Create project config with failing pre-commit command
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(config_dir.join("wt.toml"), r#"pre-commit = "exit 1""#).unwrap();

    repo.commit("Add config");

    // Create a feature worktree and make a change
    let feature_wt = repo.add_worktree("feature");
    fs::write(feature_wt.join("feature.txt"), "feature content").unwrap();

    // Merge with --yes - pre-commit command should fail and block merge
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--yes"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_pre_squash_command_success(mut repo: TestRepo) {
    // Create project config with pre-commit command (used for both squash and no-squash)
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(
        config_dir.join("wt.toml"),
        "pre-commit = \"echo 'Pre-commit check passed'\"",
    )
    .unwrap();

    repo.commit("Add config");

    // Create a feature worktree and make commits
    let feature_wt = repo.add_feature();

    // Merge with --yes (squashing is now the default)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--yes"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_pre_squash_command_failure(mut repo: TestRepo) {
    // Create project config with failing pre-commit command (used for both squash and no-squash)
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(config_dir.join("wt.toml"), r#"pre-commit = "exit 1""#).unwrap();

    repo.commit("Add config");

    let feature_wt = repo.add_feature();

    // Merge with --yes (squashing is default) - pre-commit command should fail and block merge
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--yes"],
        Some(&feature_wt)
    ));
}

/// Bug #3: Pre-commit hooks should be collected for approval when squashing,
/// even if the worktree is clean (no uncommitted changes).
///
/// Scenario: Feature worktree has multiple commits to squash, but no dirty files.
/// Without the fix, pre-commit hooks would run during squash without approval.
/// With the fix, pre-commit hooks are collected upfront and approved.
#[rstest]
fn test_merge_pre_commit_collected_for_squash_clean_worktree(
    repo_with_multi_commit_feature: TestRepo,
) {
    let repo = &repo_with_multi_commit_feature;
    let feature_wt = repo.worktrees["feature"].clone();

    // Create project config in the FEATURE worktree (where merge runs)
    // This ensures the config is visible when loading project config
    let config_dir = feature_wt.join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(
        config_dir.join("wt.toml"),
        "pre-commit = \"echo 'Pre-commit from squash'\"",
    )
    .unwrap();
    // Commit the config in the feature worktree
    repo.run_git_in(&feature_wt, &["add", ".config/wt.toml"]);
    repo.run_git_in(&feature_wt, &["commit", "-m", "Add config"]);

    // Feature worktree is CLEAN (no uncommitted changes) but has 3 commits to squash.
    // Pre-commit should be collected and approved before squash runs.
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main", "--yes"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_no_remote(#[from(repo_with_feature_worktree)] repo: TestRepo) {
    // Deliberately NOT calling setup_remote to test the error case
    let feature_wt = repo.worktree_path("feature");

    // Try to merge without specifying target (should fail - no remote to get default branch)
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "merge", &[], Some(feature_wt)));
}

// README EXAMPLE GENERATION TESTS
// These tests are specifically designed to generate realistic output examples for the README.
// The snapshots from these tests are manually copied into README.md to show users what
// worktrunk output looks like in practice.

/// Generate README example: Simple merge workflow with a single commit
/// This demonstrates the basic "What It Does" flow - create worktree, make changes, merge back.
///
/// Output is used in README.md "What It Does" section.
/// Merge output: tests/snapshots/integration__integration_tests__merge__readme_example_simple.snap
/// Switch output: tests/snapshots/integration__integration_tests__merge__readme_example_simple_switch.snap
///
#[rstest]
fn test_readme_example_simple(repo: TestRepo) {
    // Snapshot the switch --create command (runs from bare repo)
    assert_cmd_snapshot!(
        "readme_example_simple_switch",
        make_snapshot_cmd(&repo, "switch", &["--create", "fix-auth"], None)
    );

    // Get the created worktree path and make a commit
    let feature_wt = repo.root_path().parent().unwrap().join("repo.fix-auth");
    let auth_rs = r#"// JWT validation utilities
pub struct JwtClaims {
    pub sub: String,
    pub scope: String,
}

pub fn validate(token: &str) -> bool {
    token.starts_with("Bearer ") && token.split('.').count() == 3
}

pub fn refresh(refresh_token: &str) -> String {
    format!("{}::refreshed", refresh_token)
}
"#;
    std::fs::write(feature_wt.join("auth.rs"), auth_rs).unwrap();

    repo.run_git_in(&feature_wt, &["add", "auth.rs"]);
    repo.run_git_in(&feature_wt, &["commit", "-m", "Implement JWT validation"]);

    // Snapshot the merge command
    assert_cmd_snapshot!(
        "readme_example_simple",
        make_snapshot_cmd(&repo, "merge", &["main"], Some(&feature_wt))
    );
}

/// Generate README example: Complex merge with multiple hooks
/// This demonstrates advanced features - pre-merge hooks (tests, lints), post-merge hooks.
/// Shows the full power of worktrunk's automation capabilities.
///
/// Output is used in README.md "Advanced Features" or "Project Automation" section.
/// Source: tests/snapshots/integration__integration_tests__merge__readme_example_complex.snap
#[rstest]
fn test_readme_example_complex(mut repo: TestRepo) {
    // Create project config with multiple hooks
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();

    // Create mock commands for realistic output (cross-platform)
    let bin_dir = repo.root_path().join(".bin");
    fs::create_dir_all(&bin_dir).unwrap();

    // Create cross-platform mock commands
    create_mock_cargo(&bin_dir);
    create_mock_llm_auth(&bin_dir);

    let config_content = r#"
pre-merge = [
    {"test" = "cargo test"},
    {"lint" = "cargo clippy"},
]

[post-merge]
"install" = "cargo install --path ."
"#;

    fs::write(config_dir.join("wt.toml"), config_content).unwrap();

    // Commit the config and mock cargo
    repo.run_git(&["add", ".config/wt.toml", ".bin"]);
    repo.run_git(&["commit", "-m", "Add project automation config"]);

    // Create a feature worktree and make multiple commits
    let feature_wt = repo.add_worktree("feature-auth");

    // First commit: token refresh
    let commit_one = r#"// Token refresh logic
pub fn refresh(secret: &str, expires_in: u32) -> String {
    format!("{}::{}", secret, expires_in)
}

pub fn needs_rotation(issued_at: u64, ttl: u64, now: u64) -> bool {
    now.saturating_sub(issued_at) > ttl
}
"#;
    std::fs::write(feature_wt.join("auth.rs"), commit_one).unwrap();
    repo.run_git_in(&feature_wt, &["add", "auth.rs"]);
    repo.run_git_in(&feature_wt, &["commit", "-m", "Add token refresh logic"]);

    // Second commit: JWT validation
    let commit_two = r#"// JWT validation
pub fn validate_signature(payload: &str, signature: &str) -> bool {
    !payload.is_empty() && signature.len() > 12
}

pub fn decode_claims(token: &str) -> Option<&str> {
    token.split('.').nth(1)
}
"#;
    std::fs::write(feature_wt.join("jwt.rs"), commit_two).unwrap();
    repo.run_git_in(&feature_wt, &["add", "jwt.rs"]);
    repo.run_git_in(&feature_wt, &["commit", "-m", "Implement JWT validation"]);

    // Third commit: tests
    let commit_three = r#"// Tests
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn refresh_rotates_secret() {
        let token = refresh("token", 30);
        assert!(token.contains("token::30"));
    }

    #[test]
    fn decode_claims_returns_payload() {
        let token = "header.payload.signature";
        assert_eq!(decode_claims(token), Some("payload"));
    }
}
"#;
    std::fs::write(feature_wt.join("auth_test.rs"), commit_three).unwrap();
    repo.run_git_in(&feature_wt, &["add", "auth_test.rs"]);
    repo.run_git_in(&feature_wt, &["commit", "-m", "Add authentication tests"]);

    // Configure LLM in worktrunk config for deterministic, high-quality commit messages
    // On Windows, use .exe extension for the config-driven mock binary
    let llm_name = if cfg!(windows) { "llm.exe" } else { "llm" };
    let llm_path = bin_dir.join(llm_name);
    let llm_path_str = llm_path.to_slash_lossy();
    let worktrunk_config = format!(
        r#"
[commit.generation]
command = "{llm_path_str}"
"#
    );
    fs::write(repo.test_config_path(), worktrunk_config).unwrap();

    // Merge with --yes to skip approval prompts for commands
    let (path_var, path_with_bin) = make_path_with_mock_bin(&bin_dir);
    let bin_dir_str = bin_dir.to_string_lossy();
    snapshot_merge_with_env(
        "readme_example_complex",
        &repo,
        &["main", "--yes"],
        Some(&feature_wt),
        &[
            (&path_var, &path_with_bin),
            ("MOCK_CONFIG_DIR", &bin_dir_str),
        ],
    );
}

// NOTE: test_readme_example_hooks_pre_start and test_readme_example_hooks_pre_merge
// were removed - they're covered by PTY-based tests in shell_wrapper.rs that capture
// combined stdout/stderr for README examples.

#[rstest]
fn test_merge_no_commit_with_clean_tree(mut repo_with_feature_worktree: TestRepo) {
    let repo = &mut repo_with_feature_worktree;
    let feature_wt = &repo.worktrees["feature"];

    // Merge with --no-commit (should succeed - clean tree)
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main", "--no-commit", "--no-remove"],
        Some(feature_wt),
    ));
}

#[rstest]
fn test_merge_no_commit_with_dirty_tree(mut repo: TestRepo) {
    // Create a feature worktree with a commit
    let feature_wt = repo.add_worktree_with_commit(
        "feature",
        "committed.txt",
        "committed content",
        "Add committed file",
    );

    // Add uncommitted changes
    fs::write(feature_wt.join("uncommitted.txt"), "uncommitted content").unwrap();

    // Try to merge with --no-commit (should fail - dirty tree)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--no-commit"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_no_commit_no_squash_no_remove_redundant(mut repo_with_feature_worktree: TestRepo) {
    let repo = &mut repo_with_feature_worktree;
    let feature_wt = &repo.worktrees["feature"];

    // Merge with --no-commit --no-squash --no-remove (redundant but valid - should succeed)
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main", "--no-commit", "--no-squash", "--no-remove"],
        Some(feature_wt),
    ));
}

#[rstest]
fn test_merge_no_commits(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;

    // Create a feature worktree with NO commits (just branched from main)
    let feature_wt = repo.add_worktree("no-commits");

    // Merge without any commits - should skip both squashing and rebasing
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_no_commits_with_changes(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;

    // Create a feature worktree with NO commits but WITH uncommitted changes
    let feature_wt = repo.add_worktree("no-commits-dirty");
    fs::write(feature_wt.join("newfile.txt"), "new content").unwrap();

    // Merge - should commit the changes, skip squashing (only 1 commit), and skip rebasing (at merge base)
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_rebase_fast_forward(mut repo: TestRepo) {
    // Test fast-forward case: branch has no commits, main moved ahead
    // Should show "Fast-forwarded to main" without progress message

    // Create a feature worktree with NO commits (just branched from main)
    let feature_wt = repo.add_worktree("fast-forward-test");

    // Advance main with a new commit (in the primary worktree which is on main)
    fs::write(repo.root_path().join("main-update.txt"), "main content").unwrap();
    repo.run_git(&["add", "main-update.txt"]);
    repo.run_git(&["commit", "-m", "Update main"]);

    // Merge - should fast-forward (no commits to replay)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_rebase_true_rebase(mut repo: TestRepo) {
    // Test true rebase case: branch has commits and main moved ahead
    // Should show "Rebasing onto main..." progress message

    // Create a feature worktree with a commit
    let feature_wt = repo.add_worktree_with_commit(
        "true-rebase-test",
        "feature.txt",
        "feature content",
        "Add feature",
    );

    // Advance main with a new commit (in the primary worktree which is on main)
    fs::write(repo.root_path().join("main-update.txt"), "main content").unwrap();
    repo.run_git(&["add", "main-update.txt"]);
    repo.run_git(&["commit", "-m", "Update main"]);

    // Merge - should show rebasing progress (has commits to replay)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

// =============================================================================
// --no-rebase tests
// =============================================================================

#[rstest]
fn test_merge_no_rebase_when_already_rebased(merge_scenario: (TestRepo, PathBuf)) {
    // Feature branch is based on main (no divergence), so --no-rebase should succeed
    let (repo, feature_wt) = merge_scenario;

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--no-rebase"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_no_rebase_when_not_rebased(mut repo: TestRepo) {
    // Create a feature worktree with a commit
    let feature_wt = repo.add_worktree_with_commit(
        "not-rebased-test",
        "feature.txt",
        "feature content",
        "Add feature",
    );

    // Advance main with a new commit (makes feature branch diverge)
    fs::write(repo.root_path().join("main-update.txt"), "main content").unwrap();
    repo.run_git(&["add", "main-update.txt"]);
    repo.run_git(&["commit", "-m", "Update main"]);

    // --no-rebase should fail because feature is not rebased onto main
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--no-rebase"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_primary_on_different_branch(mut repo: TestRepo) {
    repo.switch_primary_to("develop");
    assert_eq!(repo.current_branch(), "develop");

    // Create a feature worktree and make a commit
    let feature_wt = repo.add_worktree_with_commit(
        "feature-from-develop",
        "feature.txt",
        "feature content",
        "Add feature file",
    );

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));

    // Verify primary stayed on develop (we don't switch branches, only worktrees)
    assert_eq!(repo.current_branch(), "develop");
}

#[rstest]
fn test_merge_primary_on_different_branch_dirty(mut repo: TestRepo) {
    // Make main and develop diverge - modify file.txt on main
    fs::write(repo.root_path().join("file.txt"), "main version").unwrap();
    repo.run_git(&["add", "file.txt"]);
    repo.run_git(&["commit", "-m", "Update file on main"]);

    // Create a develop branch from the previous commit (before the main update)
    let base_commit = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["rev-parse", "HEAD~1"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();
    repo.run_git(&["switch", "-c", "develop", &base_commit]);

    // Modify file.txt in develop (uncommitted) to a different value
    // This will conflict when trying to switch to main
    fs::write(repo.root_path().join("file.txt"), "develop local changes").unwrap();

    // Create a feature worktree and make a commit
    let feature_wt = repo.add_worktree_with_commit(
        "feature-dirty-primary",
        "feature.txt",
        "feature content",
        "Add feature file",
    );

    // Try to merge to main - should fail because primary has uncommitted changes that conflict
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_race_condition_commit_after_push(mut repo_with_feature_worktree: TestRepo) {
    let repo = &mut repo_with_feature_worktree;
    let feature_wt = repo.worktrees["feature"].clone();

    // Merge to main (this pushes the branch to main)
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main", "--no-remove"],
        Some(&feature_wt)
    ));

    // RACE CONDITION: Simulate another developer adding a commit to the feature branch
    // after the merge/push but before worktree removal and branch deletion.
    // Since feature is already checked out in feature_wt, we'll add the commit directly there.
    fs::write(feature_wt.join("extra.txt"), "race condition commit").unwrap();
    repo.run_git_in(&feature_wt, &["add", "extra.txt"]);
    repo.run_git_in(
        &feature_wt,
        &["commit", "-m", "Add extra file (race condition)"],
    );

    // Now simulate what wt merge would do: remove the worktree
    repo.run_git(&["worktree", "remove", feature_wt.to_str().unwrap()]);

    // Try to delete the branch with -d (safe delete)
    // This should FAIL because the branch has the race condition commit not in main
    let output = repo
        .git_command()
        .args(["branch", "-d", "feature"])
        .run()
        .unwrap();

    // Verify the deletion failed (non-zero exit code)
    assert!(
        !output.status.success(),
        "git branch -d should fail when branch has unmerged commits"
    );

    // Verify the error message mentions the branch is not fully merged
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("not fully merged") || stderr.contains("not merged"),
        "Error should mention branch is not fully merged, got: {}",
        stderr
    );

    // Verify the branch still exists (wasn't deleted)
    let output = repo
        .git_command()
        .args(["branch", "--list", "feature"])
        .run()
        .unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("feature"),
        "Branch should still exist after failed deletion"
    );
}

#[rstest]
fn test_merge_to_non_default_target(repo: TestRepo) {
    // Switch back to main and add a commit there
    repo.run_git(&["switch", "main"]);
    std::fs::write(repo.root_path().join("main-file.txt"), "main content").unwrap();
    repo.run_git(&["add", "main-file.txt"]);
    repo.run_git(&["commit", "-m", "Add main-specific file"]);

    // Create a staging branch from BEFORE the main commit
    let base_commit = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["rev-parse", "HEAD~1"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();
    repo.run_git(&["switch", "-c", "staging", &base_commit]);

    // Add a commit to staging to make it different from main
    std::fs::write(repo.root_path().join("staging-file.txt"), "staging content").unwrap();
    repo.run_git(&["add", "staging-file.txt"]);
    repo.run_git(&["commit", "-m", "Add staging-specific file"]);

    // Switch back to main before creating the staging worktree
    repo.run_git(&["switch", "main"]);

    // Create a worktree for staging
    let staging_wt = repo.root_path().parent().unwrap().join("repo.staging-wt");
    repo.run_git(&["worktree", "add", staging_wt.to_str().unwrap(), "staging"]);

    // Create a feature worktree from the base commit (before both main and staging diverged)
    let feature_wt = repo
        .root_path()
        .parent()
        .unwrap()
        .join("repo.feature-for-staging");
    repo.run_git(&[
        "worktree",
        "add",
        feature_wt.to_str().unwrap(),
        "-b",
        "feature-for-staging",
        &base_commit,
    ]);

    std::fs::write(feature_wt.join("feature.txt"), "feature content").unwrap();
    repo.run_git_in(&feature_wt, &["add", "feature.txt"]);
    repo.run_git_in(&feature_wt, &["commit", "-m", "Add feature for staging"]);

    // Merge to staging explicitly (NOT to main)
    // This should rebase onto staging (which has staging-file.txt)
    // NOT onto main (which has main-file.txt)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["staging"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_squash_with_working_tree_creates_backup(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;

    // Create a feature worktree with multiple commits
    let feature_wt = repo.add_worktree("feature");

    // First commit
    std::fs::write(feature_wt.join("file1.txt"), "content 1").unwrap();
    repo.run_git_in(&feature_wt, &["add", "file1.txt"]);
    repo.run_git_in(&feature_wt, &["commit", "-m", "feat: add file 1"]);

    // Second commit
    std::fs::write(feature_wt.join("file2.txt"), "content 2").unwrap();
    repo.run_git_in(&feature_wt, &["add", "file2.txt"]);
    repo.run_git_in(&feature_wt, &["commit", "-m", "feat: add file 2"]);

    // Add uncommitted tracked changes that will be included in the squash
    std::fs::write(feature_wt.join("file1.txt"), "updated content 1").unwrap();

    // Merge with squash (default behavior)
    // This should create a backup before squashing because there are uncommitted changes
    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(repo, "merge", &["main"], Some(&feature_wt));
        cmd.env(
            "WORKTRUNK_COMMIT__GENERATION__COMMAND",
            "cat >/dev/null && echo 'fix: update files'",
        );
        cmd
    });

    // Verify that a backup was created in the reflog
    // Note: The worktree has been removed by the merge, so we check from the repo root
    let output = repo
        .git_command()
        .args(["reflog", "show", "refs/wt-backup/feature"])
        .run()
        .unwrap();

    let reflog = String::from_utf8_lossy(&output.stdout);
    assert!(
        reflog.contains("feature → main (squash)"),
        "Expected backup in reflog, but reflog was: {}",
        reflog
    );
}

#[rstest]
fn test_merge_when_default_branch_missing_worktree(repo: TestRepo) {
    // Move primary off default branch so no worktree holds it
    repo.switch_primary_to("develop");

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

#[rstest]
fn test_merge_doesnt_set_receive_deny_current_branch(merge_scenario: (TestRepo, PathBuf)) {
    let (repo, feature_wt) = merge_scenario;

    // Explicitly set config to "refuse" - this would block pushes to checked-out branches
    repo.run_git(&["config", "receive.denyCurrentBranch", "refuse"]);

    // Perform merge - should succeed despite "refuse" setting because we use --receive-pack
    let mut cmd = make_snapshot_cmd(&repo, "merge", &["main"], Some(&feature_wt));
    let output = cmd.output().unwrap();
    assert!(
        output.status.success(),
        "Merge should succeed even with receive.denyCurrentBranch=refuse.\n\
         stdout: {}\n\
         stderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    // Check config after merge - should still be "refuse" (not permanently changed)
    let after = repo
        .git_command()
        .args(["config", "receive.denyCurrentBranch"])
        .run()
        .unwrap();
    let after_value = String::from_utf8_lossy(&after.stdout).trim().to_string();

    assert_eq!(
        after_value, "refuse",
        "receive.denyCurrentBranch should not be permanently modified by merge.\n\
         Expected: \"refuse\"\n\
         Got: {:?}",
        after_value
    );
}

#[rstest]
fn test_step_squash_with_no_hooks_flag(mut repo: TestRepo) {
    // Create a feature worktree with multiple commits
    let feature_wt = repo.add_worktree("feature");

    // Add a pre-commit hook so --no-hooks has something to skip
    // Create in feature worktree since worktrees don't share working tree files
    fs::create_dir_all(feature_wt.join(".config")).expect("Failed to create .config");
    fs::write(
        feature_wt.join(".config/wt.toml"),
        "pre-commit = \"echo pre-commit check\"",
    )
    .expect("Failed to write wt.toml");

    // Commit the config as part of first commit to avoid untracked file warnings
    fs::write(feature_wt.join("file1.txt"), "content 1").expect("Failed to write file");
    repo.run_git_in(&feature_wt, &["add", ".config", "file1.txt"]);
    repo.run_git_in(&feature_wt, &["commit", "-m", "feat: add file 1"]);

    fs::write(feature_wt.join("file2.txt"), "content 2").expect("Failed to write file");
    repo.run_git_in(&feature_wt, &["add", "file2.txt"]);
    repo.run_git_in(&feature_wt, &["commit", "-m", "feat: add file 2"]);

    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(&repo, "step", &[], Some(&feature_wt));
        cmd.arg("squash").args(["--no-hooks"]);
        cmd.env(
            "WORKTRUNK_COMMIT__GENERATION__COMMAND",
            "cat >/dev/null && echo 'squash: combined commits'",
        );
        cmd
    });
}

#[rstest]
fn test_step_squash_with_stage_tracked_flag(mut repo: TestRepo) {
    let feature_wt = repo.add_worktree("feature");

    fs::write(feature_wt.join("file1.txt"), "content 1").expect("Failed to write file");
    repo.run_git_in(&feature_wt, &["add", "file1.txt"]);
    repo.run_git_in(&feature_wt, &["commit", "-m", "feat: add file 1"]);

    fs::write(feature_wt.join("file2.txt"), "content 2").expect("Failed to write file");
    repo.run_git_in(&feature_wt, &["add", "file2.txt"]);
    repo.run_git_in(&feature_wt, &["commit", "-m", "feat: add file 2"]);

    // Add uncommitted tracked changes
    fs::write(feature_wt.join("file1.txt"), "updated content").expect("Failed to write file");

    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(&repo, "step", &[], Some(&feature_wt));
        cmd.arg("squash").args(["--stage=tracked"]);
        cmd.env(
            "WORKTRUNK_COMMIT__GENERATION__COMMAND",
            "cat >/dev/null && echo 'squash: combined commits'",
        );
        cmd
    });
}

#[rstest]
fn test_step_squash_with_both_flags(mut repo: TestRepo) {
    let feature_wt = repo.add_worktree("feature");

    // Add a pre-commit hook so --no-hooks has something to skip
    // Create in feature worktree since worktrees don't share working tree files
    fs::create_dir_all(feature_wt.join(".config")).expect("Failed to create .config");
    fs::write(
        feature_wt.join(".config/wt.toml"),
        "pre-commit = \"echo pre-commit check\"",
    )
    .expect("Failed to write wt.toml");

    // Commit the config as part of first commit to avoid untracked file warnings
    fs::write(feature_wt.join("file1.txt"), "content 1").expect("Failed to write file");
    repo.run_git_in(&feature_wt, &["add", ".config", "file1.txt"]);
    repo.run_git_in(&feature_wt, &["commit", "-m", "feat: add file 1"]);

    fs::write(feature_wt.join("file2.txt"), "content 2").expect("Failed to write file");
    repo.run_git_in(&feature_wt, &["add", "file2.txt"]);
    repo.run_git_in(&feature_wt, &["commit", "-m", "feat: add file 2"]);

    fs::write(feature_wt.join("file1.txt"), "updated content").expect("Failed to write file");

    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(&repo, "step", &[], Some(&feature_wt));
        cmd.arg("squash").args(["--no-hooks", "--stage=tracked"]);
        cmd.env(
            "WORKTRUNK_COMMIT__GENERATION__COMMAND",
            "cat >/dev/null && echo 'squash: combined commits'",
        );
        cmd
    });
}

#[rstest]
fn test_step_squash_no_commits(mut repo: TestRepo) {
    // Test "nothing to squash; no commits ahead" message

    // Create a feature worktree but don't add any commits
    let feature_wt = repo.add_worktree("feature");

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["squash"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_step_squash_single_commit(mut repo: TestRepo) {
    // Test "nothing to squash; already a single commit" message

    // Create a feature worktree with exactly one commit
    let feature_wt =
        repo.add_worktree_with_commit("feature", "file1.txt", "content 1", "feat: single commit");

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["squash"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_step_commit_with_no_hooks_flag(repo: TestRepo) {
    // Add a pre-commit hook so --no-hooks has something to skip
    fs::create_dir_all(repo.root_path().join(".config")).expect("Failed to create .config");
    fs::write(
        repo.root_path().join(".config/wt.toml"),
        "pre-commit = \"echo pre-commit check\"",
    )
    .expect("Failed to write wt.toml");

    fs::write(repo.root_path().join("file1.txt"), "content 1").expect("Failed to write file");

    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(&repo, "step", &[], None);
        cmd.arg("commit").args(["--no-hooks"]);
        cmd.env(
            "WORKTRUNK_COMMIT__GENERATION__COMMAND",
            "cat >/dev/null && echo 'feat: add file'",
        );
        cmd
    });
}

#[rstest]
fn test_step_commit_with_stage_tracked_flag(repo: TestRepo) {
    fs::write(repo.root_path().join("tracked.txt"), "initial").expect("Failed to write file");
    repo.commit("add tracked file");

    fs::write(repo.root_path().join("tracked.txt"), "modified").expect("Failed to write file");
    fs::write(
        repo.root_path().join("untracked.txt"),
        "should not be staged",
    )
    .expect("Failed to write file");

    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(&repo, "step", &[], None);
        cmd.arg("commit").args(["--stage=tracked"]);
        cmd.env(
            "WORKTRUNK_COMMIT__GENERATION__COMMAND",
            "cat >/dev/null && echo 'fix: update tracked file'",
        );
        cmd
    });
}

#[rstest]
fn test_step_commit_with_both_flags(repo: TestRepo) {
    // Add a pre-commit hook so --no-hooks has something to skip
    fs::create_dir_all(repo.root_path().join(".config")).expect("Failed to create .config");
    fs::write(
        repo.root_path().join(".config/wt.toml"),
        "pre-commit = \"echo pre-commit check\"",
    )
    .expect("Failed to write wt.toml");

    fs::write(repo.root_path().join("tracked.txt"), "initial").expect("Failed to write file");
    repo.commit("add tracked file");

    fs::write(repo.root_path().join("tracked.txt"), "modified").expect("Failed to write file");

    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(&repo, "step", &[], None);
        cmd.arg("commit").args(["--no-hooks", "--stage=tracked"]);
        cmd.env(
            "WORKTRUNK_COMMIT__GENERATION__COMMAND",
            "cat >/dev/null && echo 'fix: update file'",
        );
        cmd
    });
}

#[rstest]
fn test_step_commit_nothing_to_commit(repo: TestRepo) {
    // No changes made - commit should fail with "nothing to commit"
    // This test doesn't need LLM config since commit fails before generation
    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(&repo, "step", &[], None);
        cmd.arg("commit").args(["--stage=none"]);
        cmd
    });
}

#[rstest]
fn test_step_commit_branch_flag(mut repo: TestRepo) {
    // Create a feature worktree and add a dirty file there
    let feature_wt = repo.add_worktree("feature");
    fs::write(feature_wt.join("feature_file.txt"), "feature content")
        .expect("Failed to write file");

    // Run step commit from the main worktree, targeting the feature branch
    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(&repo, "step", &[], None); // cwd = main worktree
        cmd.arg("commit")
            .args(["--branch", "feature", "--no-hooks"]);
        cmd.env(
            "WORKTRUNK_COMMIT__GENERATION__COMMAND",
            "cat >/dev/null && echo 'feat: add feature file'",
        );
        cmd
    });

    // Verify the commit happened in the feature worktree
    let log_output = {
        let output = repo
            .git_command()
            .args(["log", "--oneline", "-1"])
            .current_dir(&feature_wt)
            .run()
            .unwrap();
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    };
    assert!(
        log_output.contains("feat: add feature file"),
        "Commit should appear in feature worktree, got: {log_output}"
    );
}

#[rstest]
fn test_step_commit_branch_flag_nonexistent(repo: TestRepo) {
    // Try to commit on a branch that has no worktree
    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(&repo, "step", &[], None);
        cmd.arg("commit").args(["--branch", "nonexistent"]);
        cmd
    });
}

#[rstest]
fn test_step_commit_detached_head(mut repo: TestRepo) {
    // Detach HEAD in a worktree, then commit — should work since commit
    // only needs a worktree path, not a branch name.
    let feature_wt = repo.add_worktree("feature");

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

    // Create a file to commit
    fs::write(feature_wt.join("detached_file.txt"), "detached content")
        .expect("Failed to write file");

    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(&repo, "step", &[], Some(&feature_wt));
        cmd.arg("commit").args(["--no-hooks"]);
        cmd.env(
            "WORKTRUNK_COMMIT__GENERATION__COMMAND",
            "cat >/dev/null && echo 'chore: commit in detached state'",
        );
        cmd
    });

    // Verify the commit actually landed
    let log_output = {
        let output = repo
            .git_command()
            .args(["log", "--oneline", "-1"])
            .current_dir(&feature_wt)
            .run()
            .unwrap();
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    };
    assert!(
        log_output.contains("chore: commit in detached state"),
        "Commit should appear in detached worktree, got: {log_output}"
    );
}

// =============================================================================
// Error message snapshot tests
// =============================================================================

#[rstest]
fn test_merge_error_uncommitted_changes_with_no_commit(mut repo_with_main_worktree: TestRepo) {
    // Tests the `uncommitted_changes()` error function when using --no-commit with dirty tree
    let repo = &mut repo_with_main_worktree;

    // Create a feature worktree
    let feature_wt = repo.add_worktree("feature");

    // Make uncommitted changes (dirty working tree)
    fs::write(feature_wt.join("dirty.txt"), "uncommitted content").unwrap();

    // Try to merge with --no-commit - should fail because working tree is dirty
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main", "--no-commit", "--no-remove"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_merge_error_conflicting_changes_in_target(mut repo_with_alternate_primary: TestRepo) {
    // Tests the `conflicting_changes()` error function when target worktree has
    // uncommitted changes that overlap with files being pushed
    let repo = &mut repo_with_alternate_primary;

    // Create a feature worktree and commit a change to shared.txt
    let feature_wt = repo.add_worktree_with_commit(
        "feature",
        "shared.txt",
        "feature content",
        "Add shared.txt on feature",
    );

    // Get the main worktree path (created by repo_with_alternate_primary)
    let main_wt = repo.root_path().parent().unwrap().join("repo.main-wt");

    // Now make uncommitted changes to shared.txt in main worktree
    // This creates a conflict - we're trying to push changes to shared.txt
    // but main has uncommitted changes to the same file
    fs::write(
        main_wt.join("shared.txt"),
        "conflicting uncommitted content",
    )
    .unwrap();

    // Try to merge - should fail because of conflicting uncommitted changes
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main"],
        Some(&feature_wt)
    ));
}

// =============================================================================
// --show-prompt tests
// =============================================================================

#[rstest]
fn test_step_commit_show_prompt(repo: TestRepo) {
    // Create some staged changes so there's a diff to include in the prompt
    fs::write(repo.root_path().join("new_file.txt"), "new content").expect("Failed to write file");
    repo.git_command().args(["add", "new_file.txt"]);

    // The prompt should be written to stdout
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["commit", "--show-prompt"],
        None
    ));
}

#[rstest]
fn test_step_commit_show_prompt_no_staged_changes(repo: TestRepo) {
    // No staged changes - should still output the prompt (with empty diff)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["commit", "--show-prompt"],
        None
    ));
}

#[rstest]
fn test_step_squash_show_prompt(repo_with_multi_commit_feature: TestRepo) {
    let repo = repo_with_multi_commit_feature;

    // Get the feature worktree path
    let feature_wt = repo.worktree_path("feature");

    // Should output the squash prompt with commits and diff
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["squash", "--show-prompt"],
        Some(feature_wt)
    ));
}

// =============================================================================
// step rebase tests
// =============================================================================

///
/// When a branch has merged main into it, the merge-base equals main's HEAD,
/// but there are still commits that need rebasing to linearize the history.
/// This test verifies that we don't incorrectly report "Already up-to-date".
#[rstest]
fn test_step_rebase_with_merge_commit(mut repo: TestRepo) {
    // Create a feature worktree with a commit
    let feature_wt = repo.add_worktree_with_commit(
        "feature-with-merge",
        "feature.txt",
        "feature content",
        "Add feature",
    );

    // Advance main with a new commit
    fs::write(repo.root_path().join("main-update.txt"), "main content").unwrap();
    repo.run_git(&["add", "main-update.txt"]);
    repo.run_git(&["commit", "-m", "Update main"]);

    // Merge main INTO the feature branch (creating a merge commit)
    let output = repo
        .git_command()
        .current_dir(&feature_wt)
        .args(["merge", "main", "-m", "Merge main into feature"])
        .run()
        .unwrap();
    assert!(
        output.status.success(),
        "git merge failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Now step rebase should linearize the history (not report "Already up-to-date")
    assert_cmd_snapshot!({
        let mut cmd = make_snapshot_cmd(&repo, "step", &[], Some(&feature_wt));
        cmd.arg("rebase").args(["main"]);
        cmd
    });
}

/// Test `wt step rebase` when the feature branch is already up to date with main.
///
/// This should show "Already up to date with main" message.
#[rstest]
fn test_step_rebase_already_up_to_date(mut repo: TestRepo) {
    // Create a feature worktree but don't advance main (feature is based on main's HEAD)
    let feature_wt = repo.add_worktree("feature");

    // Run `wt step rebase` - should show "Already up to date with main"
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["rebase"],
        Some(&feature_wt)
    ));
}

// =============================================================================
// Target validation tests
// =============================================================================

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

    // Try to merge into nonexistent branch - should fail with clear error
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["nonexistent-branch"],
        Some(&feature_wt)
    ));
}

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

    // Try to rebase onto nonexistent ref - should fail with clear error
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["rebase", "nonexistent-ref"],
        Some(&feature_wt)
    ));
}

#[rstest]
fn test_step_rebase_accepts_tag(mut repo: TestRepo) {
    // Create a tag on main
    repo.run_git(&["tag", "v1.0"]);

    // Advance main
    fs::write(repo.root_path().join("after-tag.txt"), "content").unwrap();
    repo.run_git(&["add", "after-tag.txt"]);
    repo.run_git(&["commit", "-m", "After tag"]);

    // Create feature from current main
    let feature_wt = repo.add_worktree("feature");

    // Rebase onto the tag - should work (commit-ish accepted)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["rebase", "v1.0"],
        Some(&feature_wt)
    ));
}

// =============================================================================
// Behavior verification: --squash with --no-commit
// =============================================================================

/// Verify that `--squash` is correctly ignored when `--no-commit` is passed.
///
/// This is expected behavior: squashing creates a single commit from multiple
/// commits. If `--no-commit` is passed, there's no commit to create, so squash
/// has no effect. The merge proceeds as a fast-forward to the target.
#[rstest]
fn test_merge_squash_ignored_with_no_commit(repo_with_multi_commit_feature: TestRepo) {
    let repo = &repo_with_multi_commit_feature;
    let feature_wt = &repo.worktrees["feature"];

    // With --no-commit, squash has no effect - the merge fast-forwards
    // to main without creating any new commits
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main", "--squash", "--no-commit", "--no-remove"],
        Some(feature_wt)
    ));
}

// =============================================================================
// --no-ff merge (creates merge commit via commit-tree)
// =============================================================================

/// Basic --no-ff merge: single commit on feature, creates a merge commit on target.
#[rstest]
fn test_merge_no_ff_basic(merge_scenario: (TestRepo, PathBuf)) {
    let (repo, feature_wt) = merge_scenario;

    // Merge with --no-ff and --no-remove so we can inspect the result
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--no-ff", "--no-remove"],
        Some(&feature_wt)
    ));

    // Verify a merge commit was created (HEAD on main should have 2 parents)
    let parent_count = repo.git_output(&["cat-file", "-p", "main"]);
    let parents: Vec<&str> = parent_count
        .lines()
        .filter(|l| l.starts_with("parent "))
        .collect();
    assert_eq!(
        parents.len(),
        2,
        "Merge commit should have exactly 2 parents"
    );

    // Verify the merge commit message
    let commit_msg = repo.git_output(&["log", "-1", "--format=%s", "main"]);
    assert_eq!(commit_msg, "Merge branch 'feature' into main");
}

/// --no-ff merge with multiple commits (no squash): all commits preserved plus merge commit.
#[rstest]
fn test_merge_no_ff_multi_commit(repo_with_multi_commit_feature: TestRepo) {
    let repo = &repo_with_multi_commit_feature;
    let feature_wt = &repo.worktrees["feature"];

    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main", "--no-ff", "--no-squash", "--no-remove"],
        Some(feature_wt)
    ));

    // Verify merge commit has 2 parents
    let parent_count = repo.git_output(&["cat-file", "-p", "main"]);
    let parents: Vec<&str> = parent_count
        .lines()
        .filter(|l| l.starts_with("parent "))
        .collect();
    assert_eq!(
        parents.len(),
        2,
        "Merge commit should have exactly 2 parents"
    );

    // Verify individual commits are preserved (3 commits on main: initial + merge,
    // with 2 feature commits reachable via second parent)
    let log = repo.git_output(&["log", "--oneline", "--graph", "main"]);
    assert!(log.contains("Merge branch"), "Should contain merge commit");
}

/// --no-ff merge with squash: squash first, then merge commit wrapping single squashed commit.
#[rstest]
fn test_merge_no_ff_with_squash(repo_with_multi_commit_feature: TestRepo) {
    let repo = &repo_with_multi_commit_feature;
    let feature_wt = &repo.worktrees["feature"];

    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main", "--no-ff", "--no-remove"],
        Some(feature_wt)
    ));

    // Verify merge commit has 2 parents
    let parent_count = repo.git_output(&["cat-file", "-p", "main"]);
    let parents: Vec<&str> = parent_count
        .lines()
        .filter(|l| l.starts_with("parent "))
        .collect();
    assert_eq!(
        parents.len(),
        2,
        "Merge commit should have exactly 2 parents"
    );
}

/// --no-ff via user config (no CLI flag needed).
#[rstest]
fn test_merge_no_ff_from_config(merge_scenario: (TestRepo, PathBuf)) {
    let (repo, feature_wt) = merge_scenario;

    // Write user config with ff = false
    fs::write(repo.test_config_path(), "[merge]\nff = false\n").unwrap();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--no-remove"],
        Some(&feature_wt)
    ));

    // Verify merge commit was created
    let parent_count = repo.git_output(&["cat-file", "-p", "main"]);
    let parents: Vec<&str> = parent_count
        .lines()
        .filter(|l| l.starts_with("parent "))
        .collect();
    assert_eq!(
        parents.len(),
        2,
        "Config-driven --no-ff should create merge commit"
    );
}

/// --ff CLI flag overrides config ff = false.
#[rstest]
fn test_merge_ff_flag_overrides_config(merge_scenario: (TestRepo, PathBuf)) {
    let (repo, feature_wt) = merge_scenario;

    // Write user config with ff = false
    fs::write(repo.test_config_path(), "[merge]\nff = false\n").unwrap();

    // --ff should override config and do a fast-forward
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--ff", "--no-remove"],
        Some(&feature_wt)
    ));

    // Verify NO merge commit (fast-forward: HEAD on main should have 1 parent)
    let parent_count = repo.git_output(&["cat-file", "-p", "main"]);
    let parents: Vec<&str> = parent_count
        .lines()
        .filter(|l| l.starts_with("parent "))
        .collect();
    assert_eq!(
        parents.len(),
        1,
        "--ff should override config and fast-forward"
    );
}

/// --no-ff with diverged branches: rebase first, then merge commit.
#[rstest]
fn test_merge_no_ff_with_rebase(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    let main_wt = repo.root_path().to_path_buf();
    let feature_wt = repo.add_worktree("feature");

    // Make a commit on feature
    repo.commit_in_worktree(&feature_wt, "feature.txt", "feature content", "Add feature");

    // Make a commit on main (diverge)
    repo.commit_in_worktree(&main_wt, "main.txt", "main content", "Advance main");

    // Merge with --no-ff: should rebase first, then create merge commit
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main", "--no-ff", "--no-squash", "--no-remove"],
        Some(&feature_wt)
    ));

    // Verify merge commit has 2 parents
    let parent_count = repo.git_output(&["cat-file", "-p", "main"]);
    let parents: Vec<&str> = parent_count
        .lines()
        .filter(|l| l.starts_with("parent "))
        .collect();
    assert_eq!(parents.len(), 2, "Should create merge commit after rebase");
}

/// --no-ff when already up to date (no commits to merge).
#[rstest]
fn test_merge_no_ff_already_up_to_date(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    let feature_wt = repo.add_worktree("feature");

    // Don't make any commits on feature - it's at the same point as main
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main", "--no-ff", "--no-remove"],
        Some(&feature_wt)
    ));
}

/// --no-ff with diverged branches and --no-rebase: fails because rebase is required.
///
/// When branches have diverged and --no-rebase is set, the merge cannot proceed
/// because --no-ff still requires a fast-forward relationship (rebase first, then
/// merge commit). This verifies the error path.
#[rstest]
fn test_merge_no_ff_diverged_no_rebase(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    let main_wt = repo.root_path().to_path_buf();
    let feature_wt = repo.add_worktree("feature");

    // Make a commit on feature
    repo.commit_in_worktree(&feature_wt, "feature.txt", "feature content", "Add feature");

    // Make a commit on main (diverge)
    repo.commit_in_worktree(&main_wt, "main.txt", "main content", "Advance main");

    // With --no-rebase, the merge fails because branches have diverged
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main", "--no-ff", "--no-rebase", "--no-remove"],
        Some(&feature_wt)
    ));
}

/// --no-ff merge succeeds and syncs target worktree via read-tree.
///
/// Verifies that after a --no-ff merge, the target worktree's working tree
/// reflects the merge commit (not the old HEAD).
#[rstest]
fn test_merge_no_ff_syncs_target_worktree(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    let main_wt = repo.root_path().to_path_buf();
    let feature_wt = repo.add_worktree("feature");

    // Make a commit on feature that adds a new file
    repo.commit_in_worktree(
        &feature_wt,
        "feature.txt",
        "feature content",
        "Add feature file",
    );

    // Merge with --no-ff
    let output = repo
        .wt_command()
        .args(["merge", "main", "--no-ff", "--no-remove"])
        .current_dir(&feature_wt)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "merge should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Verify the feature file exists in the main worktree (read-tree synced it)
    assert!(
        main_wt.join("feature.txt").exists(),
        "Target worktree should contain the merged file after read-tree"
    );

    // Verify the merge commit is on main
    let commit_msg = repo.git_output(&["log", "-1", "--format=%s", "main"]);
    assert_eq!(commit_msg, "Merge branch 'feature' into main");

    // Verify the target worktree HEAD matches the main branch tip
    let main_tip = repo.git_output(&["rev-parse", "main"]);
    let wt_head_output = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .current_dir(&main_wt)
        .run()
        .unwrap();
    let wt_head = String::from_utf8_lossy(&wt_head_output.stdout)
        .trim()
        .to_string();
    assert_eq!(
        main_tip, wt_head,
        "Target worktree HEAD should match main after read-tree"
    );
}

/// --no-ff merge with non-overlapping dirty files in the target worktree.
///
/// The target worktree has uncommitted changes to a file that doesn't overlap
/// with the merge. These should be auto-stashed, the merge commit created,
/// and the stash restored afterward.
#[rstest]
fn test_merge_no_ff_dirty_target_autostash(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    let main_wt = repo.root_path().to_path_buf();

    // Make main worktree dirty with a non-conflicting file
    fs::write(main_wt.join("notes.txt"), "temporary notes").unwrap();

    let feature_wt = repo.add_worktree("feature");
    repo.commit_in_worktree(&feature_wt, "feature.txt", "feature content", "Add feature");

    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main", "--no-ff", "--no-remove"],
        Some(&feature_wt)
    ));

    // Verify dirty file was restored after autostash
    let notes = fs::read_to_string(main_wt.join("notes.txt")).unwrap();
    assert_eq!(
        notes, "temporary notes",
        "Autostash should restore dirty file"
    );

    // Verify autostash cleaned up (no leftover stash entries)
    let stash_list = repo.git_command().args(["stash", "list"]).run().unwrap();
    assert!(
        String::from_utf8_lossy(&stash_list.stdout)
            .trim()
            .is_empty(),
        "Autostash should clean up after itself"
    );

    // Verify merge commit was created
    let parent_count = repo.git_output(&["cat-file", "-p", "main"]);
    let parents: Vec<&str> = parent_count
        .lines()
        .filter(|l| l.starts_with("parent "))
        .collect();
    assert_eq!(parents.len(), 2, "Should create merge commit");
}

/// --no-ff merge with overlapping dirty files in the target worktree.
///
/// The target worktree has uncommitted changes to a file that overlaps with
/// the merge range. The merge should fail safely without creating a merge
/// commit or losing the dirty changes.
#[rstest]
fn test_merge_no_ff_dirty_target_conflict(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    let main_wt = repo.root_path().to_path_buf();

    // Make main worktree dirty with a file that will conflict
    fs::write(main_wt.join("conflict.txt"), "old content").unwrap();

    let feature_wt =
        repo.add_worktree_with_commit("feature", "conflict.txt", "new content", "Add conflict");

    // Should fail due to conflicting uncommitted changes in target
    assert_cmd_snapshot!(make_snapshot_cmd(
        repo,
        "merge",
        &["main", "--no-ff", "--no-remove"],
        Some(&feature_wt)
    ));

    // Verify target worktree file is untouched
    let contents = fs::read_to_string(main_wt.join("conflict.txt")).unwrap();
    assert_eq!(
        contents, "old content",
        "Target dirty file should be untouched"
    );

    // Verify no stash was created
    let stash_list = repo.git_command().args(["stash", "list"]).run().unwrap();
    assert!(
        String::from_utf8_lossy(&stash_list.stdout)
            .trim()
            .is_empty(),
        "No stash should be created on conflict"
    );

    // Verify no merge commit was created (main should not have 2 parents)
    let parent_count = repo.git_output(&["cat-file", "-p", "main"]);
    let parents: Vec<&str> = parent_count
        .lines()
        .filter(|l| l.starts_with("parent "))
        .collect();
    assert!(
        parents.len() < 2,
        "No merge commit should be created on conflict"
    );
}

/// --no-ff merge succeeds with a warning when target worktree sync fails.
///
/// Simulates a TOCTOU race by locking the target worktree's index before the
/// merge. The merge commit is still created (via update-ref), but the working
/// tree sync (read-tree) fails and emits a warning instead of aborting.
#[rstest]
fn test_merge_no_ff_sync_failure_warns(mut repo_with_main_worktree: TestRepo) {
    let repo = &mut repo_with_main_worktree;
    let main_wt = repo.root_path().to_path_buf();
    let feature_wt = repo.add_worktree("feature");

    repo.commit_in_worktree(&feature_wt, "feature.txt", "feature content", "Add feature");

    // Lock the target worktree's index to make read-tree fail
    let index_lock = main_wt.join(".git/index.lock");
    fs::write(&index_lock, "").unwrap();

    let output = repo
        .wt_command()
        .args(["merge", "main", "--no-ff", "--no-remove"])
        .current_dir(&feature_wt)
        .output()
        .unwrap();

    // Merge should still succeed (ref was updated before sync)
    assert!(
        output.status.success(),
        "merge should succeed despite sync failure: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Should emit a warning about the sync failure
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("Failed to sync target worktree"),
        "should warn about sync failure: {stderr}"
    );

    // Verify merge commit was created on the ref
    let parent_count = repo.git_output(&["cat-file", "-p", "main"]);
    let parents: Vec<&str> = parent_count
        .lines()
        .filter(|l| l.starts_with("parent "))
        .collect();
    assert_eq!(
        parents.len(),
        2,
        "Should create merge commit despite sync failure"
    );

    // Clean up lock so test teardown doesn't fail
    let _ = fs::remove_file(&index_lock);
}

/// --no-ff merge when the target branch has no checked-out worktree.
///
/// The merge should succeed without attempting read-tree (no worktree to sync).
#[rstest]
fn test_merge_no_ff_target_without_worktree(repo: TestRepo) {
    // Move primary off main so main has no worktree
    repo.switch_primary_to("develop");

    // Make a commit on develop so there's something to merge
    repo.commit_in_worktree(
        repo.root_path(),
        "feature.txt",
        "feature content",
        "Add feature",
    );

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--no-ff"],
        None
    ));

    // Verify merge commit was created
    let parent_count = repo.git_output(&["cat-file", "-p", "main"]);
    let parents: Vec<&str> = parent_count
        .lines()
        .filter(|l| l.starts_with("parent "))
        .collect();
    assert_eq!(
        parents.len(),
        2,
        "Should create merge commit even without target worktree"
    );
}

// ============================================================================
// Post-merge pipeline test (Bug 1 regression test)
// ============================================================================

#[rstest]
fn test_merge_post_merge_pipeline_serial_ordering(mut repo: TestRepo) {
    // Post-merge with a pipeline config (list form) should preserve serial ordering.
    // Before the fix, pipelines were flattened into independent background commands,
    // losing serial/concurrent semantics.
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(
        config_dir.join("wt.toml"),
        r#"post-merge = [
    "echo STEP_ONE_DONE > step_one_marker.txt",
    "cat step_one_marker.txt > step_two_saw_one.txt"
]
"#,
    )
    .unwrap();

    repo.commit("Add pipeline config");

    let feature_wt = repo.add_feature();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "merge",
        &["main", "--yes"],
        Some(&feature_wt)
    ));

    // Step 2 reads step 1's output. With pipeline semantics, step 2 runs after step 1.
    // Without pipeline semantics (flat), they'd race and step 2 would likely fail.
    let marker_file = repo.root_path().join("step_two_saw_one.txt");
    wait_for_file_content(&marker_file);

    let content = fs::read_to_string(&marker_file).unwrap();
    assert!(
        content.contains("STEP_ONE_DONE"),
        "Step 2 should see step 1's output (serial pipeline), got: {content}"
    );
}

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

#[rstest]
fn test_merge_json(repo: TestRepo) {
    let (repo, feature_wt) = merge_scenario(repo);

    let output = repo
        .wt_command()
        .args(["merge", "--format=json", "--yes", "--no-hooks"])
        .current_dir(&feature_wt)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_snapshot!(String::from_utf8_lossy(&output.stdout), @r#"
    {
      "branch": "feature",
      "committed": false,
      "rebased": false,
      "removed": true,
      "squashed": false,
      "target": "main"
    }
    "#);
}