stakk 1.11.0

A CLI tool that bridges Jujutsu (jj) bookmarks to GitHub stacked pull requests
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
//! Three-phase submission: analyze, plan, execute.
//!
//! Takes a change graph and forge implementation and submits bookmarks as
//! stacked pull requests, updating existing PRs idempotently.

mod unwrap;

use std::collections::HashSet;
use std::fmt;

use miette::Diagnostic;
use thiserror::Error;

use crate::cli::submit::PrMode;
use crate::forge::CreatePrParams;
use crate::forge::Forge;
use crate::forge::ForgeError;
use crate::forge::PullRequest;
use crate::forge::comment::STAKK_REPO_URL;
use crate::forge::comment::StackCommentContext;
use crate::forge::comment::StackCommentData;
use crate::forge::comment::StackEntry;
use crate::forge::comment::StackEntryContext;
use crate::forge::comment::StackPlacement;
use crate::forge::comment::find_stack_comment;
use crate::forge::comment::find_stack_in_body;
use crate::forge::comment::format_stack_comment;
use crate::forge::comment::splice_stack_into_body;
use crate::forge::comment::strip_stack_from_body;
use crate::forge::comment::with_comment_preamble;
use crate::graph::types::BookmarkSegment;
use crate::graph::types::ChangeGraph;
use crate::graph::types::SegmentCommit;
use crate::jj::Jj;
use crate::jj::JjError;
use crate::jj::runner::JjRunner;
use crate::submit::unwrap::unwrap_markdown;

/// Errors from the submission pipeline.
#[derive(Debug, Error, Diagnostic)]
pub enum SubmitError {
    /// Target bookmark was not found in any stack.
    #[error("bookmark '{bookmark}' not found in any stack")]
    #[diagnostic(
        code(stakk::submit::bookmark_not_found),
        help("run `stakk` with no arguments to see available stacks")
    )]
    BookmarkNotFound { bookmark: String },

    /// A segment in the change graph has no bookmark name.
    #[error("segment has no bookmark name")]
    #[diagnostic(code(stakk::submit::segment_missing_bookmark))]
    SegmentMissingBookmark,

    /// Failed to look up an existing PR for a bookmark.
    #[error("failed to check for existing PR for '{bookmark}'")]
    #[diagnostic(code(stakk::submit::pr_lookup_failed))]
    PrLookupFailed {
        bookmark: String,
        #[source]
        source: ForgeError,
    },

    /// Failed to push a bookmark to the remote.
    #[error("failed to push bookmark '{bookmark}'")]
    #[diagnostic(code(stakk::submit::push_failed))]
    PushFailed {
        bookmark: String,
        #[source]
        source: JjError,
    },

    /// Failed to update the base branch of an existing PR.
    #[error("failed to update PR base for '{bookmark}'")]
    #[diagnostic(code(stakk::submit::base_update_failed))]
    BaseUpdateFailed {
        bookmark: String,
        #[source]
        source: ForgeError,
    },

    /// Failed to create a new PR.
    #[error("failed to create PR for '{bookmark}'")]
    #[diagnostic(code(stakk::submit::pr_create_failed))]
    PrCreateFailed {
        bookmark: String,
        #[source]
        source: ForgeError,
    },

    /// Failed to create or update a stack comment on a PR.
    #[error("failed to manage stack comment on PR #{pr_number}")]
    #[diagnostic(code(stakk::submit::comment_failed))]
    CommentFailed {
        pr_number: u64,
        #[source]
        source: ForgeError,
    },

    /// Failed to render a stack comment template.
    #[error("template rendering failed: {message}")]
    #[diagnostic(
        code(stakk::submit::template_render_failed),
        help("check the template syntax (minijinja/Jinja2)")
    )]
    TemplateRenderFailed { message: String },

    /// Failed to update a PR body.
    #[error("failed to update body of PR #{pr_number}")]
    #[diagnostic(code(stakk::submit::body_update_failed))]
    BodyUpdateFailed {
        pr_number: u64,
        #[source]
        source: ForgeError,
    },
}

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// Phase 1 output: the segments relevant to a submission.
#[derive(Debug, Clone)]
pub struct SubmissionAnalysis {
    /// Segments from trunk to the target bookmark, inclusive.
    /// Ordered trunk-to-leaf (same as `BranchStack::segments`).
    pub segments: Vec<BookmarkSegment>,
    /// The default branch name (e.g., "main").
    pub default_branch: String,
}

/// One bookmark's planned actions.
#[derive(Debug, Clone)]
pub struct BookmarkPlan {
    /// The bookmark name (first from `segment.bookmark_names`).
    pub bookmark_name: String,
    /// The base branch for this PR (default branch or previous bookmark).
    pub base: String,
    /// PR title (derived from first commit description).
    pub title: String,
    /// PR body built from commit descriptions, if any.
    pub body: Option<String>,
    /// Existing PR if one was found on GitHub.
    pub existing_pr: Option<PullRequest>,
    /// Whether the bookmark needs pushing.
    pub needs_push: bool,
    /// Whether a new PR must be created.
    pub needs_create: bool,
    /// Whether the existing PR's base needs updating.
    pub needs_base_update: bool,
}

/// Phase 2 output: the full submission plan.
#[derive(Debug)]
pub struct SubmissionPlan {
    /// Per-bookmark plans, ordered trunk-to-leaf.
    pub bookmark_plans: Vec<BookmarkPlan>,
    /// The remote name to push to.
    pub remote: String,
    /// Whether to create PRs as regular or draft.
    pub pr_mode: PrMode,
    /// The default branch name (e.g., "main").
    pub default_branch: String,
}

/// Phase 3 output: what was actually done.
#[derive(Debug)]
pub struct SubmissionResult {
    /// Stack entries for all submitted bookmarks.
    pub stack_entries: Vec<StackEntry>,
}

// ---------------------------------------------------------------------------
// Phase 1: Analysis
// ---------------------------------------------------------------------------

/// Find the segments relevant to submitting the target bookmark.
///
/// Locates the stack containing `target_bookmark` in the change graph and
/// returns all segments from trunk to the target (inclusive).
pub fn analyze_submission(
    target_bookmark: &str,
    change_graph: &ChangeGraph,
    default_branch: &str,
    selected_bookmarks: &HashSet<String>,
) -> Result<SubmissionAnalysis, SubmitError> {
    let stack = change_graph
        .stacks
        .iter()
        .find(|s| {
            s.segments
                .iter()
                .any(|seg| seg.bookmark_names.contains(&target_bookmark.to_string()))
        })
        .ok_or_else(|| SubmitError::BookmarkNotFound {
            bookmark: target_bookmark.to_string(),
        })?;

    let target_index = stack
        .segments
        .iter()
        .position(|seg| seg.bookmark_names.contains(&target_bookmark.to_string()))
        .expect("bookmark was found in stack above");

    let mut segments = Vec::new();
    let mut accumulated_commits: Vec<SegmentCommit> = Vec::new();

    for seg in &stack.segments[..=target_index] {
        let is_selected = seg
            .bookmark_names
            .iter()
            .any(|name| selected_bookmarks.contains(name));

        if is_selected {
            let mut commits = seg.commits.clone();
            commits.append(&mut accumulated_commits);
            segments.push(BookmarkSegment {
                bookmark_names: seg.bookmark_names.clone(),
                change_id: seg.change_id.clone(),
                commits,
            });
        } else {
            accumulated_commits.extend(seg.commits.iter().cloned());
        }
    }

    Ok(SubmissionAnalysis {
        segments,
        default_branch: default_branch.to_string(),
    })
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Build a PR body from segment commit descriptions.
///
/// - Single commit: lines after the first (the title line) become the body.
/// - Multiple commits: concatenate all descriptions with `---` separators.
/// - If the result is empty or whitespace-only, returns `None`.
fn build_pr_body(commits: &[SegmentCommit]) -> Option<String> {
    if commits.is_empty() {
        return None;
    }

    let body = if commits.len() == 1 {
        // Single commit: strip the first line (title) and use the rest.
        let desc = commits[0].description.trim();
        let rest = desc.lines().skip(1).collect::<Vec<_>>().join("\n");
        rest.trim().to_string()
    } else {
        // Multiple commits: concatenate all descriptions.
        let parts: Vec<&str> = commits
            .iter()
            .map(|c| c.description.trim())
            .filter(|d: &&str| !d.is_empty())
            .collect();
        parts.join("\n\n---\n\n")
    };

    if body.is_empty() {
        None
    } else {
        Some(unwrap_markdown(&body))
    }
}

// ---------------------------------------------------------------------------
// Phase 2: Planning
// ---------------------------------------------------------------------------

/// Query the forge to determine what actions are needed for each bookmark.
///
/// For each segment in the analysis, checks the forge for existing PRs and
/// determines whether to push, create, or update.
pub async fn create_submission_plan<F: Forge>(
    analysis: &SubmissionAnalysis,
    forge: &F,
    remote: &str,
    pr_mode: PrMode,
) -> Result<SubmissionPlan, SubmitError> {
    // Collect bookmark names for concurrent PR lookup.
    let bookmark_names: Vec<String> = analysis
        .segments
        .iter()
        .map(|seg| {
            seg.bookmark_names
                .first()
                .cloned()
                .ok_or(SubmitError::SegmentMissingBookmark)
        })
        .collect::<Result<_, _>>()?;

    // Concurrently check for existing PRs for all bookmarks.
    let pr_futures: Vec<_> = bookmark_names
        .iter()
        .map(|name| forge.find_pr_for_branch(name))
        .collect();
    let pr_results = futures::future::join_all(pr_futures).await;

    let mut bookmark_plans = Vec::new();

    for (i, (segment, pr_result)) in analysis.segments.iter().zip(pr_results).enumerate() {
        let bookmark_name = bookmark_names[i].clone();

        let base = if i == 0 {
            analysis.default_branch.clone()
        } else {
            bookmark_names[i - 1].clone()
        };

        let title = segment.commits.first().map_or_else(
            || bookmark_name.clone(),
            |c| {
                c.description
                    .lines()
                    .next()
                    .unwrap_or(&c.description)
                    .to_string()
            },
        );

        let existing_pr = pr_result.map_err(|source| SubmitError::PrLookupFailed {
            bookmark: bookmark_name.clone(),
            source,
        })?;

        let needs_base_update = existing_pr.as_ref().is_some_and(|pr| pr.base_ref != base);

        let needs_create = existing_pr.is_none();

        let body = build_pr_body(&segment.commits);

        bookmark_plans.push(BookmarkPlan {
            bookmark_name,
            base,
            title,
            body,
            existing_pr,
            needs_push: true,
            needs_create,
            needs_base_update,
        });
    }

    Ok(SubmissionPlan {
        bookmark_plans,
        remote: remote.to_string(),
        pr_mode,
        default_branch: analysis.default_branch.clone(),
    })
}

// ---------------------------------------------------------------------------
// Phase 2: Display (for --dry-run)
// ---------------------------------------------------------------------------

impl fmt::Display for SubmissionPlan {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let draft_label = if self.pr_mode == PrMode::Draft {
            ", draft"
        } else {
            ""
        };
        writeln!(
            f,
            "Submission plan ({} bookmark(s), remote: {}{draft_label}):",
            self.bookmark_plans.len(),
            self.remote,
        )?;

        for bp in &self.bookmark_plans {
            writeln!(f, "  {} (base: {})", bp.bookmark_name, bp.base)?;
            if bp.needs_push {
                writeln!(f, "    - push bookmark to {}", self.remote)?;
            }
            if bp.needs_create {
                writeln!(f, "    - create PR: \"{}\"", bp.title)?;
            }
            if bp.needs_base_update
                && let Some(pr) = &bp.existing_pr
            {
                writeln!(
                    f,
                    "    - update PR #{} base: {} -> {}",
                    pr.number, pr.base_ref, bp.base,
                )?;
            }
            if !bp.needs_create
                && !bp.needs_base_update
                && let Some(pr) = &bp.existing_pr
            {
                writeln!(f, "    - PR #{} up to date", pr.number)?;
            }
        }

        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Phase 3: Execution
// ---------------------------------------------------------------------------

/// Execute the submission plan: push, create PRs, update bases, manage
/// comments.
pub async fn execute_submission_plan<R: JjRunner, F: Forge>(
    plan: &SubmissionPlan,
    jj: &Jj<R>,
    forge: &F,
    comment_env: &minijinja::Environment<'_>,
    placement: StackPlacement,
) -> Result<SubmissionResult, SubmitError> {
    let pb = indicatif::ProgressBar::new_spinner();
    pb.enable_steady_tick(std::time::Duration::from_millis(120));

    let mut stack_entries = Vec::new();

    // Process each bookmark trunk-to-leaf: push, update base, create PR.
    // Each bookmark must be fully processed before the next is pushed to
    // prevent transient empty diffs that trigger GitHub auto-close (#35).
    for bp in &plan.bookmark_plans {
        if bp.needs_push {
            pb.set_message(format!("Pushing bookmark: {}", bp.bookmark_name));
            jj.push_bookmark(&bp.bookmark_name, &plan.remote)
                .await
                .map_err(|source| SubmitError::PushFailed {
                    bookmark: bp.bookmark_name.clone(),
                    source,
                })?;
        }

        if bp.needs_base_update
            && let Some(pr) = &bp.existing_pr
        {
            pb.set_message(format!("Updating PR #{} base...", pr.number));
            forge
                .update_pr_base(pr.number, &bp.base)
                .await
                .map_err(|source| SubmitError::BaseUpdateFailed {
                    bookmark: bp.bookmark_name.clone(),
                    source,
                })?;
        }

        let pr = if let Some(existing) = &bp.existing_pr {
            pb.println(format!(
                "  Existing PR #{}: {}",
                existing.number, existing.html_url,
            ));
            existing.clone()
        } else {
            pb.set_message(format!("Creating PR: {}", bp.title));
            let pr = forge
                .create_pr(CreatePrParams {
                    title: bp.title.clone(),
                    head: bp.bookmark_name.clone(),
                    base: bp.base.clone(),
                    body: bp.body.clone(),
                    draft: plan.pr_mode == PrMode::Draft,
                })
                .await
                .map_err(|source| SubmitError::PrCreateFailed {
                    bookmark: bp.bookmark_name.clone(),
                    source,
                })?;
            pb.println(format!("  Created PR #{}: {}", pr.number, pr.html_url,));
            pr
        };

        stack_entries.push(StackEntry {
            bookmark_name: bp.bookmark_name.clone(),
            pr_url: pr.html_url.clone(),
            pr_number: pr.number,
        });
    }

    // Step 3: Concurrently create/update stack comments on all PRs.
    // For single-bookmark submissions, skip stack info entirely and just
    // clean up any stale stack artifacts from a previously larger stack.
    if stack_entries.len() > 1 {
        pb.set_message("Updating stack comments...");
        let comment_data = StackCommentData {
            version: 0,
            stack: stack_entries.clone(),
        };

        let template = comment_env.get_template("stack_comment").map_err(|e| {
            SubmitError::TemplateRenderFailed {
                message: e.to_string(),
            }
        })?;

        // Build the shared entry contexts from stack_entries + bookmark_plans.
        let entry_contexts: Vec<StackEntryContext> = stack_entries
            .iter()
            .enumerate()
            .map(|(i, entry)| {
                let bp = &plan.bookmark_plans[i];
                StackEntryContext {
                    bookmark_name: entry.bookmark_name.clone(),
                    pr_url: entry.pr_url.clone(),
                    pr_number: entry.pr_number,
                    title: bp.title.clone(),
                    base: bp.base.clone(),
                    is_draft: plan.pr_mode == PrMode::Draft && bp.needs_create,
                    position: i + 1,
                    is_current: false, // set per-PR below
                }
            })
            .collect();

        match placement {
            StackPlacement::Comment => {
                let comment_futures: Vec<_> = stack_entries
                    .iter()
                    .enumerate()
                    .map(|(i, entry)| {
                        let mut entries = entry_contexts.clone();
                        entries[i].is_current = true;
                        let ctx = StackCommentContext {
                            stack_size: entries.len(),
                            current_bookmark: entry.bookmark_name.clone(),
                            default_branch: plan.default_branch.clone(),
                            stakk_url: STAKK_REPO_URL.to_string(),
                            stack: entries,
                        };

                        let rendered = format_stack_comment(&comment_data, &ctx, &template)
                            .map(|s| with_comment_preamble(&s));
                        let pr_number = entry.pr_number;
                        let existing_body = plan.bookmark_plans[i]
                            .existing_pr
                            .as_ref()
                            .and_then(|pr| pr.body.clone());
                        let pb = &pb;
                        async move {
                            let rendered = rendered?;
                            let existing_comments =
                                forge.list_comments(pr_number).await.map_err(|source| {
                                    SubmitError::CommentFailed { pr_number, source }
                                })?;

                            if let Some(existing) = find_stack_comment(&existing_comments) {
                                forge.update_comment(existing.id, &rendered).await.map_err(
                                    |source| SubmitError::CommentFailed { pr_number, source },
                                )?;
                            } else {
                                forge.create_comment(pr_number, &rendered).await.map_err(
                                    |source| SubmitError::CommentFailed { pr_number, source },
                                )?;

                                // Migration: if switching from body mode, strip
                                // the fenced section from the PR body.
                                if let Some(body) = &existing_body
                                    && find_stack_in_body(body).is_some()
                                {
                                    let stripped = strip_stack_from_body(body);
                                    if let Err(e) = forge.update_pr_body(pr_number, &stripped).await
                                    {
                                        pb.println(format!(
                                            "  Warning: failed to strip stack from PR \
                                             #{pr_number} body during migration: {e}"
                                        ));
                                    }
                                }
                            }
                            Ok::<(), SubmitError>(())
                        }
                    })
                    .collect();
                let comment_results = futures::future::join_all(comment_futures).await;
                for result in comment_results {
                    result?;
                }
            }
            StackPlacement::Body => {
                let body_futures: Vec<_> =
                    stack_entries
                        .iter()
                        .enumerate()
                        .map(|(i, entry)| {
                            let mut entries = entry_contexts.clone();
                            entries[i].is_current = true;
                            let ctx = StackCommentContext {
                                stack_size: entries.len(),
                                current_bookmark: entry.bookmark_name.clone(),
                                default_branch: plan.default_branch.clone(),
                                stakk_url: STAKK_REPO_URL.to_string(),
                                stack: entries,
                            };

                            let rendered = format_stack_comment(&comment_data, &ctx, &template);
                            let pr_number = entry.pr_number;
                            let bp = &plan.bookmark_plans[i];
                            let existing_body = if bp.needs_create {
                                // For newly created PRs, use the body we just
                                // submitted.
                                bp.body.clone().unwrap_or_default()
                            } else {
                                bp.existing_pr
                                    .as_ref()
                                    .and_then(|pr| pr.body.clone())
                                    .unwrap_or_default()
                            };
                            let had_fence = find_stack_in_body(&existing_body).is_some();
                            let pb = &pb;
                            async move {
                                let rendered = rendered?;
                                let new_body = splice_stack_into_body(&existing_body, &rendered);
                                forge.update_pr_body(pr_number, &new_body).await.map_err(
                                    |source| SubmitError::BodyUpdateFailed { pr_number, source },
                                )?;

                                // Migration: if no existing fenced section was found,
                                // check for an old stack comment and delete it.
                                if !had_fence {
                                    let comments =
                                        forge.list_comments(pr_number).await.map_err(|source| {
                                            SubmitError::CommentFailed { pr_number, source }
                                        })?;
                                    if let Some(old) = find_stack_comment(&comments)
                                        && let Err(e) = forge.delete_comment(old.id).await
                                    {
                                        pb.println(format!(
                                            "  Warning: failed to delete old stack comment on PR \
                                             #{pr_number} during migration: {e}"
                                        ));
                                    }
                                }
                                Ok::<(), SubmitError>(())
                            }
                        })
                        .collect();
                let body_results = futures::future::join_all(body_futures).await;
                for result in body_results {
                    result?;
                }
            }
        }
    } else if stack_entries.len() == 1 {
        // Single bookmark — not a stack. Clean up any stale stack artifacts
        // from when this PR was part of a larger stack.
        let entry = &stack_entries[0];
        let pr_number = entry.pr_number;
        let existing_body = plan.bookmark_plans[0]
            .existing_pr
            .as_ref()
            .and_then(|pr| pr.body.clone());

        // Clean up old stack comment (from either comment mode or pre-migration).
        let comments = forge
            .list_comments(pr_number)
            .await
            .map_err(|source| SubmitError::CommentFailed { pr_number, source })?;
        if let Some(old) = find_stack_comment(&comments)
            && let Err(e) = forge.delete_comment(old.id).await
        {
            pb.println(format!(
                "  Warning: failed to clean up old stack comment on PR #{pr_number}: {e}"
            ));
        }

        // Clean up old body fence (from body mode).
        if let Some(body) = &existing_body
            && find_stack_in_body(body).is_some()
        {
            let stripped = strip_stack_from_body(body);
            if let Err(e) = forge.update_pr_body(pr_number, &stripped).await {
                pb.println(format!(
                    "  Warning: failed to strip stack from PR #{pr_number} body: {e}"
                ));
            }
        }
    }

    pb.finish_and_clear();

    Ok(SubmissionResult { stack_entries })
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::sync::Arc;
    use std::sync::Mutex;

    use super::*;
    use crate::forge::Comment;
    use crate::forge::ForgeError;
    use crate::forge::PrState;
    use crate::forge::comment::build_comment_env;
    use crate::graph::types::BranchStack;
    use crate::graph::types::SegmentCommit;
    use crate::jj::JjError;

    // -- Shared operation log for ordering tests --

    type OpLog = Arc<Mutex<Vec<Op>>>;

    #[derive(Debug, Clone, PartialEq, Eq)]
    enum Op {
        Push(String),
        BaseUpdate(u64),
        CreatePr(String),
    }

    // -- Test helpers --

    fn test_comment_env() -> minijinja::Environment<'static> {
        build_comment_env(None).unwrap()
    }

    fn make_segment(names: &[&str], change_id: &str, desc: &str) -> BookmarkSegment {
        BookmarkSegment {
            bookmark_names: names.iter().map(ToString::to_string).collect(),
            change_id: change_id.to_string(),
            commits: vec![SegmentCommit {
                commit_id: format!("c_{change_id}"),
                change_id: change_id.to_string(),
                description: desc.to_string(),
                author: crate::jj::types::Signature {
                    name: "Test".to_string(),
                    email: "test@test.com".to_string(),
                    timestamp: "T".to_string(),
                },
                committer: crate::jj::types::Signature {
                    name: "Test".to_string(),
                    email: "test@test.com".to_string(),
                    timestamp: "T".to_string(),
                },
                files: vec![],
                short_change_id: change_id[..4.min(change_id.len())].to_string(),
            }],
        }
    }

    fn make_graph(stacks: Vec<BranchStack>) -> ChangeGraph {
        ChangeGraph {
            adjacency_list: HashMap::new(),
            stack_leaves: std::collections::HashSet::new(),
            stack_roots: std::collections::HashSet::new(),
            segments: HashMap::new(),
            tainted_change_ids: std::collections::HashSet::new(),
            excluded_bookmark_count: 0,
            stacks,
        }
    }

    fn make_pr(number: u64, head: &str, base: &str) -> PullRequest {
        PullRequest {
            number,
            html_url: format!("https://github.com/test/repo/pull/{number}"),
            title: format!("PR for {head}"),
            head_ref: head.to_string(),
            base_ref: base.to_string(),
            state: PrState::Open,
            body: None,
        }
    }

    fn make_pr_with_body(number: u64, head: &str, base: &str, body: &str) -> PullRequest {
        PullRequest {
            number,
            html_url: format!("https://github.com/test/repo/pull/{number}"),
            title: format!("PR for {head}"),
            head_ref: head.to_string(),
            base_ref: base.to_string(),
            state: PrState::Open,
            body: Some(body.to_string()),
        }
    }

    // -- Mock Forge --

    struct MockForge {
        existing_prs: HashMap<String, PullRequest>,
        created_prs: Mutex<Vec<CreatePrParams>>,
        created_comments: Mutex<Vec<(u64, String)>>,
        updated_comments: Mutex<Vec<(u64, String)>>,
        updated_bases: Mutex<Vec<(u64, String)>>,
        updated_bodies: Mutex<Vec<(u64, String)>>,
        deleted_comments: Mutex<Vec<u64>>,
        existing_comments: HashMap<u64, Vec<Comment>>,
        next_pr_number: Mutex<u64>,
        ops: Option<OpLog>,
    }

    impl MockForge {
        fn new() -> Self {
            Self {
                existing_prs: HashMap::new(),
                created_prs: Mutex::new(Vec::new()),
                created_comments: Mutex::new(Vec::new()),
                updated_comments: Mutex::new(Vec::new()),
                updated_bases: Mutex::new(Vec::new()),
                updated_bodies: Mutex::new(Vec::new()),
                deleted_comments: Mutex::new(Vec::new()),
                existing_comments: HashMap::new(),
                next_pr_number: Mutex::new(100),
                ops: None,
            }
        }

        fn with_ops(mut self, ops: OpLog) -> Self {
            self.ops = Some(ops);
            self
        }

        fn with_existing_pr(mut self, head: &str, pr: PullRequest) -> Self {
            self.existing_prs.insert(head.to_string(), pr);
            self
        }

        fn with_existing_comments(mut self, pr_number: u64, comments: Vec<Comment>) -> Self {
            self.existing_comments.insert(pr_number, comments);
            self
        }
    }

    impl Forge for MockForge {
        async fn get_authenticated_user(&self) -> Result<String, ForgeError> {
            Ok("test-user".to_string())
        }

        fn find_pr_for_branch(
            &self,
            head: &str,
        ) -> impl std::future::Future<Output = Result<Option<PullRequest>, ForgeError>> + Send
        {
            let result = self.existing_prs.get(head).cloned();
            async move { Ok(result) }
        }

        fn create_pr(
            &self,
            params: CreatePrParams,
        ) -> impl std::future::Future<Output = Result<PullRequest, ForgeError>> + Send {
            let mut counter = self.next_pr_number.lock().unwrap();
            let number = *counter;
            *counter += 1;
            let pr = PullRequest {
                number,
                html_url: format!("https://github.com/test/repo/pull/{number}"),
                title: params.title.clone(),
                head_ref: params.head.clone(),
                base_ref: params.base.clone(),
                state: PrState::Open,
                body: params.body.clone(),
            };
            if let Some(ops) = &self.ops {
                ops.lock().unwrap().push(Op::CreatePr(params.head.clone()));
            }
            self.created_prs.lock().unwrap().push(params);
            async move { Ok(pr) }
        }

        fn update_pr_base(
            &self,
            pr_number: u64,
            new_base: &str,
        ) -> impl std::future::Future<Output = Result<(), ForgeError>> + Send {
            if let Some(ops) = &self.ops {
                ops.lock().unwrap().push(Op::BaseUpdate(pr_number));
            }
            self.updated_bases
                .lock()
                .unwrap()
                .push((pr_number, new_base.to_string()));
            async { Ok(()) }
        }

        fn list_comments(
            &self,
            pr_number: u64,
        ) -> impl std::future::Future<Output = Result<Vec<Comment>, ForgeError>> + Send {
            let comments = self
                .existing_comments
                .get(&pr_number)
                .cloned()
                .unwrap_or_default();
            async move { Ok(comments) }
        }

        fn create_comment(
            &self,
            pr_number: u64,
            body: &str,
        ) -> impl std::future::Future<Output = Result<Comment, ForgeError>> + Send {
            let comment = Comment {
                id: pr_number * 1000,
                body: body.to_string(),
            };
            self.created_comments
                .lock()
                .unwrap()
                .push((pr_number, body.to_string()));
            async move { Ok(comment) }
        }

        fn update_comment(
            &self,
            comment_id: u64,
            body: &str,
        ) -> impl std::future::Future<Output = Result<(), ForgeError>> + Send {
            self.updated_comments
                .lock()
                .unwrap()
                .push((comment_id, body.to_string()));
            async { Ok(()) }
        }

        fn update_pr_body(
            &self,
            pr_number: u64,
            body: &str,
        ) -> impl std::future::Future<Output = Result<(), ForgeError>> + Send {
            self.updated_bodies
                .lock()
                .unwrap()
                .push((pr_number, body.to_string()));
            async { Ok(()) }
        }

        fn delete_comment(
            &self,
            comment_id: u64,
        ) -> impl std::future::Future<Output = Result<(), ForgeError>> + Send {
            self.deleted_comments.lock().unwrap().push(comment_id);
            async { Ok(()) }
        }
    }

    // -- Mock JjRunner --

    type PushLog = Arc<Mutex<Vec<(String, String)>>>;

    struct MockJjRunner {
        push_calls: PushLog,
        ops: Option<OpLog>,
    }

    impl MockJjRunner {
        fn new() -> (Self, PushLog) {
            let calls: PushLog = Arc::new(Mutex::new(Vec::new()));
            (
                Self {
                    push_calls: Arc::clone(&calls),
                    ops: None,
                },
                calls,
            )
        }

        fn new_with_ops(ops: OpLog) -> (Self, PushLog) {
            let calls: PushLog = Arc::new(Mutex::new(Vec::new()));
            (
                Self {
                    push_calls: Arc::clone(&calls),
                    ops: Some(ops),
                },
                calls,
            )
        }
    }

    impl crate::jj::runner::JjRunner for MockJjRunner {
        fn run_jj(
            &self,
            args: &[&str],
        ) -> impl std::future::Future<Output = Result<String, JjError>> + Send {
            // Only handle push commands.
            if args[0] == "git" && args[1] == "push" {
                let bookmark = args
                    .iter()
                    .position(|a| *a == "--bookmark")
                    .map(|i| args[i + 1].to_string())
                    .unwrap_or_default();
                let remote = args
                    .iter()
                    .position(|a| *a == "--remote")
                    .map(|i| args[i + 1].to_string())
                    .unwrap_or_default();
                if let Some(ops) = &self.ops {
                    ops.lock().unwrap().push(Op::Push(bookmark.clone()));
                }
                self.push_calls.lock().unwrap().push((bookmark, remote));
            }
            async { Ok(String::new()) }
        }
    }

    // -----------------------------------------------------------------------
    // Phase 1 tests
    // -----------------------------------------------------------------------

    #[test]
    fn analyze_single_bookmark() {
        let seg = make_segment(&["feat-a"], "ch_a", "add feature a");
        let graph = make_graph(vec![BranchStack {
            segments: vec![seg],
        }]);

        let all = HashSet::from(["feat-a".to_string()]);
        let result = analyze_submission("feat-a", &graph, "main", &all).unwrap();
        assert_eq!(result.segments.len(), 1);
        assert_eq!(result.segments[0].bookmark_names, vec!["feat-a"]);

        assert_eq!(result.default_branch, "main");
    }

    #[test]
    fn analyze_middle_of_stack() {
        let seg_a = make_segment(&["feat-a"], "ch_a", "feature a");
        let seg_b = make_segment(&["feat-b"], "ch_b", "feature b");
        let seg_c = make_segment(&["feat-c"], "ch_c", "feature c");
        let graph = make_graph(vec![BranchStack {
            segments: vec![seg_a, seg_b, seg_c],
        }]);

        let all = HashSet::from([
            "feat-a".to_string(),
            "feat-b".to_string(),
            "feat-c".to_string(),
        ]);
        let result = analyze_submission("feat-b", &graph, "main", &all).unwrap();
        assert_eq!(result.segments.len(), 2);
        assert_eq!(result.segments[0].bookmark_names, vec!["feat-a"]);
        assert_eq!(result.segments[1].bookmark_names, vec!["feat-b"]);
    }

    #[test]
    fn analyze_leaf_of_stack() {
        let seg_a = make_segment(&["feat-a"], "ch_a", "feature a");
        let seg_b = make_segment(&["feat-b"], "ch_b", "feature b");
        let graph = make_graph(vec![BranchStack {
            segments: vec![seg_a, seg_b],
        }]);

        let all = HashSet::from(["feat-a".to_string(), "feat-b".to_string()]);
        let result = analyze_submission("feat-b", &graph, "main", &all).unwrap();
        assert_eq!(result.segments.len(), 2);
    }

    #[test]
    fn analyze_bookmark_not_found() {
        let seg = make_segment(&["feat-a"], "ch_a", "feature a");
        let graph = make_graph(vec![BranchStack {
            segments: vec![seg],
        }]);

        let all = HashSet::from(["nonexistent".to_string()]);
        let result = analyze_submission("nonexistent", &graph, "main", &all);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("nonexistent"),
            "error should mention the bookmark name: {err}"
        );
    }

    #[test]
    fn analyze_multiple_stacks_finds_correct_one() {
        let stack1 = BranchStack {
            segments: vec![make_segment(&["alpha"], "ch_alpha", "alpha")],
        };
        let stack2 = BranchStack {
            segments: vec![
                make_segment(&["beta"], "ch_beta", "beta"),
                make_segment(&["gamma"], "ch_gamma", "gamma"),
            ],
        };
        let graph = make_graph(vec![stack1, stack2]);

        let all = HashSet::from(["beta".to_string(), "gamma".to_string()]);
        let result = analyze_submission("gamma", &graph, "main", &all).unwrap();
        assert_eq!(result.segments.len(), 2);
        assert_eq!(result.segments[0].bookmark_names, vec!["beta"]);
        assert_eq!(result.segments[1].bookmark_names, vec!["gamma"]);
    }

    #[test]
    fn analyze_filters_unselected_bookmarks() {
        let seg_a = make_segment(&["feat-a"], "ch_a", "feature a");
        let seg_b = make_segment(&["feat-b"], "ch_b", "feature b");
        let seg_c = make_segment(&["feat-c"], "ch_c", "feature c");
        let graph = make_graph(vec![BranchStack {
            segments: vec![seg_a, seg_b, seg_c],
        }]);

        // Only select the leaf — intermediate bookmarks should be excluded,
        // but their commits fold into the next retained segment.
        let selected = HashSet::from(["feat-c".to_string()]);
        let result = analyze_submission("feat-c", &graph, "main", &selected).unwrap();
        assert_eq!(result.segments.len(), 1);
        assert_eq!(result.segments[0].bookmark_names, vec!["feat-c"]);
        assert_eq!(result.segments[0].commits.len(), 3); // C's own + B's + A's
    }

    #[test]
    fn analyze_filters_keeps_selected_subset() {
        let seg_a = make_segment(&["feat-a"], "ch_a", "feature a");
        let seg_b = make_segment(&["feat-b"], "ch_b", "feature b");
        let seg_c = make_segment(&["feat-c"], "ch_c", "feature c");
        let graph = make_graph(vec![BranchStack {
            segments: vec![seg_a, seg_b, seg_c],
        }]);

        // Select first and last — middle should be excluded,
        // and middle's commits fold into the next retained segment.
        let selected = HashSet::from(["feat-a".to_string(), "feat-c".to_string()]);
        let result = analyze_submission("feat-c", &graph, "main", &selected).unwrap();
        assert_eq!(result.segments.len(), 2);
        assert_eq!(result.segments[0].bookmark_names, vec!["feat-a"]);
        assert_eq!(result.segments[0].commits.len(), 1); // A's own only
        assert_eq!(result.segments[1].bookmark_names, vec!["feat-c"]);
        assert_eq!(result.segments[1].commits.len(), 2); // C's own + B's inherited
    }

    // -----------------------------------------------------------------------
    // Phase 2 tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn plan_all_new_prs() {
        let analysis = SubmissionAnalysis {
            segments: vec![
                make_segment(&["feat-a"], "ch_a", "feature a"),
                make_segment(&["feat-b"], "ch_b", "feature b"),
            ],

            default_branch: "main".to_string(),
        };

        let forge = MockForge::new();
        let plan = create_submission_plan(&analysis, &forge, "origin", PrMode::Regular)
            .await
            .unwrap();

        assert_eq!(plan.bookmark_plans.len(), 2);

        assert!(plan.bookmark_plans[0].needs_create);
        assert!(!plan.bookmark_plans[0].needs_base_update);
        assert_eq!(plan.bookmark_plans[0].base, "main");

        assert!(plan.bookmark_plans[1].needs_create);
        assert!(!plan.bookmark_plans[1].needs_base_update);
        assert_eq!(plan.bookmark_plans[1].base, "feat-a");
    }

    #[tokio::test]
    async fn plan_existing_pr_correct_base() {
        let analysis = SubmissionAnalysis {
            segments: vec![make_segment(&["feat-a"], "ch_a", "feature a")],

            default_branch: "main".to_string(),
        };

        let forge = MockForge::new().with_existing_pr("feat-a", make_pr(42, "feat-a", "main"));

        let plan = create_submission_plan(&analysis, &forge, "origin", PrMode::Regular)
            .await
            .unwrap();

        assert!(!plan.bookmark_plans[0].needs_create);
        assert!(!plan.bookmark_plans[0].needs_base_update);
        assert_eq!(
            plan.bookmark_plans[0].existing_pr.as_ref().unwrap().number,
            42
        );
    }

    #[tokio::test]
    async fn plan_existing_pr_wrong_base() {
        let analysis = SubmissionAnalysis {
            segments: vec![
                make_segment(&["feat-a"], "ch_a", "feature a"),
                make_segment(&["feat-b"], "ch_b", "feature b"),
            ],

            default_branch: "main".to_string(),
        };

        let forge = MockForge::new()
            .with_existing_pr("feat-a", make_pr(10, "feat-a", "main"))
            .with_existing_pr("feat-b", make_pr(11, "feat-b", "main"));

        let plan = create_submission_plan(&analysis, &forge, "origin", PrMode::Regular)
            .await
            .unwrap();

        // feat-a: base is "main", existing PR base is "main" -> no update
        assert!(!plan.bookmark_plans[0].needs_base_update);

        // feat-b: base should be "feat-a", existing PR base is "main" ->
        // needs update
        assert!(plan.bookmark_plans[1].needs_base_update);
        assert_eq!(plan.bookmark_plans[1].base, "feat-a");
    }

    #[tokio::test]
    async fn plan_mixed_existing_and_new() {
        let analysis = SubmissionAnalysis {
            segments: vec![
                make_segment(&["feat-a"], "ch_a", "feature a"),
                make_segment(&["feat-b"], "ch_b", "feature b"),
            ],

            default_branch: "main".to_string(),
        };

        let forge = MockForge::new().with_existing_pr("feat-a", make_pr(10, "feat-a", "main"));

        let plan = create_submission_plan(&analysis, &forge, "origin", PrMode::Regular)
            .await
            .unwrap();

        assert!(!plan.bookmark_plans[0].needs_create);
        assert!(plan.bookmark_plans[1].needs_create);
    }

    #[test]
    fn plan_display_dry_run() {
        let plan = SubmissionPlan {
            bookmark_plans: vec![
                BookmarkPlan {
                    bookmark_name: "feat-a".to_string(),
                    base: "main".to_string(),
                    title: "feature a".to_string(),
                    body: None,
                    existing_pr: None,
                    needs_push: true,
                    needs_create: true,
                    needs_base_update: false,
                },
                BookmarkPlan {
                    bookmark_name: "feat-b".to_string(),
                    base: "feat-a".to_string(),
                    title: "feature b".to_string(),
                    body: None,
                    existing_pr: Some(make_pr(42, "feat-b", "main")),
                    needs_push: true,
                    needs_create: false,
                    needs_base_update: true,
                },
            ],
            remote: "origin".to_string(),
            pr_mode: PrMode::Regular,
            default_branch: "main".to_string(),
        };

        let output = plan.to_string();
        assert!(output.contains("2 bookmark(s)"));
        assert!(output.contains("feat-a (base: main)"));
        assert!(output.contains("create PR: \"feature a\""));
        assert!(output.contains("push bookmark to origin"));
        assert!(output.contains("update PR #42 base: main -> feat-a"));
    }

    // -----------------------------------------------------------------------
    // Phase 3 tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn execute_creates_new_prs() {
        let plan = SubmissionPlan {
            bookmark_plans: vec![
                BookmarkPlan {
                    bookmark_name: "feat-a".to_string(),
                    base: "main".to_string(),
                    title: "feature a".to_string(),
                    body: None,
                    existing_pr: None,
                    needs_push: true,
                    needs_create: true,
                    needs_base_update: false,
                },
                BookmarkPlan {
                    bookmark_name: "feat-b".to_string(),
                    base: "feat-a".to_string(),
                    title: "feature b".to_string(),
                    body: None,
                    existing_pr: None,
                    needs_push: true,
                    needs_create: true,
                    needs_base_update: false,
                },
            ],
            remote: "origin".to_string(),
            pr_mode: PrMode::Regular,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new();
        let jj = Jj::new(runner);
        let forge = MockForge::new();
        let env = test_comment_env();

        let result = execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Comment)
            .await
            .unwrap();

        assert_eq!(result.stack_entries.len(), 2);

        let created = forge.created_prs.lock().unwrap();
        assert_eq!(created.len(), 2);
        assert_eq!(created[0].head, "feat-a");
        assert_eq!(created[0].base, "main");
        assert_eq!(created[1].head, "feat-b");
        assert_eq!(created[1].base, "feat-a");
    }

    #[tokio::test]
    async fn execute_updates_base() {
        let plan = SubmissionPlan {
            bookmark_plans: vec![BookmarkPlan {
                bookmark_name: "feat-a".to_string(),
                base: "develop".to_string(),
                title: "feature a".to_string(),
                body: None,
                existing_pr: Some(make_pr(42, "feat-a", "main")),
                needs_push: true,
                needs_create: false,
                needs_base_update: true,
            }],
            remote: "origin".to_string(),
            pr_mode: PrMode::Regular,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new();
        let jj = Jj::new(runner);
        let forge = MockForge::new();
        let env = test_comment_env();

        execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Comment)
            .await
            .unwrap();

        let updated = forge.updated_bases.lock().unwrap();
        assert_eq!(updated.len(), 1);
        assert_eq!(updated[0], (42, "develop".to_string()));
    }

    #[tokio::test]
    async fn execute_creates_stack_comments() {
        let plan = SubmissionPlan {
            bookmark_plans: vec![
                BookmarkPlan {
                    bookmark_name: "feat-a".to_string(),
                    base: "main".to_string(),
                    title: "feature a".to_string(),
                    body: None,
                    existing_pr: None,
                    needs_push: true,
                    needs_create: true,
                    needs_base_update: false,
                },
                BookmarkPlan {
                    bookmark_name: "feat-b".to_string(),
                    base: "feat-a".to_string(),
                    title: "feature b".to_string(),
                    body: None,
                    existing_pr: None,
                    needs_push: true,
                    needs_create: true,
                    needs_base_update: false,
                },
            ],
            remote: "origin".to_string(),
            pr_mode: PrMode::Regular,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new();
        let jj = Jj::new(runner);
        let forge = MockForge::new();
        let env = test_comment_env();

        execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Comment)
            .await
            .unwrap();

        let comments = forge.created_comments.lock().unwrap();
        // One stack comment per PR.
        assert_eq!(comments.len(), 2);
        // Comments should contain STAKK_STACK metadata.
        assert!(comments[0].1.contains("STAKK_STACK"));
        assert!(comments[1].1.contains("STAKK_STACK"));
    }

    #[tokio::test]
    async fn execute_updates_existing_stack_comments() {
        let env = test_comment_env();
        let tmpl = env.get_template("stack_comment").unwrap();
        let existing_comment_body = format_stack_comment(
            &StackCommentData {
                version: 0,
                stack: vec![StackEntry {
                    bookmark_name: "old".to_string(),
                    pr_url: "https://example.com/1".to_string(),
                    pr_number: 1,
                }],
            },
            &StackCommentContext {
                stack: vec![StackEntryContext {
                    bookmark_name: "old".to_string(),
                    pr_url: "https://example.com/1".to_string(),
                    pr_number: 1,
                    title: "old feature".to_string(),
                    base: "main".to_string(),
                    is_draft: false,
                    position: 1,
                    is_current: true,
                }],
                stack_size: 1,
                default_branch: "main".to_string(),
                current_bookmark: "old".to_string(),
                stakk_url: STAKK_REPO_URL.to_string(),
            },
            &tmpl,
        )
        .unwrap();

        let plan = SubmissionPlan {
            bookmark_plans: vec![
                BookmarkPlan {
                    bookmark_name: "feat-a".to_string(),
                    base: "main".to_string(),
                    title: "feature a".to_string(),
                    body: None,
                    existing_pr: Some(make_pr(50, "feat-a", "main")),
                    needs_push: true,
                    needs_create: false,
                    needs_base_update: false,
                },
                BookmarkPlan {
                    bookmark_name: "feat-b".to_string(),
                    base: "feat-a".to_string(),
                    title: "feature b".to_string(),
                    body: None,
                    existing_pr: None,
                    needs_push: true,
                    needs_create: true,
                    needs_base_update: false,
                },
            ],
            remote: "origin".to_string(),
            pr_mode: PrMode::Regular,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new();
        let jj = Jj::new(runner);
        let forge = MockForge::new().with_existing_comments(
            50,
            vec![Comment {
                id: 999,
                body: existing_comment_body,
            }],
        );

        execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Comment)
            .await
            .unwrap();

        // Should have updated the existing comment on PR #50, not created a
        // new one. A new comment is created for the second PR.
        let created = forge.created_comments.lock().unwrap();
        assert_eq!(created.len(), 1);

        let updated = forge.updated_comments.lock().unwrap();
        assert_eq!(updated.len(), 1);
        assert_eq!(updated[0].0, 999);
    }

    #[tokio::test]
    async fn execute_pushes_bookmarks() {
        let plan = SubmissionPlan {
            bookmark_plans: vec![
                BookmarkPlan {
                    bookmark_name: "feat-a".to_string(),
                    base: "main".to_string(),
                    title: "feature a".to_string(),
                    body: None,
                    existing_pr: None,
                    needs_push: true,
                    needs_create: true,
                    needs_base_update: false,
                },
                BookmarkPlan {
                    bookmark_name: "feat-b".to_string(),
                    base: "feat-a".to_string(),
                    title: "feature b".to_string(),
                    body: None,
                    existing_pr: None,
                    needs_push: true,
                    needs_create: true,
                    needs_base_update: false,
                },
            ],
            remote: "my-remote".to_string(),
            pr_mode: PrMode::Regular,
            default_branch: "main".to_string(),
        };

        let (runner, push_calls) = MockJjRunner::new();
        let jj = Jj::new(runner);
        let forge = MockForge::new();
        let env = test_comment_env();

        execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Comment)
            .await
            .unwrap();

        let calls = push_calls.lock().unwrap();
        assert_eq!(calls.len(), 2);
        assert_eq!(calls[0], ("feat-a".to_string(), "my-remote".to_string()));
        assert_eq!(calls[1], ("feat-b".to_string(), "my-remote".to_string()));
    }

    #[test]
    fn plan_display_shows_draft() {
        let plan = SubmissionPlan {
            bookmark_plans: vec![BookmarkPlan {
                bookmark_name: "feat-a".to_string(),
                base: "main".to_string(),
                title: "feature a".to_string(),
                body: None,
                existing_pr: None,
                needs_push: true,
                needs_create: true,
                needs_base_update: false,
            }],
            remote: "origin".to_string(),
            pr_mode: PrMode::Draft,
            default_branch: "main".to_string(),
        };

        let output = plan.to_string();
        assert!(
            output.contains("draft"),
            "expected 'draft' in plan display: {output}"
        );
    }

    #[tokio::test]
    async fn execute_creates_draft_prs() {
        let plan = SubmissionPlan {
            bookmark_plans: vec![BookmarkPlan {
                bookmark_name: "feat-a".to_string(),
                base: "main".to_string(),
                title: "feature a".to_string(),
                body: None,
                existing_pr: None,
                needs_push: true,
                needs_create: true,
                needs_base_update: false,
            }],
            remote: "origin".to_string(),
            pr_mode: PrMode::Draft,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new();
        let jj = Jj::new(runner);
        let forge = MockForge::new();
        let env = test_comment_env();

        execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Comment)
            .await
            .unwrap();

        let created = forge.created_prs.lock().unwrap();
        assert_eq!(created.len(), 1);
        assert!(created[0].draft, "expected PR to be created as draft");
    }

    // -----------------------------------------------------------------------
    // build_pr_body tests
    // -----------------------------------------------------------------------

    #[test]
    fn build_pr_body_single_commit_with_body() {
        let commits = vec![SegmentCommit {
            commit_id: "c1".to_string(),
            change_id: "ch1".to_string(),
            description: "Add feature X\n\nThis adds feature X with foo and bar.".to_string(),
            author: crate::jj::types::Signature {
                name: "Test".to_string(),
                email: "test@test.com".to_string(),
                timestamp: "T".to_string(),
            },
            committer: crate::jj::types::Signature {
                name: "Test".to_string(),
                email: "test@test.com".to_string(),
                timestamp: "T".to_string(),
            },
            files: vec![],
            short_change_id: "ch1".to_string(),
        }];

        let body = build_pr_body(&commits);
        assert_eq!(
            body.as_deref(),
            Some("This adds feature X with foo and bar.")
        );
    }

    #[test]
    fn build_pr_body_single_commit_title_only() {
        let commits = vec![SegmentCommit {
            commit_id: "c1".to_string(),
            change_id: "ch1".to_string(),
            description: "Add feature X".to_string(),
            author: crate::jj::types::Signature {
                name: "Test".to_string(),
                email: "test@test.com".to_string(),
                timestamp: "T".to_string(),
            },
            committer: crate::jj::types::Signature {
                name: "Test".to_string(),
                email: "test@test.com".to_string(),
                timestamp: "T".to_string(),
            },
            files: vec![],
            short_change_id: "ch1".to_string(),
        }];

        let body = build_pr_body(&commits);
        assert_eq!(body, None);
    }

    #[test]
    fn build_pr_body_multiple_commits() {
        let commits = vec![
            SegmentCommit {
                commit_id: "c1".to_string(),
                change_id: "ch1".to_string(),
                description: "First commit".to_string(),
                author: crate::jj::types::Signature {
                    name: "Test".to_string(),
                    email: "test@test.com".to_string(),
                    timestamp: "T".to_string(),
                },
                committer: crate::jj::types::Signature {
                    name: "Test".to_string(),
                    email: "test@test.com".to_string(),
                    timestamp: "T".to_string(),
                },
                files: vec![],
                short_change_id: "ch1".to_string(),
            },
            SegmentCommit {
                commit_id: "c2".to_string(),
                change_id: "ch2".to_string(),
                description: "Second commit".to_string(),
                author: crate::jj::types::Signature {
                    name: "Test".to_string(),
                    email: "test@test.com".to_string(),
                    timestamp: "T".to_string(),
                },
                committer: crate::jj::types::Signature {
                    name: "Test".to_string(),
                    email: "test@test.com".to_string(),
                    timestamp: "T".to_string(),
                },
                files: vec![],
                short_change_id: "ch2".to_string(),
            },
        ];

        let body = build_pr_body(&commits);
        assert_eq!(
            body.as_deref(),
            Some("First commit\n\n---\n\nSecond commit")
        );
    }

    #[test]
    fn build_pr_body_empty() {
        let body = build_pr_body(&[]);
        assert_eq!(body, None);
    }

    // -----------------------------------------------------------------------
    // Body placement tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn execute_body_mode_creates_fenced_section() {
        let plan = SubmissionPlan {
            bookmark_plans: vec![
                BookmarkPlan {
                    bookmark_name: "feat-a".to_string(),
                    base: "main".to_string(),
                    title: "feature a".to_string(),
                    body: None,
                    existing_pr: None,
                    needs_push: true,
                    needs_create: true,
                    needs_base_update: false,
                },
                BookmarkPlan {
                    bookmark_name: "feat-b".to_string(),
                    base: "feat-a".to_string(),
                    title: "feature b".to_string(),
                    body: None,
                    existing_pr: None,
                    needs_push: true,
                    needs_create: true,
                    needs_base_update: false,
                },
            ],
            remote: "origin".to_string(),
            pr_mode: PrMode::Regular,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new();
        let jj = Jj::new(runner);
        let forge = MockForge::new();
        let env = test_comment_env();

        execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Body)
            .await
            .unwrap();

        let updated_bodies = forge.updated_bodies.lock().unwrap();
        assert_eq!(updated_bodies.len(), 2);
        assert!(
            updated_bodies[0].1.contains("STAKK_BODY_START"),
            "expected body fence: {}",
            updated_bodies[0].1
        );
        assert!(
            updated_bodies[0].1.contains("STAKK_STACK"),
            "expected stack metadata in body: {}",
            updated_bodies[0].1
        );

        // No comment API calls should be made in steady-state body mode.
        let created_comments = forge.created_comments.lock().unwrap();
        assert_eq!(created_comments.len(), 0);
    }

    #[tokio::test]
    async fn execute_body_mode_updates_existing_fence() {
        use crate::forge::comment::splice_stack_into_body;

        let existing_body = splice_stack_into_body("Original PR body", "old stack content");
        let plan = SubmissionPlan {
            bookmark_plans: vec![
                BookmarkPlan {
                    bookmark_name: "feat-a".to_string(),
                    base: "main".to_string(),
                    title: "feature a".to_string(),
                    body: None,
                    existing_pr: Some(make_pr_with_body(50, "feat-a", "main", &existing_body)),
                    needs_push: true,
                    needs_create: false,
                    needs_base_update: false,
                },
                BookmarkPlan {
                    bookmark_name: "feat-b".to_string(),
                    base: "feat-a".to_string(),
                    title: "feature b".to_string(),
                    body: None,
                    existing_pr: None,
                    needs_push: true,
                    needs_create: true,
                    needs_base_update: false,
                },
            ],
            remote: "origin".to_string(),
            pr_mode: PrMode::Regular,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new();
        let jj = Jj::new(runner);
        let forge = MockForge::new();
        let env = test_comment_env();

        execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Body)
            .await
            .unwrap();

        let updated_bodies = forge.updated_bodies.lock().unwrap();
        assert_eq!(updated_bodies.len(), 2);
        // PR #50 (feat-a) should still contain original body text.
        assert!(updated_bodies[0].1.contains("Original PR body"));
        // Should no longer contain old stack content.
        assert!(!updated_bodies[0].1.contains("old stack content"));
        // Should contain new STAKK_STACK metadata.
        assert!(updated_bodies[0].1.contains("STAKK_STACK"));

        // No comment API calls (existing fence = not first time for feat-a,
        // new PR for feat-b has no old comment either).
        let created_comments = forge.created_comments.lock().unwrap();
        assert_eq!(created_comments.len(), 0);
        let deleted = forge.deleted_comments.lock().unwrap();
        assert_eq!(deleted.len(), 0);
    }

    #[tokio::test]
    async fn execute_body_mode_migration_deletes_old_comment() {
        // Simulate a PR that has an old stack comment but no body fence.
        let env = test_comment_env();
        let tmpl = env.get_template("stack_comment").unwrap();
        let old_comment_body = format_stack_comment(
            &StackCommentData {
                version: 0,
                stack: vec![StackEntry {
                    bookmark_name: "feat-a".to_string(),
                    pr_url: "https://example.com/1".to_string(),
                    pr_number: 50,
                }],
            },
            &StackCommentContext {
                stack: vec![StackEntryContext {
                    bookmark_name: "feat-a".to_string(),
                    pr_url: "https://example.com/1".to_string(),
                    pr_number: 50,
                    title: "feature a".to_string(),
                    base: "main".to_string(),
                    is_draft: false,
                    position: 1,
                    is_current: true,
                }],
                stack_size: 1,
                default_branch: "main".to_string(),
                current_bookmark: "feat-a".to_string(),
                stakk_url: STAKK_REPO_URL.to_string(),
            },
            &tmpl,
        )
        .unwrap();

        let plan = SubmissionPlan {
            bookmark_plans: vec![
                BookmarkPlan {
                    bookmark_name: "feat-a".to_string(),
                    base: "main".to_string(),
                    title: "feature a".to_string(),
                    body: None,
                    existing_pr: Some(make_pr_with_body(50, "feat-a", "main", "Plain body")),
                    needs_push: true,
                    needs_create: false,
                    needs_base_update: false,
                },
                BookmarkPlan {
                    bookmark_name: "feat-b".to_string(),
                    base: "feat-a".to_string(),
                    title: "feature b".to_string(),
                    body: None,
                    existing_pr: None,
                    needs_push: true,
                    needs_create: true,
                    needs_base_update: false,
                },
            ],
            remote: "origin".to_string(),
            pr_mode: PrMode::Regular,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new();
        let jj = Jj::new(runner);
        let forge = MockForge::new().with_existing_comments(
            50,
            vec![Comment {
                id: 999,
                body: old_comment_body,
            }],
        );

        execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Body)
            .await
            .unwrap();

        // Should have written body for both PRs.
        let updated_bodies = forge.updated_bodies.lock().unwrap();
        assert_eq!(updated_bodies.len(), 2);
        assert!(updated_bodies[0].1.contains("STAKK_BODY_START"));

        // Should have deleted the old comment on PR #50 (migration).
        let deleted = forge.deleted_comments.lock().unwrap();
        assert_eq!(deleted.len(), 1);
        assert_eq!(deleted[0], 999);
    }

    #[tokio::test]
    async fn execute_comment_mode_migration_strips_body() {
        use crate::forge::comment::splice_stack_into_body;

        // PR has a fenced section in the body (from previous body mode).
        let body_with_fence = splice_stack_into_body("Original PR body", "old stack content");
        let plan = SubmissionPlan {
            bookmark_plans: vec![
                BookmarkPlan {
                    bookmark_name: "feat-a".to_string(),
                    base: "main".to_string(),
                    title: "feature a".to_string(),
                    body: None,
                    existing_pr: Some(make_pr_with_body(50, "feat-a", "main", &body_with_fence)),
                    needs_push: true,
                    needs_create: false,
                    needs_base_update: false,
                },
                BookmarkPlan {
                    bookmark_name: "feat-b".to_string(),
                    base: "feat-a".to_string(),
                    title: "feature b".to_string(),
                    body: None,
                    existing_pr: None,
                    needs_push: true,
                    needs_create: true,
                    needs_base_update: false,
                },
            ],
            remote: "origin".to_string(),
            pr_mode: PrMode::Regular,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new();
        let jj = Jj::new(runner);
        // No existing stack comment — so it will create one, triggering
        // migration check.
        let forge = MockForge::new();
        let env = test_comment_env();

        execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Comment)
            .await
            .unwrap();

        // Should have created comments for both PRs.
        let created_comments = forge.created_comments.lock().unwrap();
        assert_eq!(created_comments.len(), 2);
        assert!(created_comments[0].1.contains("STAKK_STACK"));

        // Should have stripped the fence from the body of PR #50 (migration).
        let updated_bodies = forge.updated_bodies.lock().unwrap();
        assert_eq!(updated_bodies.len(), 1);
        assert!(
            !updated_bodies[0].1.contains("STAKK_BODY_START"),
            "fence should be stripped: {}",
            updated_bodies[0].1
        );
        assert!(updated_bodies[0].1.contains("Original PR body"));
    }

    // -----------------------------------------------------------------------
    // Single-bookmark (no stack info) tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn execute_single_bookmark_skips_stack_comment() {
        let plan = SubmissionPlan {
            bookmark_plans: vec![BookmarkPlan {
                bookmark_name: "feat-a".to_string(),
                base: "main".to_string(),
                title: "feature a".to_string(),
                body: None,
                existing_pr: None,
                needs_push: true,
                needs_create: true,
                needs_base_update: false,
            }],
            remote: "origin".to_string(),
            pr_mode: PrMode::Regular,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new();
        let jj = Jj::new(runner);
        let forge = MockForge::new();
        let env = test_comment_env();

        let result = execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Comment)
            .await
            .unwrap();

        assert_eq!(result.stack_entries.len(), 1);

        // PR should be created.
        let created_prs = forge.created_prs.lock().unwrap();
        assert_eq!(created_prs.len(), 1);

        // No stack comments should be created.
        let created_comments = forge.created_comments.lock().unwrap();
        assert_eq!(created_comments.len(), 0);

        // No body updates for stack info.
        let updated_bodies = forge.updated_bodies.lock().unwrap();
        assert_eq!(updated_bodies.len(), 0);
    }

    #[tokio::test]
    async fn execute_single_bookmark_cleans_up_old_comment() {
        let env = test_comment_env();
        let tmpl = env.get_template("stack_comment").unwrap();
        let old_comment_body = format_stack_comment(
            &StackCommentData {
                version: 0,
                stack: vec![StackEntry {
                    bookmark_name: "feat-a".to_string(),
                    pr_url: "https://example.com/1".to_string(),
                    pr_number: 50,
                }],
            },
            &StackCommentContext {
                stack: vec![StackEntryContext {
                    bookmark_name: "feat-a".to_string(),
                    pr_url: "https://example.com/1".to_string(),
                    pr_number: 50,
                    title: "feature a".to_string(),
                    base: "main".to_string(),
                    is_draft: false,
                    position: 1,
                    is_current: true,
                }],
                stack_size: 1,
                default_branch: "main".to_string(),
                current_bookmark: "feat-a".to_string(),
                stakk_url: STAKK_REPO_URL.to_string(),
            },
            &tmpl,
        )
        .unwrap();

        let plan = SubmissionPlan {
            bookmark_plans: vec![BookmarkPlan {
                bookmark_name: "feat-a".to_string(),
                base: "main".to_string(),
                title: "feature a".to_string(),
                body: None,
                existing_pr: Some(make_pr(50, "feat-a", "main")),
                needs_push: true,
                needs_create: false,
                needs_base_update: false,
            }],
            remote: "origin".to_string(),
            pr_mode: PrMode::Regular,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new();
        let jj = Jj::new(runner);
        let forge = MockForge::new().with_existing_comments(
            50,
            vec![Comment {
                id: 999,
                body: old_comment_body,
            }],
        );

        execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Comment)
            .await
            .unwrap();

        // Old stack comment should be deleted.
        let deleted = forge.deleted_comments.lock().unwrap();
        assert_eq!(deleted.len(), 1);
        assert_eq!(deleted[0], 999);

        // No new comments should be created.
        let created = forge.created_comments.lock().unwrap();
        assert_eq!(created.len(), 0);
    }

    #[tokio::test]
    async fn execute_single_bookmark_cleans_up_old_body_fence() {
        use crate::forge::comment::splice_stack_into_body;

        let body_with_fence = splice_stack_into_body("Original PR body", "old stack content");
        let plan = SubmissionPlan {
            bookmark_plans: vec![BookmarkPlan {
                bookmark_name: "feat-a".to_string(),
                base: "main".to_string(),
                title: "feature a".to_string(),
                body: None,
                existing_pr: Some(make_pr_with_body(50, "feat-a", "main", &body_with_fence)),
                needs_push: true,
                needs_create: false,
                needs_base_update: false,
            }],
            remote: "origin".to_string(),
            pr_mode: PrMode::Regular,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new();
        let jj = Jj::new(runner);
        let forge = MockForge::new();
        let env = test_comment_env();

        execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Body)
            .await
            .unwrap();

        // Body fence should be stripped.
        let updated_bodies = forge.updated_bodies.lock().unwrap();
        assert_eq!(updated_bodies.len(), 1);
        assert!(
            !updated_bodies[0].1.contains("STAKK_BODY_START"),
            "fence should be stripped: {}",
            updated_bodies[0].1
        );
        assert!(updated_bodies[0].1.contains("Original PR body"));

        // No new comments should be created.
        let created = forge.created_comments.lock().unwrap();
        assert_eq!(created.len(), 0);
    }

    // -----------------------------------------------------------------------
    // Interleaved push+update ordering tests (issue #35)
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn execute_interleaves_push_and_base_update() {
        // Two existing PRs both needing push + base update (simulates a swap).
        let ops: OpLog = Arc::new(Mutex::new(Vec::new()));

        let plan = SubmissionPlan {
            bookmark_plans: vec![
                BookmarkPlan {
                    bookmark_name: "feat-a".to_string(),
                    base: "main".to_string(),
                    title: "feature a".to_string(),
                    body: None,
                    existing_pr: Some(make_pr(10, "feat-a", "feat-b")),
                    needs_push: true,
                    needs_create: false,
                    needs_base_update: true,
                },
                BookmarkPlan {
                    bookmark_name: "feat-b".to_string(),
                    base: "feat-a".to_string(),
                    title: "feature b".to_string(),
                    body: None,
                    existing_pr: Some(make_pr(11, "feat-b", "main")),
                    needs_push: true,
                    needs_create: false,
                    needs_base_update: true,
                },
            ],
            remote: "origin".to_string(),
            pr_mode: PrMode::Draft,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new_with_ops(Arc::clone(&ops));
        let jj = Jj::new(runner);
        let forge = MockForge::new()
            .with_existing_pr("feat-a", make_pr(10, "feat-a", "feat-b"))
            .with_existing_pr("feat-b", make_pr(11, "feat-b", "main"))
            .with_ops(Arc::clone(&ops));
        let env = test_comment_env();

        execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Comment)
            .await
            .unwrap();

        let ops = ops.lock().unwrap();
        assert_eq!(
            *ops,
            vec![
                Op::Push("feat-a".to_string()),
                Op::BaseUpdate(10),
                Op::Push("feat-b".to_string()),
                Op::BaseUpdate(11),
            ],
            "each bookmark must be pushed and have its base updated before the next bookmark is \
             pushed (prevents transient empty diffs)"
        );
    }

    #[tokio::test]
    async fn execute_interleaves_three_bookmark_reorder() {
        // Three existing PRs all needing push + base update.
        let ops: OpLog = Arc::new(Mutex::new(Vec::new()));

        let plan = SubmissionPlan {
            bookmark_plans: vec![
                BookmarkPlan {
                    bookmark_name: "feat-a".to_string(),
                    base: "main".to_string(),
                    title: "feature a".to_string(),
                    body: None,
                    existing_pr: Some(make_pr(10, "feat-a", "feat-c")),
                    needs_push: true,
                    needs_create: false,
                    needs_base_update: true,
                },
                BookmarkPlan {
                    bookmark_name: "feat-b".to_string(),
                    base: "feat-a".to_string(),
                    title: "feature b".to_string(),
                    body: None,
                    existing_pr: Some(make_pr(11, "feat-b", "main")),
                    needs_push: true,
                    needs_create: false,
                    needs_base_update: true,
                },
                BookmarkPlan {
                    bookmark_name: "feat-c".to_string(),
                    base: "feat-b".to_string(),
                    title: "feature c".to_string(),
                    body: None,
                    existing_pr: Some(make_pr(12, "feat-c", "feat-a")),
                    needs_push: true,
                    needs_create: false,
                    needs_base_update: true,
                },
            ],
            remote: "origin".to_string(),
            pr_mode: PrMode::Draft,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new_with_ops(Arc::clone(&ops));
        let jj = Jj::new(runner);
        let forge = MockForge::new()
            .with_existing_pr("feat-a", make_pr(10, "feat-a", "feat-c"))
            .with_existing_pr("feat-b", make_pr(11, "feat-b", "main"))
            .with_existing_pr("feat-c", make_pr(12, "feat-c", "feat-a"))
            .with_ops(Arc::clone(&ops));
        let env = test_comment_env();

        execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Comment)
            .await
            .unwrap();

        let ops = ops.lock().unwrap();
        assert_eq!(
            *ops,
            vec![
                Op::Push("feat-a".to_string()),
                Op::BaseUpdate(10),
                Op::Push("feat-b".to_string()),
                Op::BaseUpdate(11),
                Op::Push("feat-c".to_string()),
                Op::BaseUpdate(12),
            ],
            "strict interleaving: push(i), update(i), push(i+1), update(i+1), ..."
        );
    }

    #[tokio::test]
    async fn execute_interleaves_push_update_and_create() {
        // First bookmark has existing PR needing base update, second is new.
        let ops: OpLog = Arc::new(Mutex::new(Vec::new()));

        let plan = SubmissionPlan {
            bookmark_plans: vec![
                BookmarkPlan {
                    bookmark_name: "feat-a".to_string(),
                    base: "main".to_string(),
                    title: "feature a".to_string(),
                    body: None,
                    existing_pr: Some(make_pr(10, "feat-a", "feat-b")),
                    needs_push: true,
                    needs_create: false,
                    needs_base_update: true,
                },
                BookmarkPlan {
                    bookmark_name: "feat-b".to_string(),
                    base: "feat-a".to_string(),
                    title: "feature b".to_string(),
                    body: None,
                    existing_pr: None,
                    needs_push: true,
                    needs_create: true,
                    needs_base_update: false,
                },
            ],
            remote: "origin".to_string(),
            pr_mode: PrMode::Draft,
            default_branch: "main".to_string(),
        };

        let (runner, _push_calls) = MockJjRunner::new_with_ops(Arc::clone(&ops));
        let jj = Jj::new(runner);
        let forge = MockForge::new()
            .with_existing_pr("feat-a", make_pr(10, "feat-a", "feat-b"))
            .with_ops(Arc::clone(&ops));
        let env = test_comment_env();

        execute_submission_plan(&plan, &jj, &forge, &env, StackPlacement::Comment)
            .await
            .unwrap();

        let ops = ops.lock().unwrap();
        assert_eq!(
            *ops,
            vec![
                Op::Push("feat-a".to_string()),
                Op::BaseUpdate(10),
                Op::Push("feat-b".to_string()),
                Op::CreatePr("feat-b".to_string()),
            ],
            "base update for feat-a must complete before feat-b is pushed"
        );
    }
}