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
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
use crate::commands::ci::{fetch_ci_statuses, record_ci_history};
use crate::errors::ConflictStopped;
use crate::commands::restack_conflict::{print_restack_conflict, RestackConflictContext};
use crate::commands::restack_parent::normalize_scope_parents_for_restack;
use crate::commands::worktree::{
    remove::remove_worktree_with_hooks,
    shared::{compute_worktree_details, worktree_removal_blockers_for_cleanup},
};
use crate::config::Config;
use crate::engine::{BranchMetadata, Stack};
use crate::forge::ForgeClient;
use crate::git::repo::BranchDeleteResolution;
use crate::git::{GitRepo, RebaseResult};
use crate::ops::receipt::{OpKind, PlanSummary};
use crate::ops::tx::{self, Transaction};
use crate::progress::LiveTimer;
use crate::remote::{self, RemoteInfo};
use anyhow::{Context, Result};
use colored::Colorize;
use dialoguer::{theme::ColorfulTheme, Confirm};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::process::Command;
use std::time::{Duration, Instant};

#[derive(Debug, Default)]
struct SyncStats {
    trunk: Option<TrunkSummary>,
    merged_branches_cleaned: usize,
    restacked_branches: usize,
}

#[derive(Debug)]
enum TrunkSummary {
    UpToDate {
        branch: String,
    },
    Pulled {
        branch: String,
        commits: usize,
        additions: usize,
        deletions: usize,
    },
    Updated {
        branch: String,
    },
}

#[derive(Debug, Clone)]
struct BlockingWorktreeCleanup {
    resolution: BranchDeleteResolution,
    blockers: Vec<&'static str>,
}

impl BlockingWorktreeCleanup {
    fn can_remove_during_sync(&self) -> bool {
        !self.resolution.worktree.is_main && self.blockers.is_empty()
    }

    fn can_force_remove_dirty_worktree_during_sync(&self) -> bool {
        !self.resolution.worktree.is_main
            && !self.blockers.is_empty()
            && self.blockers.iter().all(|blocker| *blocker == "dirty")
    }

    fn blocker_summary(&self) -> Option<String> {
        if self.resolution.worktree.is_main {
            return Some("it is the main worktree".to_string());
        }

        if self.blockers.is_empty() {
            return None;
        }

        let reasons = self
            .blockers
            .iter()
            .map(|blocker| match *blocker {
                "current" => "it is the current worktree",
                "dirty" => "it has uncommitted changes",
                "locked" => "it is locked",
                "rebase" => "a rebase is in progress",
                "merge" => "a merge is in progress",
                "conflicts" => "it has unresolved conflicts",
                other => other,
            })
            .collect::<Vec<_>>();

        Some(reasons.join(", "))
    }
}

#[derive(Debug, Clone, Copy, Default)]
struct LocalBranchDeleteOutcome {
    deleted: bool,
    worktree_blocked: bool,
}

/// Sync repo: pull trunk from remote, delete merged branches, optionally restack
#[allow(clippy::too_many_arguments)]
pub fn run(
    restack: bool,
    #[allow(unused_variables)] prune: bool,
    full: bool,
    delete_merged: bool,
    delete_upstream_gone: bool,
    force: bool,
    safe: bool,
    r#continue: bool,
    quiet: bool,
    verbose: bool,
    mut auto_stash_pop: bool,
) -> Result<()> {
    let sync_started_at = Instant::now();
    let mut step_timings: Vec<(String, Duration)> = Vec::new();
    let mut stats = SyncStats::default();

    let repo = GitRepo::open()?;
    let stack = Stack::load(&repo)?;
    let current = repo.current_branch()?;
    let workdir = repo.workdir()?.to_path_buf();
    let reopen_repo_path = repo.git_dir()?.to_path_buf();
    let trunk_branch = stack.trunk.clone();
    let config = Config::load()?;
    let remote_name = config.remote_name().to_string();
    let remote_trunk_ref = format!("{}/{}", remote_name, stack.trunk);

    if r#continue {
        crate::commands::continue_cmd::run()?;
        if repo.rebase_in_progress()? {
            return Ok(());
        }
    }

    let auto_confirm = force;
    let mut stashed = false;
    if repo.is_dirty()? {
        if quiet {
            anyhow::bail!("Working tree is dirty. Please stash or commit changes first.");
        }

        let stash = if auto_confirm {
            true
        } else {
            Confirm::with_theme(&ColorfulTheme::default())
                .with_prompt("Working tree has uncommitted changes. Stash them before sync?")
                .default(true)
                .interact()?
        };

        if stash {
            let stash_started_at = Instant::now();
            stashed = repo.stash_push()?;
            auto_stash_pop = true;
            step_timings.push(("stash working tree".to_string(), stash_started_at.elapsed()));
            if !quiet {
                println!("{}", "✓ Stashed working tree changes.".green());
            }
        } else {
            println!("{}", "Aborted.".red());
            return Ok(());
        }
    }

    if !quiet {
        println!("{}", "Syncing repository...".bold());
    }

    // 1. Fetch from remote
    // Default: trunk-only fetch + `ls-remote --heads` in parallel (fast on large repos).
    // `--full`: classic `fetch --prune --no-tags` for all remote-tracking refs.
    let fetch_timer = LiveTimer::maybe_new(!quiet, &format!("Fetch {}", remote_name));

    let fetch_started_at = Instant::now();
    let output;
    // Remote branch names for merged detection (`None` when `--no-delete`: trunk-only fetch).
    let remote_branches_for_merged: Option<HashSet<String>>;

    if full {
        let fetch_args: Vec<&str> = vec!["fetch", "--prune", "--no-tags", remote_name.as_str()];
        output = Command::new("git")
            .args(&fetch_args)
            .current_dir(&workdir)
            .output()
            .context("Failed to fetch")?;
        remote_branches_for_merged = if delete_merged {
            Some(
                repo.remote_branch_names(&remote_name)
                    .context("Failed to read remote-tracking branches after fetch")?,
            )
        } else {
            None
        };
    } else if delete_merged {
        let workdir_fetch = workdir.clone();
        let remote_fetch = remote_name.clone();
        let trunk = stack.trunk.clone();
        let workdir_ls = workdir.clone();
        let remote_ls = remote_name.clone();

        let fetch_handle = std::thread::spawn(move || {
            Command::new("git")
                .args(["fetch", "--no-tags", remote_fetch.as_str(), trunk.as_str()])
                .current_dir(&workdir_fetch)
                .output()
        });

        let ls_handle =
            std::thread::spawn(move || remote::ls_remote_heads(&workdir_ls, &remote_ls));

        output = fetch_handle
            .join()
            .map_err(|_| anyhow::anyhow!("fetch thread panicked"))?
            .context("Failed to fetch")?;

        let heads = ls_handle
            .join()
            .map_err(|_| anyhow::anyhow!("git ls-remote thread panicked"))??;
        if output.status.success() {
            prune_stale_remote_tracking_refs(&workdir, remote_name.as_str(), &stack, &heads);
        }
        remote_branches_for_merged = Some(heads);
    } else {
        output = Command::new("git")
            .args([
                "fetch",
                "--no-tags",
                remote_name.as_str(),
                stack.trunk.as_str(),
            ])
            .current_dir(&workdir)
            .output()
            .context("Failed to fetch")?;
        remote_branches_for_merged = None;
    }

    step_timings.push((format!("fetch {}", remote_name), fetch_started_at.elapsed()));

    if output.status.success() {
        LiveTimer::maybe_finish_timed(fetch_timer);
        if !quiet && verbose {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if !stderr.trim().is_empty() {
                for line in stderr.lines() {
                    println!("    {}", line.dimmed());
                }
            }
        }
    } else {
        // Fetch may fail partially (lock files, etc.) but still update most refs
        LiveTimer::maybe_finish_warn(fetch_timer, "done (with warnings)");
        if !quiet && verbose {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if !stderr.trim().is_empty() {
                for line in stderr.lines() {
                    println!("    {}", line.dimmed());
                }
            }
        }
    }

    let local_trunk_before_sync = resolve_ref_oid(&workdir, &stack.trunk);
    let remote_trunk_after_fetch = resolve_ref_oid(&workdir, &remote_trunk_ref);

    // 2. Update trunk branch (before merged branch detection, so detection works correctly)
    // Note: If we're not on trunk, we use a refspec fetch which may fail if local trunk
    // has diverged. This is fine - we'll retry after branch deletions if we end up on trunk.
    let was_on_trunk = current == stack.trunk;
    let mut trunk_update_deferred = false;
    let update_trunk_started_at = Instant::now();

    if was_on_trunk {
        // We're on trunk - pull directly
        let update_timer = LiveTimer::maybe_new(!quiet, &format!("Update {}", stack.trunk));

        let output = Command::new("git")
            .args(["merge", "--ff-only", &remote_trunk_ref])
            .current_dir(&workdir)
            .output()
            .context("Failed to fast-forward trunk")?;

        if output.status.success() {
            LiveTimer::maybe_finish_timed(update_timer);
            if !quiet && verbose {
                let stdout = String::from_utf8_lossy(&output.stdout);
                if !stdout.trim().is_empty() {
                    for line in stdout.lines() {
                        println!("    {}", line.dimmed());
                    }
                }
            }
        } else if safe {
            LiveTimer::maybe_finish_warn(update_timer, "failed (safe mode, no reset)");
            if !quiet && verbose {
                let stderr = String::from_utf8_lossy(&output.stderr);
                if !stderr.trim().is_empty() {
                    for line in stderr.lines() {
                        println!("    {}", line.dimmed());
                    }
                }
            }
        } else if !is_ancestor(&workdir, &stack.trunk, &remote_trunk_ref) {
            // Local trunk has diverged from remote (has local-only commits).
            // Refuse to reset to avoid silently losing those commits.
            LiveTimer::maybe_finish_warn(
                update_timer,
                "diverged (local has commits not on remote; rebase or reset trunk manually)",
            );
        } else {
            // Local is ancestor of remote -- safe to reset (equivalent to fast-forward)
            let reset_output = Command::new("git")
                .args(["reset", "--hard", &remote_trunk_ref])
                .current_dir(&workdir)
                .output()
                .context("Failed to reset trunk")?;

            if reset_output.status.success() {
                LiveTimer::maybe_finish_warn(update_timer, "reset to remote");
            } else {
                LiveTimer::maybe_finish_err(update_timer, "failed");
                if !quiet && verbose {
                    let stderr = String::from_utf8_lossy(&reset_output.stderr);
                    if !stderr.trim().is_empty() {
                        for line in stderr.lines() {
                            println!("    {}", line.dimmed());
                        }
                    }
                }
            }
        }
    } else {
        let update_timer = LiveTimer::maybe_new(!quiet, &format!("Update {}", stack.trunk));

        if let Some(trunk_worktree_path) = repo.branch_worktree_path(&stack.trunk)? {
            let output = Command::new("git")
                .args(["merge", "--ff-only", &remote_trunk_ref])
                .current_dir(&trunk_worktree_path)
                .output()
                .context("Failed to fast-forward trunk in its worktree")?;

            if output.status.success() {
                LiveTimer::maybe_finish_timed(update_timer);
            } else if safe {
                LiveTimer::maybe_finish_warn(update_timer, "failed (safe mode, no reset)");
                if !quiet && verbose {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    if !stderr.trim().is_empty() {
                        for line in stderr.lines() {
                            println!("    {}", line.dimmed());
                        }
                    }
                }
            } else if !is_ancestor(&trunk_worktree_path, &stack.trunk, &remote_trunk_ref) {
                LiveTimer::maybe_finish_warn(
                    update_timer,
                    "diverged (local has commits not on remote; rebase or reset trunk manually)",
                );
            } else {
                let reset_output = Command::new("git")
                    .args(["reset", "--hard", &remote_trunk_ref])
                    .current_dir(&trunk_worktree_path)
                    .output()
                    .context("Failed to reset trunk in its worktree")?;

                if reset_output.status.success() {
                    LiveTimer::maybe_finish_warn(update_timer, "reset to remote");
                } else {
                    LiveTimer::maybe_finish_err(update_timer, "failed");
                    if !quiet && verbose {
                        let stderr = String::from_utf8_lossy(&reset_output.stderr);
                        if !stderr.trim().is_empty() {
                            for line in stderr.lines() {
                                println!("    {}", line.dimmed());
                            }
                        }
                    }
                }
            }
        } else {
            // Trunk isn't checked out in any worktree.
            // Resolve the two SHAs so we can give an accurate status message.
            let local_sha = Command::new("git")
                .args(["rev-parse", &stack.trunk])
                .current_dir(&workdir)
                .output()
                .ok()
                .filter(|o| o.status.success())
                .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string());

            let remote_sha = Command::new("git")
                .args(["rev-parse", &remote_trunk_ref])
                .current_dir(&workdir)
                .output()
                .ok()
                .filter(|o| o.status.success())
                .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string());

            match (local_sha, remote_sha) {
                (Some(ref local), Some(ref remote)) if local == remote => {
                    // Already up to date — nothing to do.
                    LiveTimer::maybe_finish_timed(update_timer);
                }
                (Some(_), Some(_)) => {
                    // Check if a fast-forward is safe (local trunk is an ancestor of remote).
                    let ff_possible = Command::new("git")
                        .args([
                            "merge-base",
                            "--is-ancestor",
                            &stack.trunk,
                            &remote_trunk_ref,
                        ])
                        .current_dir(&workdir)
                        .status()
                        .map(|s| s.success())
                        .unwrap_or(false);

                    if ff_possible {
                        let output = Command::new("git")
                            .args([
                                "update-ref",
                                &format!("refs/heads/{}", stack.trunk),
                                &format!("refs/remotes/{}/{}", remote_name, stack.trunk),
                            ])
                            .current_dir(&workdir)
                            .output()
                            .context("Failed to fast-forward local trunk ref")?;

                        if output.status.success() {
                            LiveTimer::maybe_finish_timed(update_timer);
                        } else {
                            trunk_update_deferred = true;
                            LiveTimer::maybe_finish_skipped(
                                update_timer,
                                "couldn't update — run 'stax trunk' to pull",
                            );
                        }
                    } else {
                        // Local trunk has commits not on the remote — can't fast-forward.
                        trunk_update_deferred = true;
                        LiveTimer::maybe_finish_skipped(
                            update_timer,
                            &format!(
                                "local {} has unpushed commits — run 'stax trunk' to sync",
                                stack.trunk
                            ),
                        );
                    }
                }
                _ => {
                    // Couldn't resolve one or both refs (shouldn't happen after a successful fetch).
                    trunk_update_deferred = true;
                    LiveTimer::maybe_finish_skipped(
                        update_timer,
                        "couldn't resolve ref — run 'stax trunk' to pull",
                    );
                }
            }
        }
    }
    step_timings.push((
        format!("update {}", stack.trunk),
        update_trunk_started_at.elapsed(),
    ));

    // 3. Delete merged branches
    let repo = if delete_merged {
        let detect_merged_started_at = Instant::now();
        let detect_timer = LiveTimer::maybe_new(!quiet, "Detect merged branches");
        let merged = find_merged_branches(
            &repo,
            &workdir,
            &stack,
            &remote_name,
            remote_branches_for_merged
                .as_ref()
                .expect("remote branch list when deleting merged branches"),
        )?;
        step_timings.push((
            "detect merged branches".to_string(),
            detect_merged_started_at.elapsed(),
        ));
        LiveTimer::maybe_finish_timed(detect_timer);

        let delete_merged_started_at = Instant::now();
        drop(repo);
        let repo = GitRepo::open_from_path(&reopen_repo_path)?;

        // Initialize forge client once up-front for any PR base updates below.
        let forge_client: Option<(tokio::runtime::Runtime, ForgeClient)> = {
            let remote_info = RemoteInfo::from_repo(&repo, &config).ok();

            if let Some(info) = remote_info {
                tokio::runtime::Runtime::new().ok().and_then(|rt| {
                    let _enter = rt.enter();
                    ForgeClient::new(&info).ok().map(|client| (rt, client))
                })
            } else {
                None
            }
        };

        if !merged.is_empty() {
            if !quiet {
                let branch_word = if merged.len() == 1 {
                    "branch"
                } else {
                    "branches"
                };
                println!(
                    "    Found {} merged {}:",
                    merged.len().to_string().cyan(),
                    branch_word
                );
                for branch in &merged {
                    println!("      {} {}", "â–¸".bright_black(), branch);
                }
                println!();
            }

            // Record CI history for merged branches before deleting them
            if let Some((ref rt, ref client)) = forge_client {
                record_ci_history_for_merged(&repo, rt, client, &merged, &stack, quiet);
            }

            for branch in &merged {
                let is_current_branch = branch == &current;
                let blocking_worktree_cleanup = if is_current_branch {
                    None
                } else {
                    plan_blocking_worktree_cleanup(&repo, branch, force)?
                };

                // Resolve parent branch for checkout/reparent.
                // Metadata can reference a deleted branch; in that case fall back to trunk.
                let recorded_parent_branch = stack
                    .branches
                    .get(branch)
                    .and_then(|b| b.parent.clone())
                    .unwrap_or_else(|| stack.trunk.clone());
                let (parent_branch, parent_fallback_from) =
                    resolve_effective_parent(&workdir, &recorded_parent_branch, &stack.trunk);
                let parent_exists_locally = local_branch_exists(&workdir, &parent_branch);

                if !quiet {
                    if let Some(missing_parent) = &parent_fallback_from {
                        println!(
                            "    {} parent {} not found locally; using {}",
                            "↪".yellow(),
                            missing_parent.yellow(),
                            parent_branch.cyan()
                        );
                    }
                }

                if !parent_exists_locally {
                    if !quiet {
                        println!(
                            "    {} {}",
                            branch.bright_black(),
                            format!(
                                "couldn't resolve a local parent branch (wanted '{}'), skipping",
                                parent_branch
                            )
                            .red()
                        );
                    }
                    continue;
                }

                let prompt = sync_delete_prompt(
                    branch,
                    if is_current_branch {
                        Some(parent_branch.as_str())
                    } else {
                        None
                    },
                    None,
                    blocking_worktree_cleanup.as_ref(),
                );

                let confirm = if auto_confirm {
                    true
                } else if quiet {
                    false
                } else {
                    Confirm::with_theme(&ColorfulTheme::default())
                        .with_prompt(prompt)
                        .default(true)
                        .interact()?
                };
                let confirmed_dirty_worktree_removal = confirm
                    && blocking_worktree_cleanup.as_ref().is_some_and(
                        BlockingWorktreeCleanup::can_force_remove_dirty_worktree_during_sync,
                    );

                if confirm {
                    // If we're on this branch, checkout parent first
                    if is_current_branch {
                        match checkout_branch_for_cleanup(&repo, &workdir, &parent_branch) {
                            Ok(()) => {
                                if !quiet {
                                    println!(
                                        "    {} checked out {}",
                                        "→".cyan(),
                                        parent_branch.cyan()
                                    );
                                }

                                // Pull latest changes for the parent branch
                                let pull_status = Command::new("git")
                                    .args(["pull", "--ff-only", &remote_name, &parent_branch])
                                    .current_dir(&workdir)
                                    .stdout(std::process::Stdio::null())
                                    .stderr(std::process::Stdio::null())
                                    .status();

                                if let Ok(status) = pull_status {
                                    if status.success() && !quiet {
                                        println!(
                                            "    {} pulled latest {}",
                                            "↓".cyan(),
                                            parent_branch.cyan()
                                        );
                                    }
                                }
                            }
                            Err(checkout_error) => {
                                if !quiet {
                                    println!(
                                        "    {} {}",
                                        branch.bright_black(),
                                        format!(
                                            "failed to checkout '{}': {}, skipping",
                                            parent_branch, checkout_error
                                        )
                                        .red()
                                    );
                                }
                                continue;
                            }
                        }
                    }

                    // Reparent tracked children onto the surviving parent before
                    // deleting, preserving the old-parent boundary for later restack.
                    reparent_children_for_deletion(
                        &repo,
                        &stack,
                        branch,
                        &parent_branch,
                        forge_client.as_ref(),
                        quiet,
                    )?;

                    let local_delete = delete_local_branch_for_sync(
                        &repo,
                        &config,
                        &workdir,
                        branch,
                        blocking_worktree_cleanup.as_ref(),
                        force,
                        confirmed_dirty_worktree_removal,
                        quiet,
                    )?;
                    let local_deleted = local_delete.deleted;
                    let local_worktree_blocked = local_delete.worktree_blocked;

                    // Delete remote branch
                    let remote_status = Command::new("git")
                        .args(["push", &remote_name, "--delete", branch])
                        .current_dir(&workdir)
                        .stdout(std::process::Stdio::null())
                        .stderr(std::process::Stdio::null())
                        .status();

                    let remote_deleted = remote_status.map(|s| s.success()).unwrap_or(false);

                    // Only delete metadata if branch no longer exists locally.
                    let local_still_exists = local_branch_exists(&workdir, branch);

                    let metadata_deleted = if !local_still_exists {
                        match crate::git::refs::delete_metadata(repo.inner(), branch) {
                            Ok(()) => true,
                            Err(e) => {
                                println!(
                                    "{}",
                                    format!(
                                        "Warning: failed to delete metadata for '{}': {}",
                                        branch, e
                                    )
                                    .yellow()
                                );
                                false
                            }
                        }
                    } else {
                        false
                    };

                    if metadata_deleted {
                        stats.merged_branches_cleaned += 1;
                    }

                    if !quiet {
                        if local_deleted && remote_deleted {
                            println!(
                                "    {} {}",
                                branch.bright_black(),
                                "deleted (local + remote)".green()
                            );
                        } else if local_deleted {
                            println!(
                                "    {} {}",
                                branch.bright_black(),
                                "deleted (local only)".green()
                            );
                        } else if remote_deleted {
                            println!(
                                "    {} {}",
                                branch.bright_black(),
                                "deleted (remote only)".green()
                            );
                            if !metadata_deleted {
                                println!(
                                    "    {} {}",
                                    "↷".yellow(),
                                    "local branch still exists, metadata kept".dimmed()
                                );
                            }
                        } else {
                            if local_worktree_blocked {
                                print_blocked_branch_delete_recovery(
                                    branch,
                                    blocking_worktree_cleanup.as_ref(),
                                );
                            } else {
                                println!("    {} {}", branch.bright_black(), "skipped".dimmed());
                            }
                            if !metadata_deleted {
                                println!(
                                    "    {} {}",
                                    "↷".yellow(),
                                    "metadata kept because local branch still exists".dimmed()
                                );
                            }
                        }
                    }
                } else if !quiet {
                    println!("    {} {}", branch.bright_black(), "skipped".dimmed());
                }
            }
        } else if !quiet {
            println!("    {}", "No merged branches to delete.".dimmed());
        }

        let delete_elapsed = delete_merged_started_at.elapsed();
        step_timings.push(("delete merged branches".to_string(), delete_elapsed));
        if !quiet && !merged.is_empty() {
            println!(
                "  {:<35} {}",
                "delete merged branches",
                format!("{:.3}s", delete_elapsed.as_secs_f64()).dimmed()
            );
        }
        repo
    } else {
        repo
    };

    // Re-check current branch since it may have changed during branch deletion
    let mut current_after_deletions = repo.current_branch()?;

    // 3b. Optionally delete local branches whose upstream is gone
    if delete_upstream_gone {
        let detect_gone_started_at = Instant::now();
        let detect_timer = LiveTimer::maybe_new(!quiet, "Detect upstream-gone branches");
        let gone = find_upstream_gone_branches(&workdir, &stack.trunk)?;
        step_timings.push((
            "detect upstream-gone branches".to_string(),
            detect_gone_started_at.elapsed(),
        ));
        LiveTimer::maybe_finish_timed(detect_timer);

        let delete_gone_started_at = Instant::now();

        if !gone.is_empty() {
            if !quiet {
                let branch_word = if gone.len() == 1 {
                    "branch"
                } else {
                    "branches"
                };
                println!(
                    "    Found {} upstream-gone {}:",
                    gone.len().to_string().cyan(),
                    branch_word
                );
                for branch in &gone {
                    println!("      {} {}", "â–¸".bright_black(), branch);
                }
                println!();
            }

            // Reload the stack so the merged-branch path's reparenting is
            // reflected before we resolve upstream-gone branches. Fall back to
            // the snapshot captured at the top of sync() if the reload fails,
            // to degrade gracefully rather than aborting a mid-sync run.
            let mut live_stack = Stack::load(&repo).unwrap_or_else(|_| stack.clone());

            // Initialize forge client once up-front for any PR base updates below.
            let forge_client: Option<(tokio::runtime::Runtime, ForgeClient)> = {
                let remote_info = RemoteInfo::from_repo(&repo, &config).ok();
                if let Some(info) = remote_info {
                    tokio::runtime::Runtime::new().ok().and_then(|rt| {
                        let _enter = rt.enter();
                        ForgeClient::new(&info).ok().map(|client| (rt, client))
                    })
                } else {
                    None
                }
            };

            for branch in &gone {
                if !local_branch_exists(&workdir, branch) {
                    continue;
                }

                let is_current_branch = branch == &current_after_deletions;
                let blocking_worktree_cleanup = if is_current_branch {
                    None
                } else {
                    plan_blocking_worktree_cleanup(&repo, branch, force)?
                };

                // Resolve the parent children will be reparented to. Walks up
                // the recorded-parent chain skipping any branch that is itself
                // scheduled for deletion in this pass, so a stack like A -> B -> C
                // (where A and B both have upstream gone) lands C on trunk
                // rather than on the soon-to-be-deleted A.
                let (fallback_parent, parent_fallback_from) =
                    resolve_fallback_parent_skipping_doomed(
                        &workdir, &live_stack, branch, &gone,
                    );

                // Print the parent-fallback hint BEFORE the confirm prompt so the
                // user knows why the prompt mentions a non-recorded parent.
                if !quiet {
                    if let Some(missing_parent) = &parent_fallback_from {
                        println!(
                            "    {} parent {} not available; using {}",
                            "↪".yellow(),
                            missing_parent.yellow(),
                            fallback_parent.cyan()
                        );
                    }
                }

                let prompt = sync_delete_prompt(
                    branch,
                    if is_current_branch {
                        Some(fallback_parent.as_str())
                    } else {
                        None
                    },
                    Some("upstream gone"),
                    blocking_worktree_cleanup.as_ref(),
                );

                let confirm = if auto_confirm {
                    true
                } else if quiet {
                    false
                } else {
                    Confirm::with_theme(&ColorfulTheme::default())
                        .with_prompt(prompt)
                        .default(true)
                        .interact()?
                };
                let confirmed_dirty_worktree_removal = confirm
                    && blocking_worktree_cleanup.as_ref().is_some_and(
                        BlockingWorktreeCleanup::can_force_remove_dirty_worktree_during_sync,
                    );

                if !confirm {
                    if !quiet {
                        println!("    {} {}", branch.bright_black(), "skipped".dimmed());
                    }
                    continue;
                }

                if is_current_branch {
                    match checkout_branch_for_cleanup(&repo, &workdir, &fallback_parent) {
                        Ok(()) => {
                            current_after_deletions = fallback_parent.clone();
                            if !quiet {
                                println!(
                                    "    {} checked out {}",
                                    "→".cyan(),
                                    fallback_parent.cyan()
                                );
                            }
                        }
                        Err(checkout_error) => {
                            if !quiet {
                                println!(
                                    "    {} {}",
                                    branch.bright_black(),
                                    format!(
                                        "failed to checkout '{}': {}, skipping",
                                        fallback_parent, checkout_error
                                    )
                                    .red()
                                );
                            }
                            continue;
                        }
                    }
                }

                // Reparent tracked children to the fallback parent before
                // deleting. The shared helper also mirrors the merged-branch
                // path's ancestor-check rationale from issue #120.
                reparent_children_for_deletion(
                    &repo,
                    &live_stack,
                    branch,
                    &fallback_parent,
                    forge_client.as_ref(),
                    quiet,
                )?;

                // Refresh the in-memory stack so subsequent iterations see the
                // just-reparented children under the new parent (preventing a
                // later iteration from bouncing them again). Fall back to the
                // current live_stack if the reload fails.
                if let Ok(refreshed) = Stack::load(&repo) {
                    live_stack = refreshed;
                }

                let local_delete = delete_local_branch_for_sync(
                    &repo,
                    &config,
                    &workdir,
                    branch,
                    blocking_worktree_cleanup.as_ref(),
                    force,
                    confirmed_dirty_worktree_removal,
                    quiet,
                )?;
                let local_deleted = local_delete.deleted;
                let local_worktree_blocked = local_delete.worktree_blocked;

                // Only delete metadata if branch no longer exists locally.
                let local_still_exists = local_branch_exists(&workdir, branch);

                let metadata_deleted = if !local_still_exists {
                    match crate::git::refs::delete_metadata(repo.inner(), branch) {
                        Ok(()) => true,
                        Err(e) => {
                            println!(
                                "{}",
                                format!(
                                    "Warning: failed to delete metadata for '{}': {}",
                                    branch, e
                                )
                                .yellow()
                            );
                            false
                        }
                    }
                } else {
                    false
                };

                if !quiet {
                    if local_deleted {
                        println!(
                            "    {} {}",
                            branch.bright_black(),
                            "deleted (local only)".green()
                        );
                    } else if local_worktree_blocked {
                        print_blocked_branch_delete_recovery(
                            branch,
                            blocking_worktree_cleanup.as_ref(),
                        );
                    } else {
                        println!("    {} {}", branch.bright_black(), "skipped".dimmed());
                    }

                    if !metadata_deleted && local_still_exists {
                        println!(
                            "    {} {}",
                            "↷".yellow(),
                            "metadata kept because local branch still exists".dimmed()
                        );
                    }
                }
            }
        } else if !quiet {
            println!("    {}", "No upstream-gone branches to delete.".dimmed());
        }

        let delete_elapsed = delete_gone_started_at.elapsed();
        step_timings.push(("delete upstream-gone branches".to_string(), delete_elapsed));
        if !quiet && !gone.is_empty() {
            println!(
                "  {:<35} {}",
                "delete upstream-gone branches",
                format!("{:.3}s", delete_elapsed.as_secs_f64()).dimmed()
            );
        }
    }

    // If we deferred trunk update (refspec fetch failed while not on trunk) and we're
    // now on trunk after branch deletions, retry with git pull which is more reliable
    if trunk_update_deferred && current_after_deletions == stack.trunk {
        let deferred_update_started_at = Instant::now();
        let deferred_timer = LiveTimer::maybe_new(!quiet, &format!("Update {}", stack.trunk));

        let output = Command::new("git")
            .args(["merge", "--ff-only", &remote_trunk_ref])
            .current_dir(&workdir)
            .output()
            .context("Failed to fast-forward trunk")?;

        if output.status.success() {
            LiveTimer::maybe_finish_timed(deferred_timer);
            if !quiet && verbose {
                let stdout = String::from_utf8_lossy(&output.stdout);
                if !stdout.trim().is_empty() {
                    for line in stdout.lines() {
                        println!("    {}", line.dimmed());
                    }
                }
            }
        } else if safe {
            LiveTimer::maybe_finish_warn(deferred_timer, "failed (safe mode, no reset)");
            if !quiet && verbose {
                let stderr = String::from_utf8_lossy(&output.stderr);
                if !stderr.trim().is_empty() {
                    for line in stderr.lines() {
                        println!("    {}", line.dimmed());
                    }
                }
            }
        } else if !is_ancestor(&workdir, &stack.trunk, &remote_trunk_ref) {
            LiveTimer::maybe_finish_warn(
                deferred_timer,
                "diverged (local has commits not on remote; rebase or reset trunk manually)",
            );
        } else {
            // Local is ancestor of remote -- safe to reset
            let reset_output = Command::new("git")
                .args(["reset", "--hard", &remote_trunk_ref])
                .current_dir(&workdir)
                .output()
                .context("Failed to reset trunk")?;

            if reset_output.status.success() {
                LiveTimer::maybe_finish_warn(deferred_timer, "reset to remote");
            } else {
                LiveTimer::maybe_finish_err(deferred_timer, "failed");
                if !quiet && verbose {
                    let stderr = String::from_utf8_lossy(&reset_output.stderr);
                    if !stderr.trim().is_empty() {
                        for line in stderr.lines() {
                            println!("    {}", line.dimmed());
                        }
                    }
                }
            }
        }

        step_timings.push((
            format!("retry update {}", stack.trunk),
            deferred_update_started_at.elapsed(),
        ));
    }

    // 4. Optionally restack
    if restack {
        let restack_started_at = Instant::now();
        if !quiet {
            println!();
            println!("{}", "Restacking...".bold());
        }

        // Scope restacking to the stack we started on, even if sync switched branches
        // (for example, if the current branch was deleted after merge).
        let scope_order: Vec<String> =
            if current != stack.trunk && stack.branches.contains_key(&current) {
                stack.current_stack(&current)
            } else {
                Vec::new()
            };
        // Normalize parents for branches whose parent was squash-merged into trunk,
        // so the rebase uses the correct --onto boundary.
        normalize_scope_parents_for_restack(&repo, &scope_order, quiet)?;

        // Reload stack to use fresh metadata after sync/deletion and normalization steps.
        let restack_stack = Stack::load(&repo)?;
        let branches_to_restack: Vec<String> = scope_order
            .iter()
            .filter(|branch| {
                restack_stack
                    .branches
                    .get(branch.as_str())
                    .map(|br| br.needs_restack)
                    .unwrap_or(false)
            })
            .cloned()
            .collect();

        if branches_to_restack.is_empty() {
            if !quiet {
                println!("  {}", "All branches up to date.".dimmed());
            }
        } else {
            // Begin transaction for restack phase
            let mut tx = Transaction::begin(OpKind::SyncRestack, &repo, quiet)?;
            tx.plan_branches(&repo, &scope_order)?;
            let restack_count = branches_to_restack.len();
            let summary = PlanSummary {
                branches_to_rebase: restack_count,
                branches_to_push: 0,
                description: vec![format!(
                    "Sync restack {} {}",
                    restack_count,
                    if restack_count == 1 {
                        "branch"
                    } else {
                        "branches"
                    }
                )],
            };
            tx::print_plan(tx.kind(), &summary, quiet);
            tx.set_plan_summary(summary);
            tx.set_auto_stash_pop(auto_stash_pop);
            tx.snapshot()?;

            let mut summary: Vec<(String, String)> = Vec::new();
            let mut restacked_branches = 0usize;

            for (index, branch) in scope_order.iter().enumerate() {
                let live_stack = Stack::load(&repo)?;
                let needs_restack = live_stack
                    .branches
                    .get(branch.as_str())
                    .map(|br| br.needs_restack)
                    .unwrap_or(false);
                if !needs_restack {
                    continue;
                }

                let restack_timer = LiveTimer::maybe_new(!quiet, &format!("Restack {}", branch));

                let meta = match BranchMetadata::read(repo.inner(), branch)? {
                    Some(meta) => meta,
                    None => continue,
                };

                match repo.rebase_branch_onto_with_provenance(
                    branch,
                    &meta.parent_branch_name,
                    &meta.parent_branch_revision,
                    auto_stash_pop,
                )? {
                    RebaseResult::Success => {
                        let parent_commit = repo.branch_commit(&meta.parent_branch_name)?;
                        let updated_meta = BranchMetadata {
                            parent_branch_revision: parent_commit,
                            ..meta
                        };
                        updated_meta.write(repo.inner(), branch)?;

                        // Record after-OID
                        tx.record_after(&repo, branch)?;
                        tx.push_completed_branch(branch);

                        LiveTimer::maybe_finish_timed(restack_timer);
                        restacked_branches += 1;
                        summary.push((branch.clone(), "ok".to_string()));
                    }
                    RebaseResult::Conflict => {
                        LiveTimer::maybe_finish_warn(restack_timer, "conflict");
                        let completed_branches: Vec<String> = summary
                            .iter()
                            .filter(|(_, status)| status == "ok")
                            .map(|(name, _)| name.clone())
                            .collect();
                        let conflict_stack = live_stack.current_stack(branch);
                        print_restack_conflict(
                            &repo,
                            &RestackConflictContext {
                                branch,
                                parent_branch: &meta.parent_branch_name,
                                completed_branches: &completed_branches,
                                remaining_branches: scope_order.len().saturating_sub(index + 1),
                                continue_commands: &[
                                    "stax resolve",
                                    "stax continue",
                                    "stax sync --continue",
                                ],
                                stack_branches: &conflict_stack,
                            },
                        );
                        if stashed {
                            println!("{}", "Stash kept to avoid conflicts.".yellow());
                        }
                        summary.push((branch.clone(), "conflict".to_string()));

                        // Finish transaction with error
                        tx.finish_err("Rebase conflict", Some("restack"), Some(branch))?;

                        return Err(ConflictStopped.into());
                    }
                }
            }

            repo.checkout(&current_after_deletions)?;

            // Finish transaction successfully
            tx.finish_ok()?;
            stats.restacked_branches = restacked_branches;

            if !quiet && !summary.is_empty() {
                println!();
                println!("{}", "Restack summary:".dimmed());
                for (branch, status) in &summary {
                    let symbol = if status == "ok" { "✓" } else { "✗" };
                    println!("  {} {} {}", symbol, branch, status);
                }
            }
        }

        step_timings.push(("restack".to_string(), restack_started_at.elapsed()));
    }

    if stashed {
        let stash_pop_started_at = Instant::now();
        repo.stash_pop()?;
        step_timings.push(("restore stash".to_string(), stash_pop_started_at.elapsed()));
        if !quiet {
            println!("{}", "✓ Restored stashed changes.".green());
        }
    }

    stats.trunk = summarize_trunk_sync(
        &workdir,
        &trunk_branch,
        local_trunk_before_sync.as_deref(),
        remote_trunk_after_fetch.as_deref(),
    );

    if verbose && !quiet {
        println!();
        println!("{}", "Sync timing summary:".bold());
        for (step, duration) in &step_timings {
            println!("  {:<35} {}", step, format_duration(*duration).dimmed());
        }
        println!(
            "  {:<35} {}",
            "total",
            format_duration(sync_started_at.elapsed()).cyan()
        );
    }

    if !quiet {
        println!();
        println!(
            "{} {}",
            "Sync complete!".green().bold(),
            render_sync_footer(&stats, sync_started_at.elapsed())
        );

        if !restack && stats.merged_branches_cleaned > 0 && config.ui.tips {
            println!(
                "{}",
                "Hint: Run `st restack --all` to rebase branches onto the updated trunk.".dimmed()
            );
        }
    }

    Ok(())
}

/// Drop stale `refs/remotes/<remote>/<branch>` for stax-tracked branches that no longer exist on the remote.
fn prune_stale_remote_tracking_refs(
    workdir: &Path,
    remote_name: &str,
    stack: &Stack,
    remote_branches: &HashSet<String>,
) {
    for branch in stack.branches.keys() {
        if branch == &stack.trunk {
            continue;
        }
        if remote_branches.contains(branch.as_str()) {
            continue;
        }
        let refname = format!("refs/remotes/{}/{}", remote_name, branch);
        let _ = Command::new("git")
            .args(["update-ref", "-d", &refname])
            .current_dir(workdir)
            .status();
    }
}

fn find_merged_branches(
    repo: &GitRepo,
    workdir: &std::path::Path,
    stack: &Stack,
    remote_name: &str,
    remote_branches: &HashSet<String>,
) -> Result<Vec<String>> {
    let mut merged = Vec::new();
    let remote_trunk_ref = format!("{}/{}", remote_name, stack.trunk);

    // Method 1: git branch --merged (finds local branches merged into trunk)
    let output = Command::new("git")
        .args(["branch", "--merged", &stack.trunk])
        .current_dir(workdir)
        .output()
        .context("Failed to list merged branches")?;

    let merged_output = String::from_utf8_lossy(&output.stdout);

    for line in merged_output.lines() {
        let branch = line.trim().trim_start_matches("* ");

        // Skip trunk itself and any non-tracked branches
        if branch == stack.trunk || branch.is_empty() {
            continue;
        }

        // Only include branches we're tracking
        if stack.branches.contains_key(branch) {
            merged.push(branch.to_string());
        }
    }

    // Method 1b: git branch --merged origin/trunk (handles stale/diverged local trunk)
    let output = Command::new("git")
        .args(["branch", "--merged", &remote_trunk_ref])
        .current_dir(workdir)
        .output();

    if let Ok(output) = output {
        let merged_output = String::from_utf8_lossy(&output.stdout);

        for line in merged_output.lines() {
            let branch = line.trim().trim_start_matches("* ");

            // Skip trunk itself and any non-tracked branches
            if branch == stack.trunk || branch.is_empty() {
                continue;
            }

            // Only include branches we're tracking (and avoid duplicates)
            if stack.branches.contains_key(branch) && !merged.iter().any(|b| b == branch) {
                merged.push(branch.to_string());
            }
        }
    }

    // Method 2: Check PR state from metadata.
    // Only an explicitly merged PR is a strong enough signal for cleanup here.
    // Closed-but-unmerged PRs must be preserved unless some other merge/deletion
    // heuristic below proves the branch is safe to clean up.
    for (branch, info) in &stack.branches {
        // Skip trunk
        if branch == &stack.trunk {
            continue;
        }

        // Skip if already in merged list
        if merged.contains(branch) {
            continue;
        }

        if matches!(
            info.pr_state.as_deref(),
            Some(state) if state.eq_ignore_ascii_case("merged")
        ) {
            merged.push(branch.clone());
        }
    }

    // Method 4: Check if the tracked remote branch was deleted (GitHub deletes
    // branch after merge). This is cheaper and more robust than enumerating the
    // entire remote ref namespace in very large repos.
    for (branch, info) in &stack.branches {
        // Skip trunk
        if branch == &stack.trunk {
            continue;
        }

        // Skip if already in merged list
        if merged.contains(branch) {
            continue;
        }

        // Only consider "remote deleted" if branch had a PR before (was pushed)
        // This prevents false positives for branches that were never pushed
        if info.pr_number.is_none() {
            continue;
        }

        // Check if remote branch was deleted (strong signal it was merged)
        if !remote_branches.contains(branch.as_str()) {
            // Remote branch doesn't exist and had a PR - likely merged and deleted
            merged.push(branch.clone());
        }
    }

    // Method 5: Find orphaned branches (tracked but no longer exist locally or remotely)
    let local_output = Command::new("git")
        .args(["branch", "--format=%(refname:short)"])
        .current_dir(workdir)
        .output()
        .context("Failed to list local branches")?;
    let local_branches: std::collections::HashSet<String> =
        String::from_utf8_lossy(&local_output.stdout)
            .lines()
            .map(|s| s.trim().to_string())
            .collect();
    for branch in stack.branches.keys() {
        // Skip trunk
        if branch == &stack.trunk {
            continue;
        }

        // Skip if already in merged list
        if merged.contains(branch) {
            continue;
        }

        let local_exists = local_branches.contains(branch);
        let remote_exists = remote_branches.contains(branch.as_str());

        // If branch doesn't exist locally AND doesn't exist remotely, it's orphaned
        if !local_exists && !remote_exists {
            merged.push(branch.clone());
        }
    }

    // Method 3: Patch-id provenance check — detects squash/rebase merges even
    // when trunk has advanced past the merge point (where a simple tree diff
    // would show false negatives). Run this last so cheaper signals resolve
    // most cases before the provenance path touches more refs.
    let trunk = stack.trunk.as_str();
    let mut need_patch_id: Vec<(String, String)> = Vec::new();

    for branch in stack.branches.keys() {
        if branch == &stack.trunk || merged.contains(branch) {
            continue;
        }
        // Remote still exists -> not merged via squash-delete; skip expensive check.
        if remote_branches.contains(branch.as_str()) {
            continue;
        }
        match repo.is_branch_merged_cheap(branch) {
            Ok(Some(())) => merged.push(branch.clone()),
            Ok(None) => {
                if let Ok(mb) = repo.merge_base(trunk, branch) {
                    need_patch_id.push((branch.clone(), mb));
                }
            }
            Err(_) => {}
        }
    }

    if !need_patch_id.is_empty() {
        let mut by_merge_base: HashMap<String, Vec<String>> = HashMap::new();
        for (branch, mb) in need_patch_id {
            by_merge_base.entry(mb).or_default().push(branch);
        }

        for (merge_base, branches) in by_merge_base {
            let trunk_range = format!("{}..{}", merge_base, trunk);
            let trunk_count = match repo.rev_list_count(workdir, &trunk_range) {
                Ok(c) => c,
                Err(_) => {
                    for branch in branches {
                        if repo
                            .is_branch_merged_equivalent_to_trunk(&branch)
                            .unwrap_or(false)
                        {
                            merged.push(branch);
                        }
                    }
                    continue;
                }
            };

            if trunk_count > GitRepo::PATCH_ID_TRUNK_COMMIT_CAP {
                for branch in branches {
                    if repo
                        .is_branch_merged_equivalent_to_trunk(&branch)
                        .unwrap_or(false)
                    {
                        merged.push(branch);
                    }
                }
                continue;
            }

            let trunk_patch_ids = match repo.patch_ids_for_range(workdir, &trunk_range) {
                Ok(ids) => ids,
                Err(_) => {
                    for branch in branches {
                        if repo
                            .is_branch_merged_equivalent_to_trunk(&branch)
                            .unwrap_or(false)
                        {
                            merged.push(branch);
                        }
                    }
                    continue;
                }
            };

            for branch in branches {
                let branch_range = format!("{}..{}", merge_base, branch);
                let branch_patch_ids = match repo.patch_ids_for_range(workdir, &branch_range) {
                    Ok(ids) => ids,
                    Err(_) => continue,
                };
                if branch_patch_ids.is_empty() || branch_patch_ids.is_subset(&trunk_patch_ids) {
                    merged.push(branch);
                }
            }
        }
    }

    Ok(merged)
}

fn find_upstream_gone_branches(workdir: &std::path::Path, trunk: &str) -> Result<Vec<String>> {
    let output = Command::new("git")
        .args([
            "for-each-ref",
            "--format=%(refname:short)%00%(upstream:short)%00%(upstream:track)",
            "refs/heads",
        ])
        .current_dir(workdir)
        .output()
        .context("Failed to list local branches with upstream tracking info")?;

    let mut branches = std::collections::BTreeSet::new();
    let stdout = String::from_utf8_lossy(&output.stdout);

    for line in stdout.lines() {
        let mut fields = line.split('\0');
        let branch = fields.next().unwrap_or("").trim();
        let _upstream = fields.next().unwrap_or("").trim();
        let tracking = fields.next().unwrap_or("").trim();

        if branch.is_empty() || branch == trunk {
            continue;
        }

        if tracking.contains("[gone]") {
            branches.insert(branch.to_string());
        }
    }

    Ok(branches.into_iter().collect())
}

fn local_branch_exists(workdir: &std::path::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(|s| s.success())
        .unwrap_or(false)
}

fn plan_blocking_worktree_cleanup(
    repo: &GitRepo,
    branch: &str,
    force: bool,
) -> Result<Option<BlockingWorktreeCleanup>> {
    let Some(resolution) = repo.branch_delete_resolution(branch)? else {
        return Ok(None);
    };

    if resolution.worktree.is_main {
        return Ok(Some(BlockingWorktreeCleanup {
            resolution,
            blockers: Vec::new(),
        }));
    }

    let details = compute_worktree_details(repo, resolution.worktree.clone())?;
    Ok(Some(BlockingWorktreeCleanup {
        resolution,
        blockers: worktree_removal_blockers_for_cleanup(&details, force),
    }))
}

#[allow(clippy::too_many_arguments)]
fn delete_local_branch_for_sync(
    repo: &GitRepo,
    config: &Config,
    workdir: &std::path::Path,
    branch: &str,
    blocking_worktree_cleanup: Option<&BlockingWorktreeCleanup>,
    force: bool,
    confirmed_dirty_worktree_removal: bool,
    quiet: bool,
) -> Result<LocalBranchDeleteOutcome> {
    let mut outcome = attempt_local_branch_delete(workdir, branch);
    if outcome.deleted || !outcome.worktree_blocked {
        return Ok(outcome);
    }

    let Some(cleanup) = blocking_worktree_cleanup else {
        return Ok(outcome);
    };

    let force_remove_linked_worktree = force
        || (confirmed_dirty_worktree_removal
            && cleanup.can_force_remove_dirty_worktree_during_sync());
    if !cleanup.can_remove_during_sync() && !force_remove_linked_worktree {
        return Ok(outcome);
    }

    let removed_worktree = remove_worktree_with_hooks(
        repo,
        config,
        &cleanup.resolution.worktree,
        force_remove_linked_worktree,
    );
    match removed_worktree {
        Ok(display_name) => {
            if !quiet {
                println!(
                    "    {} removed linked worktree {}",
                    "→".cyan(),
                    display_name.cyan()
                );
            }
            outcome = attempt_local_branch_delete(workdir, branch);
            Ok(outcome)
        }
        Err(error) => {
            if !quiet {
                println!(
                    "    {} {}",
                    "↷".yellow(),
                    format!(
                        "couldn't remove linked worktree '{}': {}",
                        cleanup.resolution.worktree.name, error
                    )
                    .dimmed()
                );
            }
            Ok(outcome)
        }
    }
}

fn attempt_local_branch_delete(
    workdir: &std::path::Path,
    branch: &str,
) -> LocalBranchDeleteOutcome {
    let local_output = Command::new("git")
        .args(["branch", "-D", branch])
        .current_dir(workdir)
        .output();

    match local_output {
        Ok(out) => {
            let stderr = String::from_utf8_lossy(&out.stderr).to_string();
            LocalBranchDeleteOutcome {
                deleted: out.status.success(),
                worktree_blocked: stderr.contains("used by worktree"),
            }
        }
        Err(_) => LocalBranchDeleteOutcome::default(),
    }
}

fn sync_delete_prompt(
    branch: &str,
    checkout_target: Option<&str>,
    reason: Option<&str>,
    blocking_worktree_cleanup: Option<&BlockingWorktreeCleanup>,
) -> String {
    if let Some(target) = checkout_target {
        if let Some(reason) = reason {
            return format!("Delete '{}' ({reason}) and checkout '{}'?", branch, target);
        }

        return format!("Delete '{}' and checkout '{}'?", branch, target);
    }

    if let Some(cleanup) = blocking_worktree_cleanup {
        if cleanup.can_remove_during_sync() {
            if let Some(reason) = reason {
                return format!(
                    "Delete '{}' ({reason}) and remove linked worktree '{}'?",
                    branch, cleanup.resolution.worktree.name
                );
            }

            return format!(
                "Delete '{}' and remove linked worktree '{}'?",
                branch, cleanup.resolution.worktree.name
            );
        }

        if cleanup.can_force_remove_dirty_worktree_during_sync() {
            if let Some(reason) = reason {
                return format!(
                    "Delete '{}' ({reason}) and force-remove dirty linked worktree '{}'?",
                    branch, cleanup.resolution.worktree.name
                );
            }

            return format!(
                "Delete '{}' and force-remove dirty linked worktree '{}'?",
                branch, cleanup.resolution.worktree.name
            );
        }

        if let Some(reason) = reason {
            return format!(
                "Delete '{}' ({reason}; keep linked worktree '{}')?",
                branch, cleanup.resolution.worktree.name
            );
        }

        return format!(
            "Delete '{}' (keep linked worktree '{}')?",
            branch, cleanup.resolution.worktree.name
        );
    }

    if let Some(reason) = reason {
        format!("Delete '{}' ({reason})?", branch)
    } else {
        format!("Delete '{}'?", branch)
    }
}

fn print_blocked_branch_delete_recovery(
    branch: &str,
    blocking_worktree_cleanup: Option<&BlockingWorktreeCleanup>,
) {
    println!(
        "    {} {}",
        branch.bright_black(),
        "not deleted locally (checked out in another worktree)".yellow()
    );
    if let Some(cleanup) = blocking_worktree_cleanup {
        if let Some(reason) = cleanup.blocker_summary() {
            println!(
                "    {} {}",
                "↷".yellow(),
                format!(
                    "sync kept linked worktree '{}' because {}",
                    cleanup.resolution.worktree.name, reason
                )
                .dimmed()
            );
        }

        let resolution = &cleanup.resolution;
        if let Some(remove_cmd) = resolution.remove_worktree_and_branch_cmd() {
            println!(
                "    {} {}",
                "↷".yellow(),
                "Run to remove that worktree and delete the branch:".dimmed()
            );
            println!("      {}", remove_cmd.cyan());
        }
        println!(
            "    {} {}",
            "↷".yellow(),
            if resolution.worktree.is_main {
                "Run to free the branch in the main worktree:".dimmed()
            } else {
                "Or keep the worktree and free the branch:".dimmed()
            }
        );
        println!("      {}", resolution.switch_branch_cmd().cyan());
    }
}

fn checkout_branch_for_cleanup(
    repo: &GitRepo,
    workdir: &std::path::Path,
    branch: &str,
) -> std::result::Result<(), String> {
    if let Ok(Some(other_worktree_path)) = repo.branch_worktree_path(branch) {
        let current_path = std::fs::canonicalize(workdir).unwrap_or_else(|_| workdir.to_path_buf());
        let other_path = std::fs::canonicalize(&other_worktree_path)
            .unwrap_or_else(|_| other_worktree_path.clone());
        if other_path != current_path {
            return Err(format!(
                "'{}' is already checked out in another worktree at '{}'",
                branch,
                other_worktree_path.display()
            ));
        }
    }

    let output = Command::new("git")
        .args(["checkout", branch])
        .current_dir(workdir)
        .output()
        .map_err(|e| format!("git checkout '{}' failed: {}", branch, e))?;

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

    let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
    if stderr.is_empty() {
        Err(format!(
            "git checkout '{}' exited with {}",
            branch, output.status
        ))
    } else {
        Err(stderr)
    }
}

fn resolve_effective_parent(
    workdir: &std::path::Path,
    recorded_parent: &str,
    trunk: &str,
) -> (String, Option<String>) {
    if local_branch_exists(workdir, recorded_parent) {
        return (recorded_parent.to_string(), None);
    }

    if recorded_parent != trunk && local_branch_exists(workdir, trunk) {
        return (trunk.to_string(), Some(recorded_parent.to_string()));
    }

    (recorded_parent.to_string(), None)
}

/// Walk the parent chain from `branch` skipping any branch in `doomed` (e.g.
/// branches scheduled for deletion in the same sync pass). Returns the first
/// ancestor that is not doomed and still exists locally, falling back to trunk.
/// This prevents reparenting children onto a branch that is about to be deleted
/// when multiple branches in the same stack have their upstream gone.
fn resolve_fallback_parent_skipping_doomed(
    workdir: &std::path::Path,
    stack: &Stack,
    branch: &str,
    doomed: &[String],
) -> (String, Option<String>) {
    let recorded_parent = stack
        .branches
        .get(branch)
        .and_then(|b| b.parent.clone())
        .unwrap_or_else(|| stack.trunk.clone());

    let mut current = recorded_parent.clone();
    let mut visited: std::collections::HashSet<String> =
        std::collections::HashSet::from([branch.to_string()]);

    // Walk up the recorded-parent chain. `visited.insert` doubles as the cycle
    // guard: once we revisit a branch we fall through to the trunk fallback.
    while visited.insert(current.clone()) {
        let is_doomed = doomed.iter().any(|d| d == &current);
        if !is_doomed && local_branch_exists(workdir, &current) {
            let fallback_from = if current == recorded_parent {
                None
            } else {
                Some(recorded_parent.clone())
            };
            return (current, fallback_from);
        }
        // Walk up to the parent of `current`; if none, break to trunk.
        match stack.branches.get(&current).and_then(|b| b.parent.clone()) {
            Some(next) if next != current => current = next,
            _ => break,
        }
    }

    // Fall back to trunk if nothing else worked.
    let fallback_from = if recorded_parent == stack.trunk {
        None
    } else {
        Some(recorded_parent)
    };
    (stack.trunk.clone(), fallback_from)
}

/// Reparent tracked children of `branch` onto `new_parent`, preserving the old
/// parent boundary for later restack (see issue #120 rationale). Best-effort
/// updates the PR base on the forge when a child has a tracked PR.
///
/// Used by both the merged-branch and upstream-gone cleanup paths.
fn reparent_children_for_deletion(
    repo: &GitRepo,
    stack_snapshot: &Stack,
    branch: &str,
    new_parent: &str,
    forge_client: Option<&(tokio::runtime::Runtime, ForgeClient)>,
    quiet: bool,
) -> Result<()> {
    let children: Vec<String> = stack_snapshot
        .branches
        .iter()
        .filter(|(_, info)| info.parent.as_deref() == Some(branch))
        .map(|(name, _)| name.clone())
        .collect();
    let doomed_tip = repo.branch_commit(branch).ok();

    for child in &children {
        let Some(child_meta) = BranchMetadata::read(repo.inner(), child)? else {
            continue;
        };

        // Preserve the old-parent boundary so restack can run `git rebase
        // --onto <new> <old>` precisely. Only use the deleted branch's tip
        // when it is still in the child's ancestry; otherwise keep the
        // recorded revision (see #120).
        let old_parent_boundary = doomed_tip
            .clone()
            .filter(|tip| repo.is_ancestor(tip, child).unwrap_or(false))
            .unwrap_or_else(|| child_meta.parent_branch_revision.clone());

        let updated_meta = BranchMetadata {
            parent_branch_name: new_parent.to_string(),
            parent_branch_revision: old_parent_boundary,
            ..child_meta.clone()
        };
        updated_meta.write(repo.inner(), child)?;

        // Best-effort PR base update. Expected to fail when upstream is gone
        // (PR closed) — log and continue.
        if let (Some(pr_info), Some((rt, client))) = (&child_meta.pr_info, forge_client) {
            match rt.block_on(client.update_pr_base(pr_info.number, new_parent)) {
                Ok(()) => {
                    if !quiet {
                        println!(
                            "    {} updated PR #{} base → {}",
                            "↪".cyan(),
                            pr_info.number,
                            new_parent.cyan()
                        );
                    }
                }
                Err(e) => {
                    if !quiet {
                        println!(
                            "    {} couldn't update PR #{} base: {}",
                            "âš ".yellow(),
                            pr_info.number,
                            e
                        );
                    }
                }
            }
        }

        if !quiet {
            println!(
                "    {} reparented {} → {}",
                "↪".cyan(),
                child.cyan(),
                new_parent.cyan()
            );
        }
    }
    Ok(())
}

/// Record CI history for merged branches before they are deleted
fn record_ci_history_for_merged(
    repo: &GitRepo,
    rt: &tokio::runtime::Runtime,
    client: &ForgeClient,
    merged_branches: &[String],
    stack: &Stack,
    quiet: bool,
) {
    // Only process branches that still exist locally (can get their commit SHA)
    let branches_to_check: Vec<String> = merged_branches
        .iter()
        .filter(|b| repo.branch_commit(b).is_ok())
        .cloned()
        .collect();

    if branches_to_check.is_empty() {
        return;
    }

    let ci_timer = LiveTimer::maybe_new(!quiet, "Record CI history");

    // Fetch CI statuses for merged branches
    match fetch_ci_statuses(repo, rt, client, stack, &branches_to_check) {
        Ok(statuses) => {
            record_ci_history(repo, &statuses);
            LiveTimer::maybe_finish_timed(ci_timer);
        }
        Err(_) => {
            LiveTimer::maybe_finish_warn(ci_timer, "skipped (couldn't fetch)");
        }
    }
}

fn format_duration(duration: Duration) -> String {
    format!("{:.3}s", duration.as_secs_f64())
}

fn render_sync_footer(stats: &SyncStats, total_duration: Duration) -> String {
    let mut parts = Vec::new();

    if let Some(trunk) = &stats.trunk {
        match trunk {
            TrunkSummary::UpToDate { branch } => {
                parts.push(format!(
                    "{} {}",
                    branch.cyan().bold(),
                    "up to date".dimmed()
                ));
            }
            TrunkSummary::Pulled {
                branch,
                commits,
                additions,
                deletions,
            } => {
                parts.push(format!(
                    "{} {}",
                    branch.cyan().bold(),
                    format!(
                        "+{} commit{}",
                        commits,
                        if *commits == 1 { "" } else { "s" }
                    )
                    .green()
                ));
                parts.push(format!(
                    "{} {}",
                    format!("+{}", additions).green(),
                    format!("-{}", deletions).red()
                ));
            }
            TrunkSummary::Updated { branch } => {
                parts.push(format!("{} {}", branch.cyan().bold(), "updated".yellow()));
            }
        }
    }

    if stats.merged_branches_cleaned > 0 {
        parts.push(format!(
            "{} {} {}",
            "cleaned".dimmed(),
            stats.merged_branches_cleaned.to_string().cyan().bold(),
            "merged".dimmed()
        ));
    }

    if stats.restacked_branches > 0 {
        parts.push(format!(
            "{} {}",
            "restacked".dimmed(),
            stats.restacked_branches.to_string().cyan().bold()
        ));
    }

    parts.push(format!("{}", format_duration(total_duration).cyan()));
    parts.join(&format!("{}", " | ".dimmed()))
}

fn summarize_trunk_sync(
    workdir: &Path,
    branch: &str,
    local_before: Option<&str>,
    remote_after_fetch: Option<&str>,
) -> Option<TrunkSummary> {
    let local_after = resolve_ref_oid(workdir, branch)?;

    if let Some(remote_after_fetch) = remote_after_fetch {
        if local_after == remote_after_fetch {
            if let Some(local_before) = local_before {
                if local_before == local_after {
                    return Some(TrunkSummary::UpToDate {
                        branch: branch.to_string(),
                    });
                }

                if is_ancestor(workdir, local_before, &local_after) {
                    let commits = count_commits_between(workdir, local_before, &local_after)?;
                    let (additions, deletions) =
                        diff_line_stats_between(workdir, local_before, &local_after)?;
                    return Some(TrunkSummary::Pulled {
                        branch: branch.to_string(),
                        commits,
                        additions,
                        deletions,
                    });
                }
            }

            return Some(TrunkSummary::Updated {
                branch: branch.to_string(),
            });
        }
    }

    None
}

fn resolve_ref_oid(workdir: &Path, reference: &str) -> Option<String> {
    let output = Command::new("git")
        .args(["rev-parse", reference])
        .current_dir(workdir)
        .output()
        .ok()?;

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

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

fn is_ancestor(workdir: &Path, ancestor: &str, descendant: &str) -> bool {
    Command::new("git")
        .args(["merge-base", "--is-ancestor", ancestor, descendant])
        .current_dir(workdir)
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

fn count_commits_between(workdir: &Path, base: &str, head: &str) -> Option<usize> {
    let output = Command::new("git")
        .args(["rev-list", "--count", &format!("{}..{}", base, head)])
        .current_dir(workdir)
        .output()
        .ok()?;

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

    String::from_utf8_lossy(&output.stdout).trim().parse().ok()
}

fn diff_line_stats_between(workdir: &Path, base: &str, head: &str) -> Option<(usize, usize)> {
    let output = Command::new("git")
        .args(["diff", "--numstat", &format!("{}..{}", base, head)])
        .current_dir(workdir)
        .output()
        .ok()?;

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

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut additions = 0usize;
    let mut deletions = 0usize;

    for line in stdout.lines() {
        let parts: Vec<&str> = line.split('\t').collect();
        if parts.len() >= 2 {
            if let Ok(add) = parts[0].parse::<usize>() {
                additions += add;
            }
            if let Ok(del) = parts[1].parse::<usize>() {
                deletions += del;
            }
        }
    }

    Some((additions, deletions))
}

#[cfg(test)]
mod tests {
    use super::*;
    use colored::control;
    use std::path::PathBuf;

    fn linked_worktree_cleanup(blockers: &[&'static str]) -> BlockingWorktreeCleanup {
        BlockingWorktreeCleanup {
            resolution: crate::git::repo::BranchDeleteResolution {
                worktree: crate::git::repo::WorktreeInfo {
                    name: "review-pass".to_string(),
                    path: PathBuf::from("/tmp/review-pass"),
                    branch: Some("cesar/review-pass".to_string()),
                    is_main: false,
                    is_current: false,
                    is_locked: false,
                    lock_reason: None,
                    is_prunable: false,
                    prunable_reason: None,
                },
                remove_worktree_selector: "cesar/review-pass".to_string(),
                switch_target: crate::git::repo::BranchDeleteSwitchTarget::Detach,
            },
            blockers: blockers.to_vec(),
        }
    }

    #[test]
    fn render_sync_footer_is_colored_and_compact() {
        control::set_override(true);

        let footer = render_sync_footer(
            &SyncStats {
                trunk: Some(TrunkSummary::Pulled {
                    branch: "main".to_string(),
                    commits: 1,
                    additions: 434,
                    deletions: 22,
                }),
                merged_branches_cleaned: 2,
                restacked_branches: 1,
            },
            Duration::from_millis(14_022),
        );

        control::unset_override();

        assert!(footer.contains("main"));
        assert!(footer.contains("+1 commit"));
        assert!(footer.contains("+434"));
        assert!(footer.contains("-22"));
        assert!(footer.contains("cleaned"));
        assert!(footer.contains("restacked"));
        assert!(footer.contains("14.022s"));
        assert!(footer.contains('\u{1b}'));
    }

    #[test]
    fn render_sync_footer_handles_up_to_date_branch() {
        control::set_override(true);

        let footer = render_sync_footer(
            &SyncStats {
                trunk: Some(TrunkSummary::UpToDate {
                    branch: "main".to_string(),
                }),
                merged_branches_cleaned: 0,
                restacked_branches: 0,
            },
            Duration::from_secs(2),
        );

        control::unset_override();

        assert!(footer.contains("main"));
        assert!(footer.contains("up to date"));
        assert!(footer.contains("2.000s"));
        assert!(footer.contains('\u{1b}'));
    }

    #[test]
    fn sync_delete_prompt_mentions_removed_linked_worktree_for_safe_non_current_branch() {
        let prompt = sync_delete_prompt(
            "cesar/review-pass",
            None,
            None,
            Some(&linked_worktree_cleanup(&[])),
        );

        assert_eq!(
            prompt,
            "Delete 'cesar/review-pass' and remove linked worktree 'review-pass'?"
        );
    }

    #[test]
    fn sync_delete_prompt_prefers_checkout_wording_for_current_branch() {
        let prompt = sync_delete_prompt(
            "cesar/review-pass",
            Some("main"),
            Some("upstream gone"),
            Some(&linked_worktree_cleanup(&[])),
        );

        assert_eq!(
            prompt,
            "Delete 'cesar/review-pass' (upstream gone) and checkout 'main'?"
        );
    }

    #[test]
    fn sync_delete_prompt_mentions_force_removed_dirty_linked_worktree_when_confirmable() {
        let prompt = sync_delete_prompt(
            "cesar/review-pass",
            None,
            Some("upstream gone"),
            Some(&linked_worktree_cleanup(&["dirty"])),
        );

        assert_eq!(
            prompt,
            "Delete 'cesar/review-pass' (upstream gone) and force-remove dirty linked worktree 'review-pass'?"
        );
    }

    #[test]
    fn sync_delete_prompt_mentions_kept_linked_worktree_when_still_unsafe() {
        let prompt = sync_delete_prompt(
            "cesar/review-pass",
            None,
            Some("upstream gone"),
            Some(&linked_worktree_cleanup(&["dirty", "locked"])),
        );

        assert_eq!(
            prompt,
            "Delete 'cesar/review-pass' (upstream gone; keep linked worktree 'review-pass')?"
        );
    }
}