stax 0.50.2

Fast stacked Git branches and PRs
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
use anyhow::{Context, Result};
use git2::{BranchType, Repository};
use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Output};

pub struct GitRepo {
    repo: Repository,
}

fn normalize_local_branch_name(branch: &str) -> &str {
    branch.strip_prefix("refs/heads/").unwrap_or(branch)
}

fn parse_branch_vv_worktree_path(line: &str) -> Option<PathBuf> {
    let start = line.find(" (")?;
    let rest = &line[start + 2..];
    let end = rest.find(')')?;
    Some(PathBuf::from(&rest[..end]))
}

fn worktree_basename(path: &Path) -> String {
    path.file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_else(|| "unknown".to_string())
}

fn branch_leaf(branch: &str) -> String {
    branch.rsplit('/').next().unwrap_or(branch).to_string()
}

fn path_components(path: &Path) -> Vec<String> {
    path.components()
        .filter_map(|component| match component {
            Component::Normal(value) => Some(value.to_string_lossy().into_owned()),
            Component::Prefix(value) => Some(value.as_os_str().to_string_lossy().into_owned()),
            Component::RootDir | Component::CurDir | Component::ParentDir => None,
        })
        .collect()
}

fn path_suffix_label(path: &Path, depth: usize) -> String {
    let components = path_components(path);
    let start = components.len().saturating_sub(depth);
    components[start..].join("/")
}

fn minimal_unique_path_suffix(
    path: &Path,
    all_paths: &[PathBuf],
    reserved: &HashSet<String>,
) -> String {
    let component_count = path_components(path).len();
    for depth in 1..=component_count {
        let candidate = path_suffix_label(path, depth);
        if reserved.contains(&candidate) {
            continue;
        }

        let matches = all_paths
            .iter()
            .filter(|other| path_suffix_label(other, depth) == candidate)
            .count();
        if matches == 1 {
            return candidate;
        }
    }

    path.display().to_string()
}

#[derive(Debug, Clone)]
struct WorktreeLabelCandidate {
    is_main: bool,
    path: PathBuf,
    basename: String,
    branch: Option<String>,
}

fn assign_unique_label_stage<F>(
    labels: &mut [Option<String>],
    reserved: &mut HashSet<String>,
    candidates: &[WorktreeLabelCandidate],
    mut label_for: F,
) where
    F: FnMut(&WorktreeLabelCandidate) -> Option<String>,
{
    let mut counts = HashMap::new();
    for (idx, candidate) in candidates.iter().enumerate() {
        if labels[idx].is_some() {
            continue;
        }

        if let Some(label) = label_for(candidate) {
            if !reserved.contains(&label) {
                *counts.entry(label).or_insert(0usize) += 1;
            }
        }
    }

    for (idx, candidate) in candidates.iter().enumerate() {
        if labels[idx].is_some() {
            continue;
        }

        let Some(label) = label_for(candidate) else {
            continue;
        };

        if reserved.contains(&label) || counts.get(&label).copied() != Some(1) {
            continue;
        }

        reserved.insert(label.clone());
        labels[idx] = Some(label);
    }
}

fn derive_worktree_names(candidates: &[WorktreeLabelCandidate]) -> Vec<String> {
    let mut labels = vec![None; candidates.len()];
    let mut reserved = HashSet::new();

    for (idx, candidate) in candidates.iter().enumerate() {
        if candidate.is_main {
            labels[idx] = Some("main".to_string());
            reserved.insert("main".to_string());
        }
    }

    assign_unique_label_stage(&mut labels, &mut reserved, candidates, |candidate| {
        (!candidate.is_main).then(|| candidate.basename.clone())
    });
    assign_unique_label_stage(&mut labels, &mut reserved, candidates, |candidate| {
        candidate.branch.as_deref().map(branch_leaf)
    });
    assign_unique_label_stage(&mut labels, &mut reserved, candidates, |candidate| {
        candidate.branch.clone()
    });

    let all_paths = candidates
        .iter()
        .map(|candidate| candidate.path.clone())
        .collect::<Vec<_>>();
    for (idx, candidate) in candidates.iter().enumerate() {
        if labels[idx].is_none() {
            let label = minimal_unique_path_suffix(&candidate.path, &all_paths, &reserved);
            reserved.insert(label.clone());
            labels[idx] = Some(label);
        }
    }

    labels
        .into_iter()
        .map(|label| label.expect("every worktree should get a label"))
        .collect()
}

fn run_git_in(cwd: &Path, args: &[&str]) -> Result<Output> {
    Command::new("git")
        .args(args)
        .current_dir(cwd)
        .output()
        .with_context(|| format!("Failed to run git {}", args.join(" ")))
}

pub fn checkout_branch_in(workdir: &Path, branch: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["checkout", branch])
        .current_dir(workdir)
        .output()
        .with_context(|| format!("Failed to run git checkout {}", branch))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
        anyhow::bail!("git checkout {} failed: {}", branch, stderr);
    }

    Ok(())
}

pub fn local_branch_exists_in(workdir: &Path, branch: &str) -> bool {
    let local_ref = format!("refs/heads/{}", branch);
    Command::new("git")
        .args(["show-ref", "--verify", "--quiet", &local_ref])
        .current_dir(workdir)
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

#[derive(Debug, Clone)]
pub struct WorktreeInfo {
    /// Short display/selector label: "main" for the main worktree, otherwise a unique label
    /// derived from the basename, branch, or path suffix.
    pub name: String,
    pub path: PathBuf,
    pub branch: Option<String>,
    /// True for the first entry (main worktree, not a linked worktree)
    pub is_main: bool,
    /// True if this worktree's path matches the current working directory
    pub is_current: bool,
    /// True when git marks the worktree as locked
    pub is_locked: bool,
    /// Optional lock reason from `git worktree list --porcelain`
    pub lock_reason: Option<String>,
    /// True when git marks the worktree as prunable/stale
    pub is_prunable: bool,
    /// Optional prune reason from `git worktree list --porcelain`
    pub prunable_reason: Option<String>,
}

#[derive(Debug, Clone)]
pub enum BranchDeleteSwitchTarget {
    Branch(String),
    Detach,
}

#[derive(Debug, Clone)]
pub struct BranchDeleteResolution {
    pub worktree: WorktreeInfo,
    pub remove_worktree_selector: String,
    pub switch_target: BranchDeleteSwitchTarget,
}

impl BranchDeleteResolution {
    pub fn remove_worktree_cmd(&self) -> Option<String> {
        if self.worktree.is_main {
            None
        } else {
            Some(format!("st wt rm {}", self.remove_worktree_selector))
        }
    }

    pub fn remove_worktree_and_branch_cmd(&self) -> Option<String> {
        self.remove_worktree_cmd()
            .map(|command| format!("{command} --delete-branch"))
    }

    pub fn switch_branch_cmd(&self) -> String {
        match &self.switch_target {
            BranchDeleteSwitchTarget::Branch(target) => format!(
                "git -C '{}' switch {}",
                self.worktree.path.display(),
                target
            ),
            BranchDeleteSwitchTarget::Detach => {
                format!("git -C '{}' switch --detach", self.worktree.path.display())
            }
        }
    }
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct BranchParentMetadata {
    parent_branch_name: String,
}

impl GitRepo {
    /// Open the repository at the current directory or any parent
    pub fn open() -> Result<Self> {
        let repo = Repository::discover(".").context("Not in a git repository")?;
        Ok(Self { repo })
    }

    /// Open the repository from a known repository path without rediscovering the cwd.
    pub fn open_from_path(path: &Path) -> Result<Self> {
        let repo = Repository::open(path)
            .with_context(|| format!("Failed to open git repository at '{}'", path.display()))?;
        Ok(Self { repo })
    }

    /// Get the repository root path
    pub fn workdir(&self) -> Result<&Path> {
        self.repo
            .workdir()
            .context("Repository has no working directory")
    }

    /// Get the .git directory path
    pub fn git_dir(&self) -> Result<&Path> {
        Ok(self.repo.path())
    }

    fn run_git(&self, cwd: &Path, args: &[&str]) -> Result<Output> {
        Command::new("git")
            .args(args)
            .current_dir(cwd)
            .output()
            .with_context(|| format!("Failed to run git {}", args.join(" ")))
    }

    pub(crate) fn normalize_path(path: &Path) -> PathBuf {
        std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
    }

    fn current_branch_in_path(&self, cwd: &Path) -> Result<String> {
        let output = self.run_git(cwd, &["rev-parse", "--abbrev-ref", "HEAD"])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!(
                "git rev-parse --abbrev-ref HEAD failed in '{}': {}",
                cwd.display(),
                stderr
            );
        }

        let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if branch.is_empty() || branch == "HEAD" {
            anyhow::bail!(
                "HEAD is detached in '{}'. Please checkout a branch first.",
                cwd.display()
            );
        }
        Ok(branch)
    }

    fn git_dir_in_path(&self, cwd: &Path) -> Result<PathBuf> {
        let output = self.run_git(cwd, &["rev-parse", "--git-dir"])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!(
                "git rev-parse --git-dir failed in '{}': {}",
                cwd.display(),
                stderr
            );
        }

        let git_dir = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if git_dir.is_empty() {
            anyhow::bail!("git rev-parse --git-dir returned empty output");
        }

        let path = PathBuf::from(git_dir);
        if path.is_absolute() {
            Ok(path)
        } else {
            Ok(cwd.join(path))
        }
    }

    fn rebase_in_progress_at(&self, cwd: &Path) -> Result<bool> {
        let git_dir = self.git_dir_in_path(cwd)?;
        Ok(git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists())
    }

    pub(crate) fn is_dirty_at(&self, cwd: &Path) -> Result<bool> {
        let output = self.run_git(cwd, &["status", "--porcelain"])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git status failed in '{}': {}", cwd.display(), stderr);
        }
        Ok(!String::from_utf8_lossy(&output.stdout).trim().is_empty())
    }

    /// Count tracked files in the given worktree path.
    pub fn tracked_file_count_at(&self, cwd: &Path) -> Result<usize> {
        let output = self.run_git(cwd, &["ls-files", "-z"])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git ls-files failed in '{}': {}", cwd.display(), stderr);
        }

        Ok(output
            .stdout
            .split(|byte| *byte == 0)
            .filter(|entry| !entry.is_empty())
            .count())
    }

    pub(crate) fn stash_push_at(&self, cwd: &Path) -> Result<bool> {
        let output = self.run_git(cwd, &["stash", "push", "-u", "-m", "stax auto-stash"])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git stash failed in '{}': {}", cwd.display(), stderr);
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        if stdout.contains("No local changes") {
            return Ok(false);
        }
        Ok(true)
    }

    pub(crate) fn stash_pop_at(&self, cwd: &Path) -> Result<()> {
        let output = self.run_git(cwd, &["stash", "pop"])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git stash pop failed in '{}': {}", cwd.display(), stderr);
        }
        Ok(())
    }

    pub fn list_worktrees(&self) -> Result<Vec<WorktreeInfo>> {
        Self::list_worktrees_in(self.workdir()?)
    }

    pub fn list_worktrees_in(cwd: &Path) -> Result<Vec<WorktreeInfo>> {
        let output = run_git_in(cwd, &["worktree", "list", "--porcelain"])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git worktree list failed: {}", stderr);
        }

        let cwd = std::env::current_dir().unwrap_or_default();
        let cwd_normalized = Self::normalize_path(&cwd);

        let stdout = String::from_utf8_lossy(&output.stdout);
        #[allow(clippy::type_complexity)]
        let mut raw_entries: Vec<(
            PathBuf,
            Option<String>,
            bool,
            Option<String>,
            bool,
            Option<String>,
        )> = Vec::new();
        let mut current_path: Option<PathBuf> = None;
        let mut current_branch: Option<String> = None;
        let mut current_locked = false;
        let mut current_lock_reason: Option<String> = None;
        let mut current_prunable = false;
        let mut current_prunable_reason: Option<String> = None;

        let mut flush_entry = |path: &mut Option<PathBuf>,
                               branch: &mut Option<String>,
                               locked: &mut bool,
                               lock_reason: &mut Option<String>,
                               prunable: &mut bool,
                               prunable_reason: &mut Option<String>| {
            if let Some(p) = path.take() {
                raw_entries.push((
                    Self::normalize_path(&p),
                    branch.take(),
                    std::mem::take(locked),
                    lock_reason.take(),
                    std::mem::take(prunable),
                    prunable_reason.take(),
                ));
            }
        };

        for line in stdout.lines() {
            if line.is_empty() {
                flush_entry(
                    &mut current_path,
                    &mut current_branch,
                    &mut current_locked,
                    &mut current_lock_reason,
                    &mut current_prunable,
                    &mut current_prunable_reason,
                );
                continue;
            }

            if let Some(path) = line.strip_prefix("worktree ") {
                flush_entry(
                    &mut current_path,
                    &mut current_branch,
                    &mut current_locked,
                    &mut current_lock_reason,
                    &mut current_prunable,
                    &mut current_prunable_reason,
                );
                current_path = Some(PathBuf::from(path.trim()));
                continue;
            }

            if let Some(branch) = line.strip_prefix("branch ") {
                let branch = branch
                    .trim()
                    .strip_prefix("refs/heads/")
                    .unwrap_or(branch.trim())
                    .to_string();
                current_branch = Some(branch);
                continue;
            }

            if let Some(reason) = line.strip_prefix("locked") {
                current_locked = true;
                let reason = reason.trim();
                if !reason.is_empty() {
                    current_lock_reason = Some(reason.to_string());
                }
                continue;
            }

            if let Some(reason) = line.strip_prefix("prunable") {
                current_prunable = true;
                let reason = reason.trim();
                if !reason.is_empty() {
                    current_prunable_reason = Some(reason.to_string());
                }
            }
        }

        flush_entry(
            &mut current_path,
            &mut current_branch,
            &mut current_locked,
            &mut current_lock_reason,
            &mut current_prunable,
            &mut current_prunable_reason,
        );

        let label_candidates = raw_entries
            .iter()
            .enumerate()
            .map(|(idx, (path, branch, _, _, _, _))| WorktreeLabelCandidate {
                is_main: idx == 0,
                path: path.clone(),
                basename: if idx == 0 {
                    "main".to_string()
                } else {
                    worktree_basename(path)
                },
                branch: branch.clone(),
            })
            .collect::<Vec<_>>();
        let labels = derive_worktree_names(&label_candidates);

        let worktrees = raw_entries
            .into_iter()
            .enumerate()
            .map(
                |(idx, (path, branch, is_locked, lock_reason, is_prunable, prunable_reason))| {
                    let is_main = idx == 0;
                    let is_current = path == cwd_normalized;
                    WorktreeInfo {
                        name: labels[idx].clone(),
                        path,
                        branch,
                        is_main,
                        is_current,
                        is_locked,
                        lock_reason,
                        is_prunable,
                        prunable_reason,
                    }
                },
            )
            .collect();

        Ok(worktrees)
    }

    /// Return the absolute path to the main repo's working directory.
    /// Works correctly even when called from inside a linked worktree.
    pub fn main_repo_workdir(&self) -> Result<PathBuf> {
        let worktrees = self.list_worktrees()?;
        worktrees
            .into_iter()
            .next()
            .map(|wt| wt.path)
            .context("git worktree list returned no entries")
    }

    /// Create a new linked worktree at `path` for an existing `branch`.
    pub fn worktree_create(&self, branch: &str, path: &Path) -> Result<()> {
        let main_dir = self.main_repo_workdir()?;
        let output = self.run_git(
            &main_dir,
            &[
                "worktree",
                "add",
                path.to_str().context("Non-UTF-8 worktree path")?,
                branch,
            ],
        )?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git worktree add failed: {}", stderr);
        }
        Ok(())
    }

    /// Create a new linked worktree at `path` with a brand-new `branch` stacked on `base`.
    pub fn worktree_create_new_branch(&self, branch: &str, path: &Path, base: &str) -> Result<()> {
        let main_dir = self.main_repo_workdir()?;
        let output = self.run_git(
            &main_dir,
            &[
                "worktree",
                "add",
                "-b",
                branch,
                path.to_str().context("Non-UTF-8 worktree path")?,
                base,
            ],
        )?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git worktree add -b failed: {}", stderr);
        }
        Ok(())
    }

    /// Remove a linked worktree by path.
    pub fn worktree_remove(&self, path: &Path, force: bool) -> Result<()> {
        let main_dir = self.main_repo_workdir()?;
        let path_str = path.to_str().context("Non-UTF-8 worktree path")?;
        let args: Vec<&str> = if force {
            vec!["worktree", "remove", "--force", path_str]
        } else {
            vec!["worktree", "remove", path_str]
        };
        let output = self.run_git(&main_dir, &args)?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git worktree remove failed: {}", stderr);
        }
        Ok(())
    }

    /// Run `git worktree prune` from the main worktree.
    pub fn worktree_prune(&self) -> Result<()> {
        let main_dir = self.main_repo_workdir()?;
        let output = self.run_git(&main_dir, &["worktree", "prune"])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git worktree prune failed: {}", stderr);
        }
        Ok(())
    }

    pub fn branch_worktree(&self, branch: &str) -> Result<Option<WorktreeInfo>> {
        Self::branch_worktree_in(self.workdir()?, branch)
    }

    pub fn branch_worktree_in(cwd: &Path, branch: &str) -> Result<Option<WorktreeInfo>> {
        let branch = normalize_local_branch_name(branch);
        let worktrees = Self::list_worktrees_in(cwd)?;

        let output = run_git_in(cwd, &["branch", "-vv", "--list", branch])?;
        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            if let Some(path) = stdout.lines().find_map(parse_branch_vv_worktree_path) {
                let normalized_path = Self::normalize_path(&path);
                if let Some(worktree) = worktrees
                    .iter()
                    .find(|worktree| worktree.path == normalized_path)
                {
                    return Ok(Some(worktree.clone()));
                }
            }
        }

        Ok(worktrees.into_iter().find(|worktree| {
            worktree.branch.as_deref().map(normalize_local_branch_name) == Some(branch)
        }))
    }

    pub fn branch_worktree_path(&self, branch: &str) -> Result<Option<PathBuf>> {
        Ok(self.branch_worktree(branch)?.map(|worktree| worktree.path))
    }

    pub fn branch_delete_resolution(&self, branch: &str) -> Result<Option<BranchDeleteResolution>> {
        let branch = normalize_local_branch_name(branch);
        let Some(worktree) = self.branch_worktree(branch)? else {
            return Ok(None);
        };

        let switch_target = match self.trunk_branch() {
            Ok(trunk)
                if self
                    .branch_worktree(&trunk)?
                    .is_some_and(|target_worktree| target_worktree.path != worktree.path) =>
            {
                BranchDeleteSwitchTarget::Detach
            }
            Ok(trunk) => BranchDeleteSwitchTarget::Branch(trunk),
            Err(_) => BranchDeleteSwitchTarget::Detach,
        };

        Ok(Some(BranchDeleteResolution {
            remove_worktree_selector: worktree
                .branch
                .clone()
                .unwrap_or_else(|| worktree.path.display().to_string()),
            worktree,
            switch_target,
        }))
    }

    pub fn branch_delete_resolution_hint(&self, branch: &str) -> Result<Option<String>> {
        let Some(resolution) = self.branch_delete_resolution(branch)? else {
            return Ok(None);
        };

        let switch_cmd = resolution.switch_branch_cmd();
        let hint = if let Some(remove_cmd) = resolution.remove_worktree_cmd() {
            format!(
                "run {} to remove the linked worktree; or run {} to keep the worktree and free the branch",
                remove_cmd,
                switch_cmd
            )
        } else {
            format!(
                "run {} to free the branch in main worktree '{}'",
                switch_cmd,
                resolution.worktree.path.display()
            )
        };

        Ok(Some(hint))
    }

    /// Get the current branch name
    pub fn current_branch(&self) -> Result<String> {
        let head = self.repo.head().context("Failed to get HEAD")?;

        // Check if HEAD is detached
        if !head.is_branch() {
            anyhow::bail!(
                "HEAD is detached (not on a branch).\n\
                 Please checkout a branch first: stax checkout <branch>"
            );
        }

        let name = head
            .shorthand()
            .context("HEAD is not a branch")?
            .to_string();
        Ok(name)
    }

    /// Get all local branch names
    pub fn list_branches(&self) -> Result<Vec<String>> {
        let branches = self.repo.branches(Some(BranchType::Local))?;
        let mut names = Vec::new();
        for branch in branches {
            let (branch, _) = branch?;
            if let Some(name) = branch.name()? {
                names.push(name.to_string());
            }
        }
        Ok(names)
    }

    /// Get the commit SHA for a branch
    pub fn branch_commit(&self, branch: &str) -> Result<String> {
        let reference = self
            .repo
            .find_branch(branch, BranchType::Local)
            .with_context(|| format!("Branch '{}' not found", branch))?;
        let commit = reference.get().peel_to_commit()?;
        Ok(commit.id().to_string())
    }

    /// Get commits ahead/behind between two branches (uses libgit2, no subprocess)
    pub fn commits_ahead_behind(&self, base: &str, head: &str) -> Result<(usize, usize)> {
        let base_oid = self.resolve_to_oid(base)?;
        let head_oid = self.resolve_to_oid(head)?;
        let (ahead, behind) = self.repo.graph_ahead_behind(head_oid, base_oid)?;
        Ok((ahead, behind))
    }

    /// Get commit messages between base and head (commits on head not in base)
    pub fn commits_between(&self, base: &str, head: &str) -> Result<Vec<String>> {
        let base_oid = self.resolve_to_oid(base)?;
        let head_oid = self.resolve_to_oid(head)?;

        let mut revwalk = self.repo.revwalk()?;
        revwalk.push(head_oid)?;
        revwalk.hide(base_oid)?;

        let mut commits = Vec::new();
        for oid in revwalk {
            let oid = oid?;
            if let Ok(commit) = self.repo.find_commit(oid) {
                if let Some(msg) = commit.summary() {
                    commits.push(msg.to_string());
                }
            }
        }

        Ok(commits)
    }

    /// Resolve any ref (local branch, remote branch, SHA) to a commit SHA string.
    /// Useful for resolving refs like "origin/main" to their current commit.
    pub fn resolve_ref(&self, refspec: &str) -> Result<String> {
        let oid = self.resolve_to_oid(refspec)?;
        Ok(oid.to_string())
    }

    /// Resolve a branch name or ref to an OID
    fn resolve_to_oid(&self, refspec: &str) -> Result<git2::Oid> {
        // Try as local branch first
        if let Ok(branch) = self.repo.find_branch(refspec, BranchType::Local) {
            if let Some(oid) = branch.get().target() {
                return Ok(oid);
            }
        }
        // Try as remote branch (e.g., "origin/main")
        if let Ok(branch) = self.repo.find_branch(refspec, BranchType::Remote) {
            if let Some(oid) = branch.get().target() {
                return Ok(oid);
            }
        }
        // Try as reference
        if let Ok(reference) = self.repo.find_reference(refspec) {
            if let Some(oid) = reference.target() {
                return Ok(oid);
            }
        }
        // Try revparse
        let obj = self.repo.revparse_single(refspec)?;
        Ok(obj.id())
    }

    /// Get the trunk branch name (from stored setting or auto-detect main/master)
    pub fn trunk_branch(&self) -> Result<String> {
        // First check if trunk is stored
        if let Some(trunk) = super::refs::read_trunk(&self.repo)? {
            // Validate the stored trunk branch actually exists locally
            if self.repo.find_branch(&trunk, BranchType::Local).is_ok() {
                return Ok(trunk);
            }
            // Stored trunk doesn't exist, fall through to auto-detection
        }
        // Fall back to auto-detection and persist the result
        let detected = self.detect_trunk()?;
        super::refs::write_trunk(&self.repo, &detected)?;
        Ok(detected)
    }

    /// Auto-detect trunk branch (main or master)
    pub fn detect_trunk(&self) -> Result<String> {
        for name in ["main", "master"] {
            if self.repo.find_branch(name, BranchType::Local).is_ok() {
                return Ok(name.to_string());
            }
        }
        anyhow::bail!("No trunk branch (main/master) found")
    }

    /// Check if stax has been initialized in this repo
    pub fn is_initialized(&self) -> bool {
        super::refs::is_initialized(&self.repo)
    }

    /// Check if working tree has uncommitted changes
    pub fn is_dirty(&self) -> Result<bool> {
        self.is_dirty_at(self.workdir()?)
    }

    /// Stash local changes (including untracked)
    pub fn stash_push(&self) -> Result<bool> {
        self.stash_push_at(self.workdir()?)
    }

    /// Pop the most recent stash
    pub fn stash_pop(&self) -> Result<()> {
        self.stash_pop_at(self.workdir()?)
    }

    /// Set the trunk branch
    pub fn set_trunk(&self, trunk: &str) -> Result<()> {
        super::refs::write_trunk(&self.repo, trunk)
    }

    /// Checkout a branch
    pub fn checkout(&self, branch: &str) -> Result<()> {
        let output = self.run_git(self.workdir()?, &["checkout", branch])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git checkout {} failed: {}", branch, stderr);
        }
        Ok(())
    }

    /// Fetch a remote and return whether the fetch succeeded.
    pub fn fetch_remote(&self, remote: &str) -> Result<bool> {
        let output = self.run_git(self.workdir()?, &["fetch", remote])?;
        Ok(output.status.success())
    }

    fn rebase_with_args_in_path(&self, cwd: &Path, args: &[&str]) -> Result<RebaseResult> {
        let output = self.run_git(cwd, args)?;
        if output.status.success() {
            return Ok(RebaseResult::Success);
        }

        if self.rebase_in_progress_at(cwd)? {
            return Ok(RebaseResult::Conflict);
        }

        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
        anyhow::bail!(
            "git {} failed in '{}': {}",
            args.join(" "),
            cwd.display(),
            stderr
        );
    }

    fn rebase_in_path(&self, cwd: &Path, onto: &str) -> Result<RebaseResult> {
        self.rebase_with_args_in_path(cwd, &["rebase", onto])
    }

    fn rebase_onto_upstream_in_path(
        &self,
        cwd: &Path,
        onto: &str,
        upstream: &str,
    ) -> Result<RebaseResult> {
        self.rebase_with_args_in_path(cwd, &["rebase", "--onto", onto, upstream])
    }

    /// Resolve the worktree path where a branch rebase would run.
    /// Returns the linked worktree path if one exists, otherwise the main workdir.
    pub(crate) fn branch_rebase_target_workdir(&self, branch: &str) -> Result<PathBuf> {
        let current_workdir = Self::normalize_path(self.workdir()?);
        let target_workdir = self
            .branch_worktree_path(branch)?
            .unwrap_or_else(|| current_workdir.clone());
        let target_workdir = Self::normalize_path(&target_workdir);

        if target_workdir != current_workdir {
            let current_in_target = self.current_branch_in_path(&target_workdir)?;
            if current_in_target != branch {
                anyhow::bail!(
                    "Expected '{}' in '{}', found '{}' instead.",
                    branch,
                    target_workdir.display(),
                    current_in_target
                );
            }
        }

        Ok(target_workdir)
    }

    fn prepare_branch_rebase_context(&self, branch: &str) -> Result<(PathBuf, PathBuf)> {
        let current_workdir = Self::normalize_path(self.workdir()?);
        let target_workdir = self.branch_rebase_target_workdir(branch)?;

        if target_workdir == current_workdir && self.current_branch()? != branch {
            self.checkout(branch)?;
        }

        Ok((current_workdir, target_workdir))
    }

    fn run_patch_id_from_input(&self, cwd: &Path, input: &[u8]) -> Result<Vec<String>> {
        let mut patch_id = Command::new("git")
            .args(["patch-id", "--stable"])
            .current_dir(cwd)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .context("Failed to run git patch-id --stable")?;

        // Write stdin on a background thread to avoid a deadlock: git patch-id
        // buffers output as it reads input. If its stdout pipe fills up before
        // we start reading stdout, both processes stall (git patch-id can't
        // write, so it stops reading, so write_all blocks forever). Spawning a
        // writer thread lets us drain stdout on the main thread concurrently.
        let input = input.to_vec();
        let mut stdin = patch_id.stdin.take().context("Failed to open stdin")?;
        let writer = std::thread::spawn(move || -> std::io::Result<()> {
            stdin.write_all(&input)?;
            // Drop stdin here so git patch-id sees EOF and flushes output.
            Ok(())
        });

        let output = patch_id
            .wait_with_output()
            .context("Failed to read git patch-id output")?;

        writer
            .join()
            .map_err(|_| anyhow::anyhow!("stdin writer thread panicked"))?
            .context("Failed to write to git patch-id stdin")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git patch-id --stable failed: {}", stderr);
        }

        Ok(String::from_utf8_lossy(&output.stdout)
            .lines()
            .filter_map(|line| line.split_whitespace().next())
            .map(ToString::to_string)
            .collect())
    }

    fn rev_list_reverse_range(&self, cwd: &Path, range: &str) -> Result<Vec<String>> {
        let output = self.run_git(cwd, &["rev-list", "--reverse", "--no-merges", range])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!(
                "git rev-list --reverse --no-merges {} failed: {}",
                range,
                stderr
            );
        }

        Ok(String::from_utf8_lossy(&output.stdout)
            .lines()
            .map(str::trim)
            .filter(|line| !line.is_empty())
            .map(ToString::to_string)
            .collect())
    }

    /// Max commits in `merge_base..trunk` for patch-id provenance; beyond this we skip the
    /// expensive `git log -p` path (see sync merged-branch detection).
    pub(crate) const PATCH_ID_TRUNK_COMMIT_CAP: usize = 200;

    pub(crate) fn rev_list_count(&self, cwd: &Path, range: &str) -> Result<usize> {
        let output = self.run_git(cwd, &["rev-list", "--count", range])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git rev-list --count {} failed: {}", range, stderr);
        }
        Ok(String::from_utf8_lossy(&output.stdout)
            .trim()
            .parse()
            .unwrap_or(0))
    }

    pub(crate) fn patch_ids_for_range(&self, cwd: &Path, range: &str) -> Result<HashSet<String>> {
        let output = self.run_git(cwd, &["log", "--format=%H", "-p", "--no-merges", range])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!(
                "git log --format=%H -p --no-merges {} failed: {}",
                range,
                stderr
            );
        }

        Ok(self
            .run_patch_id_from_input(cwd, &output.stdout)?
            .into_iter()
            .collect())
    }

    fn patch_id_for_commit(&self, cwd: &Path, commit: &str) -> Result<Option<String>> {
        let output = self.run_git(
            cwd,
            &[
                "show",
                "--no-color",
                "--pretty=format:",
                "--no-ext-diff",
                commit,
            ],
        )?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git show {} failed: {}", commit, stderr);
        }

        Ok(self
            .run_patch_id_from_input(cwd, &output.stdout)?
            .into_iter()
            .next())
    }

    fn infer_patch_id_upstream(
        &self,
        cwd: &Path,
        branch: &str,
        onto: &str,
        fallback_upstream: &str,
    ) -> Result<Option<String>> {
        if fallback_upstream.trim().is_empty() {
            return Ok(None);
        }

        if !self.is_ancestor(fallback_upstream, branch)? {
            return Ok(None);
        }

        let branch_range = format!("{}..{}", fallback_upstream, branch);
        let branch_commits = self.rev_list_reverse_range(cwd, &branch_range)?;
        if branch_commits.len() < 2 {
            return Ok(None);
        }

        let merge_base = match self.merge_base_refs(onto, branch) {
            Ok(base) => base,
            Err(_) => return Ok(None),
        };
        let onto_range = format!("{}..{}", merge_base, onto);
        let onto_patch_ids = self.patch_ids_for_range(cwd, &onto_range)?;
        if onto_patch_ids.is_empty() {
            return Ok(None);
        }

        let mut integrated_prefix = 0usize;
        for commit in &branch_commits {
            let Some(patch_id) = self.patch_id_for_commit(cwd, commit)? else {
                break;
            };
            if onto_patch_ids.contains(&patch_id) {
                integrated_prefix += 1;
            } else {
                break;
            }
        }

        if integrated_prefix == 0 || integrated_prefix >= branch_commits.len() {
            return Ok(None);
        }

        Ok(Some(branch_commits[integrated_prefix - 1].clone()))
    }

    /// Infer a precise upstream marker for `git rebase --onto` based on patch-id provenance.
    #[allow(dead_code)] // Exposed for tests and future diagnostics surfaces.
    pub fn infer_rebase_upstream_by_patch_id(
        &self,
        branch: &str,
        onto: &str,
        fallback_upstream: &str,
    ) -> Result<String> {
        let workdir = self.workdir()?;
        Ok(self
            .infer_patch_id_upstream(workdir, branch, onto, fallback_upstream)?
            .unwrap_or_else(|| fallback_upstream.to_string()))
    }

    /// Rebase a branch onto `onto` while preserving provenance from `fallback_upstream`.
    ///
    /// If patch-id analysis identifies a prefix already integrated into `onto`, this uses
    /// `git rebase --onto <onto> <adjusted-upstream>` to replay only novel commits.
    pub fn rebase_branch_onto_with_provenance(
        &self,
        branch: &str,
        onto: &str,
        fallback_upstream: &str,
        auto_stash_pop: bool,
    ) -> Result<RebaseResult> {
        let (_current_workdir, target_workdir) = self.prepare_branch_rebase_context(branch)?;

        let mut stashed = false;
        if self.is_dirty_at(&target_workdir)? {
            if !auto_stash_pop {
                anyhow::bail!(
                    "Cannot restack '{}': worktree '{}' has uncommitted changes. \
Use --auto-stash-pop or stash/commit changes first.",
                    branch,
                    target_workdir.display()
                );
            }
            stashed = self.stash_push_at(&target_workdir)?;
        }

        let can_use_fallback_upstream = !fallback_upstream.trim().is_empty()
            && self.is_ancestor(fallback_upstream, branch).unwrap_or(false);
        let inferred_upstream = self
            .infer_patch_id_upstream(&target_workdir, branch, onto, fallback_upstream)
            .unwrap_or(None);
        let upstream_for_rebase = if can_use_fallback_upstream {
            Some(inferred_upstream.unwrap_or_else(|| fallback_upstream.to_string()))
        } else {
            None
        };

        let rebase_result = if let Some(upstream) = upstream_for_rebase.as_deref() {
            self.rebase_onto_upstream_in_path(&target_workdir, onto, upstream)
                .with_context(|| {
                    format!(
                        "Failed to rebase '{}' onto '{}' with upstream '{}' in '{}'",
                        branch,
                        onto,
                        upstream,
                        target_workdir.display()
                    )
                })
        } else {
            self.rebase_in_path(&target_workdir, onto).with_context(|| {
                format!(
                    "Failed to rebase '{}' onto '{}' in '{}'",
                    branch,
                    onto,
                    target_workdir.display()
                )
            })
        };

        let result = match rebase_result {
            Ok(result) => result,
            Err(err) => {
                if stashed {
                    return Err(err.context(format!(
                        "Auto-stash was kept in '{}' due to rebase failure.",
                        target_workdir.display()
                    )));
                }
                return Err(err);
            }
        };

        if stashed && result == RebaseResult::Success {
            self.stash_pop_at(&target_workdir).with_context(|| {
                format!(
                    "Rebased '{}' successfully, but failed to auto-pop stash in '{}'",
                    branch,
                    target_workdir.display()
                )
            })?;
        }

        Ok(result)
    }

    /// Rebase current branch onto target
    #[allow(dead_code)] // Kept for compatibility with existing APIs and future command flows
    pub fn rebase(&self, onto: &str) -> Result<RebaseResult> {
        self.rebase_in_path(self.workdir()?, onto)
    }

    /// Rebase the target branch onto another branch, using the branch's owning worktree.
    /// If the target branch is not checked out in any worktree, it falls back to current workdir.
    pub fn rebase_branch_onto(
        &self,
        branch: &str,
        onto: &str,
        auto_stash_pop: bool,
    ) -> Result<RebaseResult> {
        self.rebase_branch_onto_with_provenance(branch, onto, "", auto_stash_pop)
    }

    /// Continue a rebase after resolving conflicts
    pub fn rebase_continue(&self) -> Result<RebaseResult> {
        let status = Command::new("git")
            .args(["rebase", "--continue"])
            .env("GIT_EDITOR", "true")
            .current_dir(self.workdir()?)
            .status()
            .context("Failed to run git rebase --continue")?;

        if status.success() {
            Ok(RebaseResult::Success)
        } else if self.rebase_in_progress()? {
            Ok(RebaseResult::Conflict)
        } else {
            anyhow::bail!("git rebase --continue failed")
        }
    }

    /// Check if a rebase is in progress
    pub fn rebase_in_progress(&self) -> Result<bool> {
        self.rebase_in_progress_at(self.workdir()?)
    }

    /// Check whether a rebase is in progress inside the given worktree path.
    pub fn rebase_in_progress_in(&self, cwd: &Path) -> Result<bool> {
        self.rebase_in_progress_at(cwd)
    }

    /// Check whether a merge is in progress inside the given worktree path.
    pub fn merge_in_progress_in(&self, cwd: &Path) -> Result<bool> {
        let git_dir = self.git_dir_in_path(cwd)?;
        Ok(git_dir.join("MERGE_HEAD").exists())
    }

    /// Check whether the given worktree path currently has unresolved conflicts.
    pub fn has_conflicts_in(&self, cwd: &Path) -> Result<bool> {
        let output = self.run_git(cwd, &["diff", "--name-only", "--diff-filter=U"])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git diff --name-only --diff-filter=U failed: {}", stderr);
        }
        Ok(!String::from_utf8_lossy(&output.stdout).trim().is_empty())
    }

    /// Create a new branch at HEAD
    pub fn create_branch(&self, name: &str) -> Result<()> {
        let head = self.repo.head()?;
        let commit = head.peel_to_commit()?;
        self.repo.branch(name, &commit, false)?;
        Ok(())
    }

    /// Create a new branch from another local branch
    pub fn create_branch_at(&self, name: &str, base_branch: &str) -> Result<()> {
        let reference = self
            .repo
            .find_branch(base_branch, BranchType::Local)
            .with_context(|| format!("Branch '{}' not found", base_branch))?;
        let commit = reference.get().peel_to_commit()?;
        self.repo.branch(name, &commit, false)?;
        Ok(())
    }

    /// Create a new branch at a specific commit SHA
    pub fn create_branch_at_commit(&self, name: &str, commit_sha: &str) -> Result<()> {
        let oid = git2::Oid::from_str(commit_sha)
            .with_context(|| format!("Invalid commit SHA: {}", commit_sha))?;
        let commit = self
            .repo
            .find_commit(oid)
            .with_context(|| format!("Commit '{}' not found", commit_sha))?;
        self.repo.branch(name, &commit, false)?;
        Ok(())
    }

    /// Find merge-base commit between two local branches
    pub fn merge_base(&self, left: &str, right: &str) -> Result<String> {
        let left_commit = self
            .repo
            .find_branch(left, BranchType::Local)?
            .get()
            .peel_to_commit()?;
        let right_commit = self
            .repo
            .find_branch(right, BranchType::Local)?
            .get()
            .peel_to_commit()?;

        let base = self.repo.merge_base(left_commit.id(), right_commit.id())?;
        Ok(base.to_string())
    }

    /// Find merge-base commit between any two refs (branch names, remote refs, or SHAs).
    pub fn merge_base_refs(&self, left: &str, right: &str) -> Result<String> {
        let left_oid = self.resolve_to_oid(left)?;
        let right_oid = self.resolve_to_oid(right)?;
        Ok(self.repo.merge_base(left_oid, right_oid)?.to_string())
    }

    /// Check whether `ancestor` is an ancestor of `descendant`.
    pub fn is_ancestor(&self, ancestor: &str, descendant: &str) -> Result<bool> {
        let ancestor_oid = self.resolve_to_oid(ancestor)?;
        let descendant_oid = self.resolve_to_oid(descendant)?;
        if ancestor_oid == descendant_oid {
            return Ok(true);
        }
        Ok(self
            .repo
            .graph_descendant_of(descendant_oid, ancestor_oid)?)
    }

    /// Delete a branch
    pub fn delete_branch(&self, name: &str, force: bool) -> Result<()> {
        let name = normalize_local_branch_name(name);
        if let Some(hint) = self.branch_delete_resolution_hint(name)? {
            anyhow::bail!(
                "Cannot delete branch '{}' because it is currently checked out in a linked worktree. To fix it, {}.",
                name,
                hint
            );
        }

        if !force {
            let branch = self.repo.find_branch(name, BranchType::Local)?;
            let branch_commit = branch.get().peel_to_commit()?;
            let mut candidate_bases = vec![self.trunk_branch()?];

            if let Ok(Some(json)) = crate::git::refs::read_metadata(&self.repo, name) {
                if let Ok(meta) = serde_json::from_str::<BranchParentMetadata>(&json) {
                    if meta.parent_branch_name != name
                        && !candidate_bases.contains(&meta.parent_branch_name)
                    {
                        candidate_bases.insert(0, meta.parent_branch_name);
                    }
                }
            }

            let merged_into_any_base = candidate_bases.into_iter().any(|base| {
                let Ok(base_branch) = self.repo.find_branch(&base, BranchType::Local) else {
                    return false;
                };
                let Ok(base_commit) = base_branch.get().peel_to_commit() else {
                    return false;
                };
                self.repo
                    .merge_base(base_commit.id(), branch_commit.id())
                    .map(|base_oid| base_oid == branch_commit.id())
                    .unwrap_or(false)
            });

            if !merged_into_any_base {
                anyhow::bail!(
                    "Branch '{}' is not merged. Use --force to delete anyway.",
                    name
                );
            }
        }

        // Use git CLI instead of libgit2's branch.delete() to avoid issues
        // with config cleanup on branch names containing slashes
        let flag = if force { "-D" } else { "-d" };
        let output = self.run_git(self.workdir()?, &["branch", flag, name])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("Failed to delete branch '{}': {}", name, stderr.trim());
        }
        Ok(())
    }

    /// Read an optional user-defined worktree marker for a branch from git config.
    pub fn worktree_marker(&self, branch: &str) -> Option<String> {
        let key = format!(
            "stax.worktree-marker.{}",
            branch
                .chars()
                .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
                .collect::<String>()
        );
        self.repo
            .config()
            .ok()
            .and_then(|cfg| cfg.get_string(&key).ok())
            .filter(|value| !value.trim().is_empty())
    }

    /// Get underlying repository (for advanced operations)
    pub fn inner(&self) -> &Repository {
        &self.repo
    }

    /// Get commits unique to a branch (not in parent)
    pub fn branch_commits(&self, branch: &str, parent: Option<&str>) -> Result<Vec<CommitInfo>> {
        let branch_ref = self.repo.find_branch(branch, BranchType::Local)?;
        let branch_commit = branch_ref.get().peel_to_commit()?;

        let mut commits = Vec::new();
        let mut revwalk = self.repo.revwalk()?;
        revwalk.push(branch_commit.id())?;

        // If parent specified, exclude its commits
        if let Some(parent_name) = parent {
            if let Ok(parent_ref) = self.repo.find_branch(parent_name, BranchType::Local) {
                if let Ok(parent_commit) = parent_ref.get().peel_to_commit() {
                    revwalk.hide(parent_commit.id())?;
                }
            }
        }

        for oid in revwalk.take(5) {
            // Max 5 commits
            let oid = oid?;
            let commit = self.repo.find_commit(oid)?;
            let message = commit.summary().unwrap_or("").to_string();
            let short_id = &oid.to_string()[..10];
            commits.push(CommitInfo {
                short_hash: short_id.to_string(),
                message,
            });
        }

        Ok(commits)
    }

    /// Get time since last commit on a branch
    pub fn branch_age(&self, branch: &str) -> Result<String> {
        let branch_ref = self.repo.find_branch(branch, BranchType::Local)?;
        let commit = branch_ref.get().peel_to_commit()?;
        let time = commit.time();
        let commit_ts = time.seconds();
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;
        let diff = now - commit_ts;

        Ok(format_duration(diff))
    }

    /// Get recent commits on a branch within the last N hours
    /// Returns (branch_name, commit_count, most_recent_age)
    pub fn recent_branch_activity(
        &self,
        branch: &str,
        hours: i64,
    ) -> Result<Option<(usize, String)>> {
        let workdir = self.workdir()?;
        let since_arg = format!("--since={} hours ago", hours);

        let output = Command::new("git")
            .args(["log", &since_arg, "--oneline", branch])
            .current_dir(workdir)
            .output()
            .context("Failed to run git log")?;

        if !output.status.success() {
            return Ok(None);
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let commit_count = stdout.lines().filter(|l| !l.is_empty()).count();

        if commit_count == 0 {
            return Ok(None);
        }

        // Get the age of the most recent commit
        let age = self.branch_age(branch).ok();

        Ok(Some((
            commit_count,
            age.unwrap_or_else(|| "recently".to_string()),
        )))
    }

    /// Check if a branch is merged into trunk
    pub fn is_branch_merged(&self, branch: &str) -> Result<bool> {
        let trunk = self.trunk_branch()?;
        let trunk_commit = self
            .repo
            .find_branch(&trunk, BranchType::Local)?
            .get()
            .peel_to_commit()?;
        let branch_commit = self
            .repo
            .find_branch(branch, BranchType::Local)?
            .get()
            .peel_to_commit()?;

        // Branch is merged if its commit is an ancestor of trunk
        Ok(self
            .repo
            .merge_base(trunk_commit.id(), branch_commit.id())?
            == branch_commit.id())
    }

    /// Cheap merge-equivalence checks only (ancestor + identical tree). Returns `Some(())` if
    /// merged by those signals, `None` if patch-id provenance may still be needed.
    pub fn is_branch_merged_cheap(&self, branch: &str) -> Result<Option<()>> {
        if self.is_branch_merged(branch).unwrap_or(false) {
            return Ok(Some(()));
        }

        let trunk = self.trunk_branch()?;

        // Tree-level diff: if the trees are identical the branch is fully merged,
        // regardless of how many commits were squashed.
        if self.refs_have_no_diff(&trunk, branch)? {
            return Ok(Some(()));
        }

        Ok(None)
    }

    /// Return true when two refs have no content diff.
    /// Check whether a branch is merged-equivalent to trunk.
    ///
    /// Uses multiple strategies in order:
    /// 1. Ancestor check (`git branch --merged`)
    /// 2. Tree-level diff (`git diff --quiet`) — catches multi-commit squash merges
    ///    when trunk hasn't diverged
    /// 3. Patch-id provenance — catches single-commit squash/cherry-pick merges even
    ///    after trunk has advanced with unrelated commits
    pub fn is_branch_merged_equivalent_to_trunk(&self, branch: &str) -> Result<bool> {
        if self.is_branch_merged_cheap(branch)?.is_some() {
            return Ok(true);
        }

        let trunk = self.trunk_branch()?;

        // Patch-id provenance: handles the case where trunk has advanced past the
        // merge point with unrelated commits (tree diff would show false negatives).
        let merge_base = match self.merge_base(&trunk, branch) {
            Ok(base) => base,
            Err(_) => return Ok(false),
        };

        let cwd = self.workdir()?;
        let branch_range = format!("{}..{}", merge_base, branch);
        let branch_patch_ids = self.patch_ids_for_range(cwd, &branch_range)?;
        if branch_patch_ids.is_empty() {
            return Ok(true);
        }

        let trunk_range = format!("{}..{}", merge_base, trunk);
        let trunk_count = self.rev_list_count(cwd, &trunk_range)?;
        if trunk_count > Self::PATCH_ID_TRUNK_COMMIT_CAP {
            return Ok(false);
        }

        let trunk_patch_ids = self.patch_ids_for_range(cwd, &trunk_range)?;
        if trunk_patch_ids.is_empty() {
            return Ok(false);
        }

        Ok(branch_patch_ids.is_subset(&trunk_patch_ids))
    }

    /// Return true when two refs have identical trees (no content diff).
    fn refs_have_no_diff(&self, left: &str, right: &str) -> Result<bool> {
        let output = self.run_git(self.workdir()?, &["diff", "--quiet", left, right])?;
        match output.status.code() {
            Some(0) => Ok(true),
            Some(1) => Ok(false),
            _ => {
                let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
                anyhow::bail!("git diff --quiet {} {} failed: {}", left, right, stderr)
            }
        }
    }

    /// Check if a branch has a remote tracking branch (origin/<branch>)
    pub fn has_remote(&self, branch: &str) -> bool {
        let remote_name = format!("origin/{}", branch);
        self.repo
            .find_branch(&remote_name, BranchType::Remote)
            .is_ok()
    }

    /// Return all branch names under `refs/remotes/<remote>/` as a set.
    /// One libgit2 ref-glob instead of one subprocess per branch.
    pub fn remote_branch_names(&self, remote: &str) -> Result<HashSet<String>> {
        let prefix = format!("refs/remotes/{}/", remote);
        let refs = self
            .repo
            .references_glob(&format!("{}*", prefix))
            .context("Failed to glob remote refs")?;
        let mut names = HashSet::new();
        for r in refs.flatten() {
            if let Some(name) = r.name() {
                if let Some(branch) = name.strip_prefix(&prefix) {
                    names.insert(branch.to_string());
                }
            }
        }
        Ok(names)
    }

    /// Get commits ahead/behind compared to remote tracking branch (origin/branch)
    /// Returns (unpushed, unpulled) or None if no remote tracking branch exists
    pub fn commits_vs_remote(&self, branch: &str) -> Option<(usize, usize)> {
        let remote_name = format!("origin/{}", branch);
        if self
            .repo
            .find_branch(&remote_name, BranchType::Remote)
            .is_ok()
        {
            self.commits_ahead_behind(&remote_name, branch).ok()
        } else {
            None
        }
    }

    /// Get diff between a branch and its parent
    pub fn diff_against_parent(&self, branch: &str, parent: &str) -> Result<Vec<String>> {
        // Use merge-base diff (A...B) to match PR semantics and avoid showing unrelated
        // parent-side changes when the parent branch has advanced.
        let range = format!("{}...{}", parent, branch);
        let output = Command::new("git")
            .args(["diff", "--color=never", &range])
            .current_dir(self.workdir()?)
            .output()
            .context("Failed to get diff")?;

        if !output.status.success() {
            return Ok(Vec::new());
        }

        let diff = String::from_utf8_lossy(&output.stdout);
        Ok(diff.lines().map(|s| s.to_string()).collect())
    }

    /// Get diff stat (numstat) between a branch and its parent
    pub fn diff_stat(&self, branch: &str, parent: &str) -> Result<Vec<(String, usize, usize)>> {
        let range = format!("{}...{}", parent, branch);
        let output = Command::new("git")
            .args(["diff", "--numstat", &range])
            .current_dir(self.workdir()?)
            .output()
            .context("Failed to get diff stat")?;

        if !output.status.success() {
            return Ok(Vec::new());
        }

        let stat = String::from_utf8_lossy(&output.stdout);
        let mut results = Vec::new();

        for line in stat.lines() {
            let parts: Vec<&str> = line.split('\t').collect();
            if parts.len() >= 3 {
                let additions = parts[0].parse().unwrap_or(0);
                let deletions = parts[1].parse().unwrap_or(0);
                let file = parts[2].to_string();
                results.push((file, additions, deletions));
            }
        }

        Ok(results)
    }

    /// Get all branches that are merged into trunk (excluding trunk itself)
    pub fn merged_branches(&self) -> Result<Vec<String>> {
        let trunk = self.trunk_branch()?;
        let current = self.current_branch()?;
        let all_branches = self.list_branches()?;

        let mut merged = Vec::new();
        for branch in all_branches {
            if branch == trunk || branch == current {
                continue;
            }
            if self
                .is_branch_merged_equivalent_to_trunk(&branch)
                .unwrap_or(false)
            {
                merged.push(branch);
            }
        }
        Ok(merged)
    }

    /// Check if rebasing a branch onto target would produce conflicts
    /// Uses git merge-tree to detect potential conflicts without actually rebasing
    /// Returns a list of files that would have conflicts
    pub fn check_rebase_conflicts(&self, branch: &str, onto: &str) -> Result<Vec<String>> {
        // Get the merge base between the branch and onto target
        let merge_base = match self.merge_base(onto, branch) {
            Ok(base) => base,
            Err(_) => return Ok(Vec::new()),
        };

        // Use git merge-tree to check for conflicts
        // git merge-tree --write-tree <base> <onto> <branch>
        let output = Command::new("git")
            .args([
                "merge-tree",
                "--write-tree",
                "--no-messages",
                &merge_base,
                onto,
                branch,
            ])
            .current_dir(self.workdir()?)
            .output()
            .context("Failed to run git merge-tree")?;

        // If the command fails (non-zero exit), there are conflicts
        // The output will contain the conflicting files
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);

            // Parse conflict information from output
            let mut conflict_files = Vec::new();

            // The output format typically shows conflicting files
            for line in stdout.lines().chain(stderr.lines()) {
                // Look for lines indicating conflicts (file paths in merge conflicts)
                if line.contains("CONFLICT") {
                    // Extract filename from conflict message
                    // Format: "CONFLICT (content): Merge conflict in <file>"
                    if let Some(file) = line.split("Merge conflict in ").nth(1) {
                        conflict_files.push(file.trim().to_string());
                    } else if let Some(file) = line.split("CONFLICT (").nth(1) {
                        // Other conflict formats
                        if let Some(f) = file.split("):").nth(1) {
                            conflict_files.push(f.trim().to_string());
                        }
                    }
                }
            }

            return Ok(conflict_files);
        }

        Ok(Vec::new())
    }

    /// Predict conflicts for multiple branches before restacking.
    /// Returns only branches that would have conflicts.
    pub fn predict_restack_conflicts(
        &self,
        branches_with_parents: &[(String, String)],
    ) -> Vec<ConflictPrediction> {
        branches_with_parents
            .iter()
            .filter_map(
                |(branch, parent)| match self.check_rebase_conflicts(branch, parent) {
                    Ok(files) if !files.is_empty() => Some(ConflictPrediction {
                        branch: branch.clone(),
                        onto: parent.clone(),
                        conflicting_files: files,
                    }),
                    _ => None,
                },
            )
            .collect()
    }

    /// Get files modified in a branch compared to its parent
    #[allow(dead_code)] // Reserved for future conflict detection improvements
    pub fn files_modified(&self, branch: &str, parent: &str) -> Result<Vec<String>> {
        let output = Command::new("git")
            .args(["diff", "--name-only", parent, branch])
            .current_dir(self.workdir()?)
            .output()
            .context("Failed to get modified files")?;

        if !output.status.success() {
            return Ok(Vec::new());
        }

        let files = String::from_utf8_lossy(&output.stdout);
        Ok(files.lines().map(|s| s.to_string()).collect())
    }

    /// Check for overlapping files between two branches that could cause conflicts
    #[allow(dead_code)] // Reserved for future conflict detection improvements
    pub fn check_overlapping_files(
        &self,
        branch1: &str,
        branch2: &str,
        common_parent: &str,
    ) -> Result<Vec<String>> {
        let files1 = self.files_modified(branch1, common_parent)?;
        let files2 = self.files_modified(branch2, common_parent)?;

        let files1_set: std::collections::HashSet<_> = files1.into_iter().collect();
        let overlapping: Vec<String> = files2
            .into_iter()
            .filter(|f| files1_set.contains(f))
            .collect();

        Ok(overlapping)
    }

    /// Abort an in-progress rebase
    pub fn rebase_abort(&self) -> Result<()> {
        if !self.rebase_in_progress()? {
            return Ok(());
        }

        let status = Command::new("git")
            .args(["rebase", "--abort"])
            .current_dir(self.workdir()?)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .context("Failed to run git rebase --abort")?;

        if !status.success() {
            anyhow::bail!("git rebase --abort failed");
        }
        Ok(())
    }

    /// List files currently in an unmerged (conflicted) state.
    pub fn conflicted_files(&self) -> Result<Vec<String>> {
        let output = self.run_git(self.workdir()?, &["diff", "--name-only", "--diff-filter=U"])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!("git diff --name-only --diff-filter=U failed: {}", stderr);
        }

        Ok(String::from_utf8_lossy(&output.stdout)
            .lines()
            .map(str::trim)
            .filter(|line| !line.is_empty())
            .map(ToString::to_string)
            .collect())
    }

    /// List paths currently modified, staged, unmerged, or untracked.
    pub fn changed_files(&self) -> Result<Vec<String>> {
        let output = self.run_git(
            self.workdir()?,
            &["status", "--porcelain", "--untracked-files=all"],
        )?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            anyhow::bail!(
                "git status --porcelain --untracked-files=all failed: {}",
                stderr
            );
        }

        let mut seen = HashSet::new();
        let mut files = Vec::new();
        for line in String::from_utf8_lossy(&output.stdout).lines() {
            if line.len() < 4 {
                continue;
            }
            let mut path = line[3..].trim().to_string();
            if path.is_empty() {
                continue;
            }

            if let Some((_, new_path)) = path.rsplit_once(" -> ") {
                path = new_path.to_string();
            }

            if seen.insert(path.clone()) {
                files.push(path);
            }
        }

        Ok(files)
    }

    /// Stage an explicit list of files.
    pub fn add_files(&self, paths: &[String]) -> Result<()> {
        if paths.is_empty() {
            return Ok(());
        }

        let status = Command::new("git")
            .arg("add")
            .arg("--")
            .args(paths)
            .current_dir(self.workdir()?)
            .status()
            .context("Failed to run git add")?;

        if !status.success() {
            anyhow::bail!("git add failed");
        }

        Ok(())
    }

    /// Update a ref to point to a specific OID
    pub fn update_ref(&self, refname: &str, oid: &str) -> Result<()> {
        let status = Command::new("git")
            .args(["update-ref", refname, oid])
            .current_dir(self.workdir()?)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .context("Failed to run git update-ref")?;

        if !status.success() {
            anyhow::bail!("git update-ref {} {} failed", refname, oid);
        }
        Ok(())
    }

    /// Delete a ref
    pub fn delete_ref(&self, refname: &str) -> Result<()> {
        let status = Command::new("git")
            .args(["update-ref", "-d", refname])
            .current_dir(self.workdir()?)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .context("Failed to run git update-ref -d")?;

        if !status.success() {
            anyhow::bail!("git update-ref -d {} failed", refname);
        }
        Ok(())
    }

    /// Resolve a refspec to an OID (git rev-parse)
    pub fn rev_parse(&self, refspec: &str) -> Result<String> {
        let output = Command::new("git")
            .args(["rev-parse", refspec])
            .current_dir(self.workdir()?)
            .output()
            .context("Failed to run git rev-parse")?;

        if !output.status.success() {
            anyhow::bail!("git rev-parse {} failed", refspec);
        }

        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }

    /// Lease-protected force push a branch to the remote.
    pub fn force_push(&self, remote: &str, branch: &str) -> Result<()> {
        let status = Command::new("git")
            .args(["push", "--force-with-lease", remote, branch])
            .current_dir(self.workdir()?)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .context("Failed to run git push --force-with-lease")?;

        if !status.success() {
            anyhow::bail!("git push --force-with-lease {} {} failed", remote, branch);
        }
        Ok(())
    }

    /// Hard reset to a specific ref/OID
    pub fn reset_hard(&self, target: &str) -> Result<()> {
        let status = Command::new("git")
            .args(["reset", "--hard", target])
            .current_dir(self.workdir()?)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .context("Failed to run git reset --hard")?;

        if !status.success() {
            anyhow::bail!("git reset --hard {} failed", target);
        }
        Ok(())
    }
}

#[derive(Debug, PartialEq)]
pub enum RebaseResult {
    Success,
    Conflict,
}

#[derive(Debug, Clone)]
pub struct CommitInfo {
    pub short_hash: String,
    pub message: String,
}

/// Predicted conflict for a single branch rebase
#[derive(Debug, Clone)]
pub struct ConflictPrediction {
    pub branch: String,
    pub onto: String,
    pub conflicting_files: Vec<String>,
}

fn format_duration(seconds: i64) -> String {
    if seconds < 60 {
        "just now".to_string()
    } else if seconds < 3600 {
        let mins = seconds / 60;
        format!("{} minute{} ago", mins, if mins == 1 { "" } else { "s" })
    } else if seconds < 86400 {
        let hours = seconds / 3600;
        format!("{} hour{} ago", hours, if hours == 1 { "" } else { "s" })
    } else {
        let days = seconds / 86400;
        format!("{} day{} ago", days, if days == 1 { "" } else { "s" })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::Path;
    use std::process::Command;
    use tempfile::TempDir;

    fn run_git(path: &Path, args: &[&str]) {
        let output = Command::new("git")
            .args(args)
            .current_dir(path)
            .output()
            .expect("failed to run git");
        assert!(
            output.status.success(),
            "git {:?} failed\nstdout: {}\nstderr: {}",
            args,
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn run_git_stdout(path: &Path, args: &[&str]) -> String {
        let output = Command::new("git")
            .args(args)
            .current_dir(path)
            .output()
            .expect("failed to run git");
        assert!(
            output.status.success(),
            "git {:?} failed\nstdout: {}\nstderr: {}",
            args,
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }

    #[test]
    fn test_format_duration_just_now() {
        assert_eq!(format_duration(0), "just now");
        assert_eq!(format_duration(30), "just now");
        assert_eq!(format_duration(59), "just now");
    }

    #[test]
    fn test_format_duration_minutes() {
        assert_eq!(format_duration(60), "1 minute ago");
        assert_eq!(format_duration(120), "2 minutes ago");
        assert_eq!(format_duration(3599), "59 minutes ago");
    }

    #[test]
    fn test_format_duration_hours() {
        assert_eq!(format_duration(3600), "1 hour ago");
        assert_eq!(format_duration(7200), "2 hours ago");
        assert_eq!(format_duration(86399), "23 hours ago");
    }

    #[test]
    fn test_format_duration_days() {
        assert_eq!(format_duration(86400), "1 day ago");
        assert_eq!(format_duration(172800), "2 days ago");
        assert_eq!(format_duration(604800), "7 days ago");
    }

    #[test]
    fn test_rebase_result_eq() {
        assert_eq!(RebaseResult::Success, RebaseResult::Success);
        assert_eq!(RebaseResult::Conflict, RebaseResult::Conflict);
        assert_ne!(RebaseResult::Success, RebaseResult::Conflict);
    }

    #[test]
    fn test_rebase_result_debug() {
        let result = RebaseResult::Success;
        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("Success"));

        let result = RebaseResult::Conflict;
        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("Conflict"));
    }

    #[test]
    fn test_open_from_path_opens_repo_from_git_dir() {
        let dir = TempDir::new().expect("tempdir");
        let path = dir.path();

        run_git(path, &["init", "-b", "main"]);
        run_git(path, &["config", "user.email", "test@example.com"]);
        run_git(path, &["config", "user.name", "Test User"]);

        fs::write(path.join("README.md"), "base\n").expect("write readme");
        run_git(path, &["add", "README.md"]);
        run_git(path, &["commit", "-m", "Initial commit"]);

        let repo = GitRepo::open_from_path(&path.join(".git")).expect("open repo from git dir");
        assert_eq!(
            std::fs::canonicalize(repo.workdir().expect("repo workdir"))
                .expect("canonical workdir"),
            std::fs::canonicalize(path).expect("canonical temp repo path")
        );
    }

    #[test]
    fn test_commit_info_clone() {
        let commit = CommitInfo {
            short_hash: "abc123".to_string(),
            message: "Test commit".to_string(),
        };
        let cloned = commit.clone();
        assert_eq!(cloned.short_hash, "abc123");
        assert_eq!(cloned.message, "Test commit");
    }

    #[test]
    fn test_commit_info_debug() {
        let commit = CommitInfo {
            short_hash: "abc123".to_string(),
            message: "Test commit".to_string(),
        };
        let debug_str = format!("{:?}", commit);
        assert!(debug_str.contains("abc123"));
        assert!(debug_str.contains("Test commit"));
    }

    #[test]
    fn test_rebase_branch_onto_with_provenance_replays_only_novel_commits() {
        let dir = TempDir::new().expect("tempdir");
        let path = dir.path();

        run_git(path, &["init", "-b", "main"]);
        run_git(path, &["config", "user.email", "test@example.com"]);
        run_git(path, &["config", "user.name", "Test User"]);

        fs::write(path.join("README.md"), "base\n").expect("write readme");
        run_git(path, &["add", "README.md"]);
        run_git(path, &["commit", "-m", "Initial commit"]);
        let base_sha = run_git_stdout(path, &["rev-parse", "HEAD"]);

        run_git(path, &["checkout", "-b", "feature"]);
        fs::write(path.join("a1.txt"), "A1\n").expect("write a1");
        run_git(path, &["add", "a1.txt"]);
        run_git(path, &["commit", "-m", "A1"]);
        let a1_sha = run_git_stdout(path, &["rev-parse", "HEAD"]);

        fs::write(path.join("a2.txt"), "A2\n").expect("write a2");
        run_git(path, &["add", "a2.txt"]);
        run_git(path, &["commit", "-m", "A2"]);
        let a2_sha = run_git_stdout(path, &["rev-parse", "HEAD"]);

        fs::write(path.join("b.txt"), "B\n").expect("write b");
        run_git(path, &["add", "b.txt"]);
        run_git(path, &["commit", "-m", "B"]);

        run_git(path, &["checkout", "main"]);
        run_git(path, &["cherry-pick", &a1_sha]);
        run_git(path, &["cherry-pick", &a2_sha]);

        let repo = GitRepo {
            repo: Repository::open(path).expect("open repo"),
        };

        let result = repo
            .rebase_branch_onto_with_provenance("feature", "main", &base_sha, false)
            .expect("rebase with provenance");
        assert_eq!(result, RebaseResult::Success);

        let unique_count = run_git_stdout(path, &["rev-list", "--count", "main..feature"]);
        assert_eq!(unique_count, "1");
    }

    #[test]
    fn test_delete_branch_non_force_allows_empty_branch_merged_into_parent() {
        let dir = TempDir::new().expect("tempdir");
        let path = dir.path();

        run_git(path, &["init", "-b", "main"]);
        run_git(path, &["config", "user.email", "test@example.com"]);
        run_git(path, &["config", "user.name", "Test User"]);

        fs::write(path.join("README.md"), "# repo\n").expect("write readme");
        run_git(path, &["add", "README.md"]);
        run_git(path, &["commit", "-m", "Initial commit"]);

        run_git(path, &["checkout", "-b", "parent"]);
        fs::write(path.join("parent.txt"), "parent change\n").expect("write parent");
        run_git(path, &["add", "parent.txt"]);
        run_git(path, &["commit", "-m", "Parent commit"]);

        run_git(path, &["checkout", "-b", "child"]);
        run_git(path, &["checkout", "parent"]);

        let repo = GitRepo {
            repo: Repository::open(path).expect("open repo"),
        };

        crate::git::refs::write_metadata(
            &repo.repo,
            "child",
            r#"{"parentBranchName":"parent","parentBranchRevision":"ignored"}"#,
        )
        .expect("write metadata");

        repo.delete_branch("child", false)
            .expect("delete should succeed without force");
        assert!(repo.repo.find_branch("child", BranchType::Local).is_err());
    }

    #[test]
    fn derive_worktree_names_prefers_branch_leaf_for_duplicate_basenames() {
        let names = derive_worktree_names(&[
            WorktreeLabelCandidate {
                is_main: true,
                path: PathBuf::from("/tmp/repo"),
                basename: "main".to_string(),
                branch: Some("main".to_string()),
            },
            WorktreeLabelCandidate {
                is_main: false,
                path: PathBuf::from("/tmp/a/stax"),
                basename: "stax".to_string(),
                branch: Some("codex/fix-zsh".to_string()),
            },
            WorktreeLabelCandidate {
                is_main: false,
                path: PathBuf::from("/tmp/b/stax"),
                basename: "stax".to_string(),
                branch: Some("codex/docs".to_string()),
            },
        ]);

        assert_eq!(names, vec!["main", "fix-zsh", "docs"]);
    }

    #[test]
    fn derive_worktree_names_falls_back_to_path_suffix_for_detached_duplicates() {
        let names = derive_worktree_names(&[
            WorktreeLabelCandidate {
                is_main: true,
                path: PathBuf::from("/tmp/repo"),
                basename: "main".to_string(),
                branch: Some("main".to_string()),
            },
            WorktreeLabelCandidate {
                is_main: false,
                path: PathBuf::from("/tmp/00cb/stax"),
                basename: "stax".to_string(),
                branch: None,
            },
            WorktreeLabelCandidate {
                is_main: false,
                path: PathBuf::from("/tmp/073a/stax"),
                basename: "stax".to_string(),
                branch: None,
            },
        ]);

        assert_eq!(names, vec!["main", "00cb/stax", "073a/stax"]);
    }
}