git-loom 0.25.0

A Git CLI tool that weaves together multiple feature branches into integration branches
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
use std::io::Write as _;
use std::path::Path;
use std::process::Command;
use std::sync::OnceLock;
use std::time::Instant;

use anyhow::{Context, Result, anyhow, bail};
use git2::Repository;

use crate::core::agent_mode;
use crate::core::graph;
use crate::core::msg;
use crate::core::repo;
use crate::core::repo::RemoteStatus;
use crate::git;
use crate::status;
use crate::trace as loom_trace;

/// Remote type detected for the push operation.
#[derive(Debug, PartialEq, Eq)]
enum RemoteType {
    Plain,
    GitHub,
    GitLab,
    AzureDevOps,
    Gerrit { target_branch: String },
}

/// One pushed branch and the branch its PR targets: the branch below it in
/// the stack, or the upstream target branch for the bottom layer.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Layer {
    branch: String,
    base: String,
}

/// Everything one `loom push` touches.
///
/// A stacked branch cannot be reviewed without the branches it is built on,
/// so the requested branch is pushed together with its downstack. Published
/// branches above it whose remote is stale were rewritten by the same rebase
/// and are re-pushed too, otherwise the stack breaks on the server. Branches
/// above it that were never pushed are only reported.
#[derive(Debug, Default, PartialEq, Eq)]
struct PushPlan {
    /// Base of the bottom layer: the upstream branch (e.g. `main`).
    target_branch: String,
    /// Bottom-to-top chain ending with the requested branch.
    layers: Vec<Layer>,
    /// Published upstack branches whose remote is stale, nearest first.
    republish: Vec<Layer>,
    /// Upstack branches that were never pushed, nearest first: this push
    /// leaves them alone and only reports them.
    not_pushed: Vec<String>,
}

impl PushPlan {
    /// A plan for one branch with no PR bookkeeping (Gerrit `--no-pr`, tests).
    fn single(branch: &str) -> Self {
        PushPlan {
            layers: vec![Layer {
                branch: branch.to_string(),
                base: String::new(),
            }],
            ..Default::default()
        }
    }

    /// The branch the user asked to push.
    fn requested(&self) -> &str {
        &self
            .layers
            .last()
            .expect("a plan has at least one layer")
            .branch
    }

    /// True when the requested branch depends on other feature branches.
    fn is_stacked(&self) -> bool {
        self.layers.len() > 1
    }

    /// True when this push looks after more than one branch's PR, so those
    /// PRs form a chain. A re-published upstack layer makes a chain of a
    /// branch that is not itself stacked: its PR targets the one below.
    fn is_chain(&self) -> bool {
        self.layers.len() + self.republish.len() > 1
    }

    /// Every branch to push, downstack first, then re-published upstack.
    fn branches(&self) -> Vec<&str> {
        self.layers
            .iter()
            .chain(&self.republish)
            .map(|l| l.branch.as_str())
            .collect()
    }

    /// Layers whose PRs are looked after, downstack first; the flag marks the
    /// re-published upstack ones, which never get a PR created.
    fn pr_layers(&self) -> impl Iterator<Item = (&Layer, bool)> {
        self.layers
            .iter()
            .map(|l| (l, false))
            .chain(self.republish.iter().map(|l| (l, true)))
    }
}

/// Remote tracking status of a feature branch by name, `None` when it was
/// never pushed or the name is not a feature branch.
fn remote_status<'a>(info: &'a repo::RepoInfo, name: &str) -> Option<&'a RemoteStatus> {
    info.branches
        .iter()
        .find(|b| b.name == name)
        .and_then(|b| b.remote.as_ref())
}

/// Work out which branches `loom push <branch>` pushes and what each PR
/// targets, from the stack shape the status graph sees.
fn plan_push(info: &repo::RepoInfo, branch: &str, target_branch: &str) -> PushPlan {
    // A lower branch whose remote ref is gone had its PR merged or closed and
    // the branch deleted: pushing it would resurrect it on the server and aim
    // the layer above at a dead base. Drop it and let the layer above take its
    // place. The requested branch is pushed whatever its remote status.
    let chain: Vec<String> = graph::downstack(info, branch)
        .into_iter()
        .filter(|name| {
            name == branch || !matches!(remote_status(info, name), Some(RemoteStatus::Gone))
        })
        .collect();
    let layers: Vec<Layer> = chain
        .iter()
        .enumerate()
        .map(|(i, b)| Layer {
            branch: b.clone(),
            base: if i == 0 {
                target_branch.to_string()
            } else {
                chain[i - 1].clone()
            },
        })
        .collect();

    let mut republish = Vec::new();
    let mut not_pushed = Vec::new();
    // Walking up the stack: the nearest branch below that this push leaves on
    // the remote, which is what a re-published layer's PR targets.
    let mut base = chain
        .last()
        .cloned()
        .unwrap_or_else(|| target_branch.to_string());
    for name in graph::upstack(info, branch) {
        match remote_status(info, &name) {
            // Published and out of step with the remote: re-push it, or what
            // is on the server stops matching the stack it belongs to.
            Some(RemoteStatus::Different) => {
                republish.push(Layer {
                    base: base.clone(),
                    branch: name.clone(),
                });
                base = name;
            }
            // Never pushed: publishing it is the user's call, not this push's.
            None => not_pushed.push(name),
            // On the remote unchanged: nothing to push, but a layer above can
            // still target it.
            Some(RemoteStatus::Synced) => base = name,
            // Its PR was merged or closed and the ref is off the remote.
            Some(RemoteStatus::Gone) => {}
        }
    }

    PushPlan {
        target_branch: target_branch.to_string(),
        layers,
        republish,
        not_pushed,
    }
}

fn backticked(names: impl IntoIterator<Item = impl AsRef<str>>) -> String {
    names
        .into_iter()
        .map(|n| format!("`{}`", n.as_ref()))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Success line for a completed `git push` of the plan's branches.
fn pushed_message(remote: &str, plan: &PushPlan) -> String {
    let mut message = format!(
        "Pushed {} to `{}`",
        backticked(plan.layers.iter().map(|l| &l.branch)),
        remote
    );
    if !plan.republish.is_empty() {
        message.push_str(&format!(
            "\nRe-pushed above `{}`: {}",
            plan.requested(),
            backticked(plan.republish.iter().map(|l| &l.branch))
        ));
    }
    message
}

/// Point out upstack branches this push does not touch.
fn report_not_pushed(plan: &PushPlan) {
    // The stack is linear, so the topmost one publishes every branch below it.
    if let Some(top) = plan.not_pushed.last() {
        msg::warn(&format!(
            "Not pushed above `{}`: {}\nRun `loom push {}` to publish them",
            plan.requested(),
            backticked(&plan.not_pushed),
            top
        ));
    }
}

/// Refuse a stacked branch on Azure DevOps.
///
/// Azure has no stacked pull requests, and `az repos pr update` cannot even
/// retarget an existing one, so a stack would land as PRs whose base says
/// nothing a reviewer can rely on. Every other remote type stacks freely.
fn refuse_stacked_azure(remote_type: &RemoteType, plan: &PushPlan) -> Result<()> {
    if *remote_type != RemoteType::AzureDevOps || !plan.is_stacked() {
        return Ok(());
    }
    bail!(
        "`{}` is stacked on {} — Azure DevOps has no stacked pull requests\n\
         Land the branches below it first, or push without a PR (`--no-pr`)",
        plan.requested(),
        backticked(plan.layers.iter().rev().skip(1).map(|l| &l.branch))
    )
}

/// Push a feature branch to remote, dispatching on the detected remote type
/// (plain, GitHub, GitLab, Azure, Gerrit). Without a branch argument, shows
/// an interactive picker.
///
/// `no_pr` skips PR/review creation; for Gerrit it prompts unless the branch
/// is `wip/`-prefixed. `force` pushes with `--force` instead of the default
/// `--force-with-lease --force-if-includes`.
pub fn run(branch: Option<String>, no_pr: bool, force: bool) -> Result<()> {
    let repo = repo::open_repo()?;
    let workdir = repo::require_workdir(&repo, "push")?.to_path_buf();
    let mut info = repo::gather_repo_info(&repo, false, 1)?;
    let hide_pattern = status::hide_pattern(&repo);

    if info.branches.is_empty() {
        bail!("No woven branches to push\nCreate a branch with `git loom branch` first");
    }
    if info
        .branches
        .iter()
        .all(|b| status::is_hidden(&b.name, &hide_pattern))
    {
        bail!(
            "Every woven branch is hidden by `loom.hideBranchPattern` (`{}`)\n\
             Rename one, or change the pattern to publish it",
            hide_pattern
        );
    }

    let branch_name = match branch {
        Some(b) => resolve_branch(&repo, &info, &b)?,
        None => pick_branch(&info, &hide_pattern)?,
    };
    refuse_hidden(&info, &branch_name, &hide_pattern)?;
    // Hidden branches leave the graph here, as they do in `loom status`. A
    // visible branch stacked above one goes with it: its parent link is gone,
    // so it is neither re-pushed nor hinted — and `refuse_hidden` above turns
    // down a direct push of it too, that being a push of the hidden commits.
    status::apply_hidden_branches(&repo, &mut info);

    let mut remote_type = detect_remote_type(&repo, &workdir, &info.upstream.label)?;
    if remote_type == RemoteType::Plain && looks_like_gerrit(&repo, &info.upstream.label) {
        remote_type = confirm_gerrit(&workdir, &info.upstream.label)?;
    }
    let remote_name = resolve_push_remote(&repo, &workdir, &info.upstream.label, &remote_type);

    let target_branch = extract_target_branch(&info.upstream.label);
    let plan = plan_push(&info, &branch_name, &target_branch);

    if no_pr {
        let pushed = match remote_type {
            RemoteType::Gerrit { .. } => {
                push_gerrit_no_pr(&workdir, &remote_name, &branch_name, force)
            }
            _ => push_plain(&workdir, &remote_name, &plan, force),
        };
        return pushed.map_err(|err| force_hint(err, &branch_name, no_pr, force));
    }

    refuse_stacked_azure(&remote_type, &plan)?;

    let pushed = match remote_type {
        RemoteType::Plain => push_plain(&workdir, &remote_name, &plan, force),
        RemoteType::GitHub => push_github(
            &repo,
            &workdir,
            &remote_name,
            &plan,
            &info,
            &info.upstream.label,
            force,
        ),
        RemoteType::GitLab => push_gitlab(&workdir, &remote_name, &plan, force),
        RemoteType::AzureDevOps => push_azure(&repo, &workdir, &remote_name, &plan, &info, force),
        // Gerrit uploads the whole ancestry as a relation chain by itself.
        RemoteType::Gerrit { target_branch } => {
            push_gerrit(&workdir, &remote_name, &branch_name, &target_branch)
        }
    };
    pushed.map_err(|err| force_hint(err, &branch_name, no_pr, force))
}

fn resolve_branch(repo: &Repository, info: &repo::RepoInfo, branch_arg: &str) -> Result<String> {
    let name = repo::resolve_arg(repo, branch_arg, &[repo::TargetKind::Branch])?.expect_branch()?;
    if info.branches.iter().any(|b| b.name == name) {
        Ok(name)
    } else {
        bail!("Branch '{}' is not woven into the integration branch", name)
    }
}

/// Refuse to publish a hidden branch (`loom.hideBranchPattern`, spec 001):
/// the requested branch itself, or one it is stacked on and would push along.
fn refuse_hidden(info: &repo::RepoInfo, branch: &str, hide_pattern: &str) -> Result<()> {
    let hidden = hidden_downstack(info, branch, hide_pattern);
    if hidden.is_empty() {
        return Ok(());
    }
    let hint = "Rename it, or change `loom.hideBranchPattern` to publish it";
    if hidden.iter().any(|h| h == branch) {
        bail!(
            "Branch `{}` is hidden and is never pushed\n{}",
            branch,
            hint
        );
    }
    bail!(
        "Branch `{}` is stacked on hidden branch {}, which is never pushed\n{}",
        branch,
        backticked(&hidden),
        hint
    );
}

/// The hidden branches in `branch`'s downstack, itself included, bottom first.
fn hidden_downstack(info: &repo::RepoInfo, branch: &str, hide_pattern: &str) -> Vec<String> {
    graph::downstack(info, branch)
        .into_iter()
        .filter(|b| status::is_hidden(b, hide_pattern))
        .collect()
}

fn pick_branch(info: &repo::RepoInfo, hide_pattern: &str) -> Result<String> {
    let items: Vec<String> = info
        .branches
        .iter()
        .filter(|b| !status::is_hidden(&b.name, hide_pattern))
        .map(|b| b.name.clone())
        .collect();
    msg::select(
        "Select branch to push",
        items,
        "re-run with: loom push <branch>",
    )
}

/// Detect the remote type from config, URL heuristics, or hook inspection.
///
/// Priority: git config `loom.remote-type` → URL contains `github.com` →
/// `.git/hooks/commit-msg` contains "gerrit" → Plain fallback.
fn detect_remote_type(
    repo: &Repository,
    workdir: &Path,
    upstream_label: &str,
) -> Result<RemoteType> {
    if let Ok(config_value) = git::run_git_stdout(workdir, &["config", "--get", "loom.remote-type"])
    {
        let value = config_value.trim().to_lowercase();
        if value == "github" {
            return Ok(RemoteType::GitHub);
        }
        if value == "gitlab" {
            return Ok(RemoteType::GitLab);
        }
        if value == "azure" {
            return Ok(RemoteType::AzureDevOps);
        }
        if value == "gerrit" {
            let target_branch = extract_target_branch(upstream_label);
            return Ok(RemoteType::Gerrit { target_branch });
        }
        if value == "plain" {
            return Ok(RemoteType::Plain);
        }
        msg::warn(&format!(
            "Unknown loom.remote-type '{}' — falling back to auto-detection.\n\
             Valid values: github, gitlab, azure, gerrit, plain",
            config_value.trim()
        ));
    }

    let remote_name = extract_remote_name(upstream_label);
    if let Ok(remote) = repo.find_remote(&remote_name)
        && let Ok(url) = remote.url()
    {
        if url.contains("github.com") {
            return Ok(RemoteType::GitHub);
        }
        if url.contains("gitlab") {
            return Ok(RemoteType::GitLab);
        }
        if url.contains("dev.azure.com") {
            return Ok(RemoteType::AzureDevOps);
        }
    }

    // Use repo.commondir() so this works in worktrees (where hooks are shared)
    let hook_path = repo.commondir().join("hooks").join("commit-msg");
    if let Ok(content) = std::fs::read_to_string(&hook_path)
        && content.to_lowercase().contains("gerrit")
    {
        let target_branch = extract_target_branch(upstream_label);
        return Ok(RemoteType::Gerrit { target_branch });
    }

    Ok(RemoteType::Plain)
}

/// Hint of a Gerrit remote: the standard SSH port (29418). Only a hint — the
/// hook check in [`detect_remote_type`] can miss (e.g. pre-commit owns
/// commit-msg) — so callers confirm with the user first. `Change-Id` trailers
/// are no hint: loom itself puts one on every commit (Spec 002).
fn looks_like_gerrit(repo: &Repository, upstream_label: &str) -> bool {
    let remote_name = extract_remote_name(upstream_label);
    repo.find_remote(&remote_name)
        .ok()
        .and_then(|remote| remote.url().ok().map(|url| url.contains(":29418/")))
        .unwrap_or(false)
}

/// Ask the user to confirm a suspected Gerrit remote, saving the answer as
/// `loom.remote-type` so the question is asked at most once per repository.
fn confirm_gerrit(workdir: &Path, upstream_label: &str) -> Result<RemoteType> {
    let is_gerrit = msg::confirm(
        "This remote looks like Gerrit (SSH port 29418). Is it a Gerrit remote?",
        "set `git config loom.remote-type gerrit` (or plain), then re-run: loom push <branch>",
    )?;
    let value = if is_gerrit { "gerrit" } else { "plain" };
    git::run_git(workdir, &["config", "loom.remote-type", value])?;
    if is_gerrit {
        Ok(RemoteType::Gerrit {
            target_branch: extract_target_branch(upstream_label),
        })
    } else {
        Ok(RemoteType::Plain)
    }
}

/// Extract the remote name from an upstream label like "origin/main" → "origin".
fn extract_remote_name(upstream_label: &str) -> String {
    upstream_label
        .split('/')
        .next()
        .unwrap_or("origin")
        .to_string()
}

/// Extract `owner/repo` from a git remote URL for `gh --repo`, or `None` when
/// the remote is missing or the URL is unrecognised.
fn extract_gh_repo(repo: &Repository, remote: &str) -> Option<String> {
    let remote = repo.find_remote(remote).ok()?;
    let url = remote.url().ok()?;

    // SCP-style SSH URLs: [git@]<host>:owner/repo[.git], including bare aliases
    // like `github-work:owner/repo`. Told from real URLs by having no '://' and
    // no '/' before the ':'.
    let scp_url = url.strip_prefix("git@").unwrap_or(url);
    if !scp_url.contains("://")
        && let Some(colon_idx) = scp_url.find(':')
    {
        let host = &scp_url[..colon_idx];
        if !host.contains('/') {
            let path = &scp_url[colon_idx + 1..];
            return Some(path.trim_end_matches(".git").to_string());
        }
    }

    // HTTPS: https://github.com/owner/repo.git
    if let Some(path) = url
        .strip_prefix("https://github.com/")
        .or_else(|| url.strip_prefix("http://github.com/"))
    {
        return Some(path.trim_end_matches(".git").to_string());
    }

    None
}

/// Extract the target branch from an upstream label like "origin/main" → "main".
fn extract_target_branch(upstream_label: &str) -> String {
    let branch = repo::upstream_local_branch(upstream_label);
    if branch.is_empty() {
        "main".to_string()
    } else {
        branch
    }
}

/// The remote `loom push` sends to: `loom.push-remote` if set, else `origin`
/// when the integration branch tracks `upstream` (GitHub fork convention),
/// else the integration branch's own remote.
fn resolve_push_remote(
    repo: &Repository,
    workdir: &Path,
    upstream_label: &str,
    remote_type: &RemoteType,
) -> String {
    if let Ok(push_remote) = git::run_git_stdout(workdir, &["config", "--get", "loom.push-remote"])
    {
        let remote = push_remote.trim();
        if !remote.is_empty() && repo.find_remote(remote).is_ok() {
            return remote.to_string();
        }
    }

    let remote_name = extract_remote_name(upstream_label);
    if *remote_type == RemoteType::GitHub
        && remote_name == "upstream"
        && repo.find_remote("origin").is_ok()
    {
        "origin".to_string()
    } else {
        remote_name
    }
}

/// The remote `loom push` sends feature branches to, when it differs from the
/// remote the integration branch tracks — i.e. a fork workflow.
///
/// Returns `None` for the common single-remote setup, where both are the same.
pub(crate) fn fork_push_remote(
    repo: &Repository,
    workdir: &Path,
    upstream_label: &str,
) -> Option<String> {
    let remote_type = detect_remote_type(repo, workdir, upstream_label).ok()?;
    let push_remote = resolve_push_remote(repo, workdir, upstream_label, &remote_type);
    (push_remote != extract_remote_name(upstream_label)).then_some(push_remote)
}

/// What a refused push bails with, and what [`force_hint`] recognises it by.
const PUSH_FAILED: &str = "git push failed";

/// Add the flag that gets past a refused push.
///
/// A forge rebases a stacked branch for us when the pull request below it
/// lands, after which `--force-with-lease`/`--force-if-includes` refuse every
/// later push and nothing done locally helps; git's own "pull first" hint
/// only merges back content the branch already carries. Whether the force is
/// warranted is the user's call, so they have to type it.
fn force_hint(err: anyhow::Error, branch: &str, no_pr: bool, force: bool) -> anyhow::Error {
    if force || err.to_string() != PUSH_FAILED {
        return err;
    }
    anyhow!(
        "{}\nIf `{}` has diverged on the remote, push again with `loom push {}{} -f`",
        err,
        branch,
        branch,
        if no_pr { " --no-pr" } else { "" }
    )
}

/// Run a `git push …`, trace-log it, bail on failure, and return its stderr.
///
/// stderr carries the server's `remote:` messages — GitLab MR links, Gerrit
/// review URLs, GitHub "create a pull request" hints — so callers surface them
/// to the user via [`append_remote_urls`].
fn run_push_capture(workdir: &Path, args: &[&str]) -> Result<String> {
    let start = Instant::now();
    let output = Command::new("git")
        .current_dir(workdir)
        .args(args)
        .output()?;

    let duration_ms = start.elapsed().as_millis();
    let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
    loom_trace::log_command(
        "git",
        &args.join(" "),
        duration_ms,
        output.status.success(),
        &stderr,
    );

    if !output.status.success() {
        bail!("{}", PUSH_FAILED);
    }

    Ok(stderr)
}

/// Append `remote:` URLs found in git push stderr to `message` as indented
/// continuation lines. A trailing `[tag]` (Gerrit) is wrapped in backticks.
fn append_remote_urls(message: &mut String, stderr: &str) {
    for line in stderr.lines() {
        if let Some(rest) = line.strip_prefix("remote:") {
            let trimmed = rest.trim();
            if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
                message.push('\n');
                if trimmed.ends_with(']') {
                    if let Some(pos) = trimmed.rfind('[') {
                        let (before, tag) = trimmed.split_at(pos);
                        message.push_str(&format!("{}`{}`", before, tag));
                    } else {
                        message.push_str(trimmed);
                    }
                } else {
                    message.push_str(trimmed);
                }
            }
        }
    }
}

/// Flags that let a push overwrite the remote branch.
///
/// `--force` is what the user asked for explicitly; otherwise use the safe
/// pair that refuses to overwrite commits we haven't seen.
fn force_args(force: bool) -> &'static [&'static str] {
    if force {
        &["--force"]
    } else {
        &["--force-with-lease", "--force-if-includes"]
    }
}

/// Push `branches` to `remote` in one go (one lease check, one round trip)
/// and return the server's stderr for [`append_remote_urls`]. A stack goes
/// out atomically: a lease refused on one branch leaves the others untouched.
fn git_push(workdir: &Path, remote: &str, branches: &[&str], force: bool) -> Result<String> {
    run_push_capture(workdir, &push_args(remote, branches, force))
}

/// The `git push` argv for the plan's branches. A stack carries `--atomic`,
/// which is what makes a refused lease leave every branch untouched.
fn push_args<'a>(remote: &'a str, branches: &[&'a str], force: bool) -> Vec<&'a str> {
    let mut args = vec!["push"];
    args.extend_from_slice(force_args(force));
    if branches.len() > 1 {
        args.push("--atomic");
    }
    args.extend_from_slice(&["-u", remote]);
    args.extend_from_slice(branches);
    args
}

/// The commits a PR from `branch` onto `base` contains, oldest first.
///
/// Usually the branch's own commits; when the base is further down — a fork's
/// trunk-targeted PR, or a layer dropped because its remote branch is gone —
/// the range spans the branches in between, and so must the description.
fn commits_in_pr(info: &repo::RepoInfo, branch: &str, base: &str) -> Vec<git2::Oid> {
    let chain = graph::downstack(info, branch);
    let from = chain
        .iter()
        .position(|name| name == base)
        .map_or(0, |i| i + 1);
    chain[from..]
        .iter()
        .flat_map(|name| {
            let mut oids = graph::commits_in_branch(info, name);
            oids.reverse();
            oids
        })
        .collect()
}

/// Collect the commits a PR contains, oldest first, as `(subject, body)`
/// pairs where `body` is everything after the first line (may be empty).
fn gather_branch_commits(
    repo: &Repository,
    info: &repo::RepoInfo,
    branch_name: &str,
    base: &str,
) -> Result<Vec<(String, String)>> {
    let oids = commits_in_pr(info, branch_name, base);
    oids.iter()
        .map(|oid| {
            let commit = repo.find_commit(*oid)?;
            let subject = repo::commit_subject(&commit);
            let body = commit.body().ok().flatten().unwrap_or("").to_string();
            Ok((subject, body))
        })
        .collect()
}

/// Build a PR title and description from the commits the PR contains: a lone
/// commit gives subject and body; several prompt for a title and concatenate
/// their messages oldest first.
fn pr_title_and_description(
    repo: &Repository,
    info: &repo::RepoInfo,
    branch_name: &str,
    base: &str,
) -> Result<(String, String)> {
    let commits = gather_branch_commits(repo, info, branch_name, base)?;

    if commits.is_empty() {
        return Ok((branch_name.to_string(), String::new()));
    }

    if commits.len() == 1 {
        let (subject, body) = &commits[0];
        return Ok((subject.clone(), body.clone()));
    }

    let title = msg::input(
        &format!("PR title for `{}`", branch_name),
        "PR creation is skipped in agent mode — this prompt is unreachable there",
        |s| {
            if s.is_empty() {
                Err("Title cannot be empty")
            } else {
                Ok(())
            }
        },
    )?;

    let description = commits
        .iter()
        .map(|(subject, body)| {
            if body.is_empty() {
                subject.clone()
            } else {
                format!("{}\n\n{}", subject, body)
            }
        })
        .collect::<Vec<_>>()
        .join("\n\n---\n\n");

    Ok((title, description))
}

/// Push every branch in the plan and report what went out.
fn push_plain(workdir: &Path, remote: &str, plan: &PushPlan, force: bool) -> Result<()> {
    let stderr = git_push(workdir, remote, &plan.branches(), force)?;
    let mut message = pushed_message(remote, plan);
    append_remote_urls(&mut message, &stderr);
    msg::success(&message);
    report_not_pushed(plan);
    Ok(())
}

/// Run `gh` with `args` in `workdir`, trace-log it, and return stdout on
/// success. Failures are logged (stderr goes to the trace) and yield `None`.
fn run_gh(workdir: &Path, args: &[&str], stdin: Option<&str>) -> Option<String> {
    use std::process::Stdio;

    let start = Instant::now();
    let mut cmd = Command::new("gh");
    cmd.current_dir(workdir).args(args);
    if stdin.is_some() {
        cmd.stdin(Stdio::piped());
    }
    cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
    let mut child = cmd.spawn().ok()?;
    if let (Some(input), Some(mut pipe)) = (stdin, child.stdin.take()) {
        let _ = pipe.write_all(input.as_bytes());
    }
    let output = child.wait_with_output().ok()?;
    let duration_ms = start.elapsed().as_millis();
    let stderr = String::from_utf8_lossy(&output.stderr);
    loom_trace::log_command(
        "gh",
        &args.join(" "),
        duration_ms,
        output.status.success(),
        &stderr,
    );
    output
        .status
        .success()
        .then(|| String::from_utf8_lossy(&output.stdout).into_owned())
}

/// A pull request as `gh` reports it.
#[derive(Debug, Clone, PartialEq, Eq)]
struct GhPr {
    number: u64,
    url: String,
    /// The branch the PR merges into.
    base: String,
}

/// The PR number at the end of a GitHub PR URL.
fn pr_number_from_url(url: &str) -> Option<u64> {
    url.trim().rsplit('/').next()?.parse().ok()
}

/// Pick our PR out of the `gh pr list --json
/// number,url,baseRefName,headRepositoryOwner` output.
///
/// `gh pr list --head` matches the branch name across every fork of the
/// repository, so the PR whose head lives in `head_owner`'s repository is the
/// one; with no known owner the first match is taken.
fn parse_gh_pr_list(json: &str, head_owner: Option<&str>) -> Option<GhPr> {
    let prs: serde_json::Value = serde_json::from_str(json.trim()).ok()?;
    let pr = prs.as_array()?.iter().find(|pr| {
        let Some(owner) = head_owner else {
            return true;
        };
        pr.get("headRepositoryOwner")
            .and_then(|o| o.get("login"))
            .and_then(|l| l.as_str())
            .is_some_and(|login| login.eq_ignore_ascii_case(owner))
    })?;
    Some(GhPr {
        number: pr.get("number")?.as_u64()?,
        url: pr.get("url")?.as_str()?.to_string(),
        base: pr.get("baseRefName")?.as_str()?.to_string(),
    })
}

/// Find the open GitHub PR for `branch` whose head is in `head_owner`'s
/// repository, if any.
fn find_existing_github_pr(
    workdir: &Path,
    gh_repo: &str,
    branch: &str,
    head_owner: Option<&str>,
) -> Option<GhPr> {
    let stdout = run_gh(
        workdir,
        &[
            "pr",
            "list",
            "--head",
            branch,
            "--repo",
            gh_repo,
            "--json",
            "number,url,baseRefName,headRepositoryOwner",
            "--limit",
            "30",
        ],
        None,
    )?;
    parse_gh_pr_list(&stdout, head_owner)
}

/// Create a PR without opening the browser; returns it when `gh` succeeded.
fn create_github_pr(
    workdir: &Path,
    gh_repo: &str,
    head: &str,
    base: &str,
    title: &str,
    body: &str,
) -> Option<GhPr> {
    let stdout = run_gh(
        workdir,
        &[
            "pr", "create", "--head", head, "--base", base, "--repo", gh_repo, "--title", title,
            "--body", body,
        ],
        None,
    )?;
    let url = stdout.lines().rev().find(|l| l.contains("/pull/"))?.trim();
    Some(GhPr {
        number: pr_number_from_url(url)?,
        url: url.to_string(),
        base: base.to_string(),
    })
}

/// Open the browser on GitHub's PR creation page, today's single-branch flow.
fn create_github_pr_web(
    workdir: &Path,
    gh_repo: &str,
    head: &str,
    base: &str,
    title: &str,
    body: &str,
) -> Result<()> {
    // Inherits stdio so the browser opens.
    let args = vec![
        "pr", "create", "--web", "--head", head, "--base", base, "--repo", gh_repo, "--title",
        title, "--body", body,
    ];

    let start = Instant::now();
    let status = Command::new("gh")
        .current_dir(workdir)
        .args(&args)
        .status()?;

    let duration_ms = start.elapsed().as_millis();
    loom_trace::log_command("gh", &args.join(" "), duration_ms, status.success(), "");

    if !status.success() {
        msg::warn("PR creation may have failed — check your browser");
    }
    Ok(())
}

/// Point an existing PR at a different base branch.
fn retarget_github_pr(workdir: &Path, gh_repo: &str, number: u64, base: &str) -> bool {
    let number = number.to_string();
    run_gh(
        workdir,
        &["pr", "edit", &number, "--repo", gh_repo, "--base", base],
        None,
    )
    .is_some()
}

/// How the chain of PRs relates to GitHub's Stack objects.
#[derive(Debug, PartialEq, Eq)]
enum StackAction {
    /// No PR is in a stack yet: create one from the whole chain.
    Create,
    /// The bottom PRs are already in `stack`; append the rest, from index `from`.
    Extend { stack: u64, from: usize },
    /// Every PR is already in `stack`.
    Complete { stack: u64 },
    /// The chain spans several stacks, or a lower PR was unstacked: leave it.
    Conflict,
}

/// Decide what to do from each PR's stack membership, bottom to top.
fn plan_stack_registration(memberships: &[Option<u64>]) -> StackAction {
    let Some(Some(stack)) = memberships.first() else {
        return if memberships.iter().all(Option::is_none) {
            StackAction::Create
        } else {
            StackAction::Conflict
        };
    };
    let from = memberships
        .iter()
        .position(|m| *m != Some(*stack))
        .unwrap_or(memberships.len());
    if from == memberships.len() {
        StackAction::Complete { stack: *stack }
    } else if memberships[from..].iter().all(Option::is_none) {
        StackAction::Extend {
            stack: *stack,
            from,
        }
    } else {
        StackAction::Conflict
    }
}

/// The `stack.number` of a PR resource, `Some(None)` when it is in no stack,
/// `None` when the lookup failed.
fn github_pr_stack(workdir: &Path, gh_repo: &str, number: u64) -> Option<Option<u64>> {
    let path = format!("repos/{}/pulls/{}", gh_repo, number);
    let stdout = run_gh(workdir, &["api", &path, "--jq", ".stack"], None)?;
    Some(parse_stack_number(&stdout))
}

/// Parse the `.stack` object of a PR resource into its stack number.
fn parse_stack_number(json: &str) -> Option<u64> {
    let value: serde_json::Value = serde_json::from_str(json.trim()).ok()?;
    value.get("number")?.as_u64()
}

/// Body for the Stacks API: PR numbers ordered bottom to top.
fn stack_request_body(numbers: &[u64]) -> String {
    serde_json::json!({ "pull_requests": numbers }).to_string()
}

/// The PR numbers a GitHub Stack can link, bottom to top: the run of layers
/// from the bottom that all have a PR and each target the layer below. The
/// Stacks API requires every PR's base to be the previous PR's head, so a
/// layer skipped in between (an upstack branch that was already in sync)
/// ends the run.
fn stack_pr_numbers(chain: &[(Layer, Option<u64>)]) -> Vec<u64> {
    let mut numbers = Vec::new();
    for (i, (layer, number)) in chain.iter().enumerate() {
        let Some(number) = number else { break };
        if i > 0 && layer.base != chain[i - 1].0.branch {
            break;
        }
        numbers.push(*number);
    }
    numbers
}

/// Link the chain of PRs (bottom to top) into a GitHub Stack.
///
/// Nothing is remembered locally: the stack membership of each PR is read
/// back through the API on every push and reconciled.
fn register_github_stack(workdir: &Path, gh_repo: &str, numbers: &[u64]) {
    let memberships: Option<Vec<Option<u64>>> = numbers
        .iter()
        .map(|n| github_pr_stack(workdir, gh_repo, *n))
        .collect();
    let Some(memberships) = memberships else {
        msg::warn(
            "Could not read the GitHub stack of these PRs — left as they are\n\
             Stacked pull requests may be unavailable on this host — see `loom trace`\n\
             Link them on GitHub, or with `gh extension install github/gh-stack`",
        );
        return;
    };

    let (path, body, verb) = match plan_stack_registration(&memberships) {
        StackAction::Create => (
            format!("repos/{}/stacks", gh_repo),
            stack_request_body(numbers),
            "registered",
        ),
        StackAction::Extend { stack, from } => (
            format!("repos/{}/stacks/{}/add", gh_repo, stack),
            stack_request_body(&numbers[from..]),
            "extended",
        ),
        StackAction::Complete { stack } => {
            msg::success(&format!(
                "Stack #{} already links these {} PRs",
                stack,
                numbers.len()
            ));
            return;
        }
        StackAction::Conflict => {
            msg::warn(
                "These PRs belong to different GitHub stacks — left as they are\n\
                 Fix the stack on GitHub or with `gh stack`",
            );
            return;
        }
    };

    match run_gh(
        workdir,
        &["api", "--method", "POST", &path, "--input", "-"],
        Some(&body),
    ) {
        Some(stdout) => {
            let stack = match parse_stack_number(&stdout) {
                Some(n) => format!("Stack #{}", n),
                None => "Stack".to_string(),
            };
            msg::success(&format!("{} {} with {} PRs", stack, verb, numbers.len()));
        }
        None => msg::warn(
            "Could not register the GitHub stack (the PR bases are set)\n\
             Stacked pull requests may be unavailable on this host — see `loom trace`\n\
             Link them on GitHub, or with `gh extension install github/gh-stack`",
        ),
    }
}

/// Push to GitHub: push the plan's branches, then look after their PRs.
///
/// For each layer, bottom to top: an existing PR is retargeted if its base is
/// wrong and reported; a missing one is created. A lone branch keeps the
/// `gh pr create --web` flow; a stack creates PRs directly, because the stack
/// can only be registered once every PR exists. Re-published upstack branches
/// never get a PR created.
///
/// In a fork workflow the PR is based on the integration branch's remote with
/// its head on the push remote; GitHub cannot stack PRs across forks, so
/// there every PR targets the upstream branch. Pushing the upstream target
/// branch itself skips PRs and falls back to a plain push.
fn push_github(
    repo: &Repository,
    workdir: &Path,
    remote: &str,
    plan: &PushPlan,
    info: &repo::RepoInfo,
    upstream_label: &str,
    force: bool,
) -> Result<()> {
    push_plain(workdir, remote, plan, force)?;

    // Skip PR creation when pushing the upstream target branch itself
    if plan.requested() == plan.target_branch {
        return Ok(());
    }

    let start = Instant::now();
    let gh_check = Command::new("gh").arg("--version").output();
    let gh_available = gh_check.as_ref().is_ok_and(|o| o.status.success());
    let duration_ms = start.elapsed().as_millis();
    loom_trace::log_command("gh", "--version", duration_ms, gh_available, "");

    if !gh_available {
        msg::warn("Install 'gh' CLI to create pull requests: https://cli.github.com");
        return Ok(());
    }

    // Fork workflow: the upstream branch's remote is the PR base, the push
    // remote holds the head. Non-fork: both are the same.
    let integration_remote = extract_remote_name(upstream_label);
    let (pr_target_remote, pr_target_repo) = extract_gh_repo(repo, &integration_remote)
        .map(|r| (integration_remote.as_str(), r))
        .or_else(|| {
            // Integration remote missing: fall back to the push remote.
            extract_gh_repo(repo, remote).map(|r| (remote, r))
        })
        .ok_or_else(|| {
            anyhow::anyhow!(
                "Could not determine target repository for PR creation\n\
                 Run `gh repo set-default` to select a default remote repository"
            )
        })?;

    let is_fork = remote != pr_target_remote;
    // Owner of the repository the branches land in; PR lookups are pinned to
    // it because `gh pr list --head` matches the branch name across forks.
    let head_owner =
        extract_gh_repo(repo, remote).and_then(|r| r.split('/').next().map(str::to_string));
    // In fork workflow, --head needs "fork-owner:branch" prefix
    let head_for = |branch: &str| match (&head_owner, is_fork) {
        (Some(owner), true) => format!("{}:{}", owner, branch),
        _ => branch.to_string(),
    };

    let mut layers: Vec<(Layer, bool)> = plan
        .pr_layers()
        .map(|(l, republish)| (l.clone(), republish))
        .collect();
    if is_fork && layers.iter().any(|(l, _)| l.base != plan.target_branch) {
        msg::warn(&format!(
            "Stacked pull requests are not supported across forks — PRs target `{}`",
            plan.target_branch
        ));
        for (layer, _) in &mut layers {
            layer.base = plan.target_branch.clone();
        }
    }
    // One branch keeps the browser flow; a chain needs every PR to exist
    // before it can be linked, and only a same-repo chain can be registered.
    let web = !plan.is_chain();
    let register = plan.is_chain() && !is_fork;

    // Each layer with its PR number, bottom to top, for the stack registration.
    let mut chain: Vec<(Layer, Option<u64>)> = Vec::new();
    for (layer, republish) in &layers {
        let pr = match find_existing_github_pr(
            workdir,
            &pr_target_repo,
            &layer.branch,
            head_owner.as_deref(),
        ) {
            Some(pr) if pr.base != layer.base => {
                if retarget_github_pr(workdir, &pr_target_repo, pr.number, &layer.base) {
                    msg::success(&format!("PR retargeted to `{}`: {}", layer.base, pr.url));
                    Some(pr)
                } else {
                    msg::warn(&format!(
                        "Could not retarget {} to `{}` — see `loom trace`",
                        pr.url, layer.base
                    ));
                    // Its base on the server is not the layer below, so the
                    // stack run has to end here rather than be registered
                    // over a chain GitHub will reject.
                    None
                }
            }
            Some(pr) => {
                msg::success(&format!("PR updated: {}", pr.url));
                Some(pr)
            }
            None if *republish => None,
            None if agent_mode::enabled() => {
                // Post-mutation: the branch is already pushed, and PR creation
                // opens a browser or prompts for a title — never do that behind
                // an agent's back (see spec 019).
                msg::warn(&format!(
                    "Skipped creating a PR for `{}` (agent mode)\n\
                     Create it on GitHub, or run `loom push {}` interactively",
                    layer.branch, layer.branch
                ));
                None
            }
            None => {
                let (title, body) =
                    pr_title_and_description(repo, info, &layer.branch, &layer.base)?;
                let head = head_for(&layer.branch);
                if web {
                    create_github_pr_web(
                        workdir,
                        &pr_target_repo,
                        &head,
                        &layer.base,
                        &title,
                        &body,
                    )?;
                    None
                } else {
                    let pr = create_github_pr(
                        workdir,
                        &pr_target_repo,
                        &head,
                        &layer.base,
                        &title,
                        &body,
                    );
                    match &pr {
                        Some(pr) => msg::success(&format!("PR created: {}", pr.url)),
                        None => msg::warn(&format!(
                            "Could not create a PR for `{}` — see `loom trace`",
                            layer.branch
                        )),
                    }
                    pr
                }
            }
        };
        chain.push((layer.clone(), pr.map(|pr| pr.number)));
    }

    let numbers = stack_pr_numbers(&chain);
    if register && numbers.len() >= 2 {
        register_github_stack(workdir, &pr_target_repo, &numbers);
    }

    Ok(())
}

/// Push to GitLab: push each branch with `merge_request.create` push options
/// so GitLab creates or updates a merge request, then surface the MR URL from
/// the push output. Re-published upstack layers carry only the target option,
/// updating an existing MR without creating one.
///
/// Push options apply to the whole push and each layer targets a different
/// branch, so layers go out one push at a time, bottom first. Pushing the
/// upstream target branch itself falls back to a plain push.
fn push_gitlab(workdir: &Path, remote: &str, plan: &PushPlan, force: bool) -> Result<()> {
    if plan.requested() == plan.target_branch {
        return push_plain(workdir, remote, plan, force);
    }

    for (layer, republish) in plan.pr_layers() {
        let target_opt = format!("merge_request.target={}", layer.base);
        let mut args = vec!["push"];
        args.extend_from_slice(force_args(force));
        if !republish {
            args.extend_from_slice(&["-o", "merge_request.create"]);
        }
        args.extend_from_slice(&["-o", &target_opt, "-u", remote, &layer.branch]);
        let stderr = run_push_capture(workdir, &args)?;
        let mut message = format!("Pushed `{}` to `{}`", layer.branch, remote);
        append_remote_urls(&mut message, &stderr);
        msg::success(&message);
    }
    report_not_pushed(plan);
    Ok(())
}

/// Azure DevOps coordinates parsed from a git remote URL.
struct AzureRemote {
    /// Organization URL, e.g. `https://dev.azure.com/<org>`.
    org_url: String,
    /// Team project name, when it can be read from the URL.
    project: Option<String>,
    /// Repository name, when it can be read from the URL.
    repository: Option<String>,
}

/// Extract the Azure DevOps organization URL, project, and repository from a
/// remote URL (`dev.azure.com` HTTPS or SSH, or legacy `<org>.visualstudio.com`
/// which yields the org only). `None` when the URL is unrecognised.
///
/// The project matters because `az repos pr create` only auto-detects it for
/// the HTTPS form; an SSH remote needs it passed via `--project`.
fn extract_azure_remote(repo: &Repository, remote: &str) -> Option<AzureRemote> {
    let remote = repo.find_remote(remote).ok()?;
    let url = remote.url().ok()?;

    let opt = |s: &str| (!s.is_empty()).then(|| s.to_string());

    // Repository is the segment after `_git` (HTTPS form), or the last segment
    // when there is no `_git` marker (SSH form: `<org>/<project>/<repo>`).
    let repository = |parts: &[&str]| {
        parts
            .iter()
            .position(|p| *p == "_git")
            .and_then(|i| parts.get(i + 1))
            .or_else(|| parts.get(2))
            .and_then(|r| opt(r.trim_end_matches(".git")))
    };

    let split_org_project = |rest: &str| {
        let parts: Vec<&str> = rest.split('/').collect();
        let org = opt(parts.first()?)?;
        let project = parts.get(1).and_then(|p| opt(p));
        Some((org, project, repository(&parts)))
    };

    if let Some(rest) = url.strip_prefix("https://dev.azure.com/") {
        let (org, project, repository) = split_org_project(rest)?;
        return Some(AzureRemote {
            org_url: format!("https://dev.azure.com/{}", org),
            project,
            repository,
        });
    }

    if let Some(rest) = url.strip_prefix("git@ssh.dev.azure.com:v3/") {
        let (org, project, repository) = split_org_project(rest)?;
        return Some(AzureRemote {
            org_url: format!("https://dev.azure.com/{}", org),
            project,
            repository,
        });
    }

    if let Some(rest) = url.strip_prefix("https://")
        && let Some((host, path)) = rest.split_once('/')
        && host.ends_with(".visualstudio.com")
    {
        // Legacy collection URLs are ambiguous about the project segment, so
        // leave it to az auto-detection rather than guessing.
        let parts: Vec<&str> = path.split('/').collect();
        return Some(AzureRemote {
            org_url: format!("https://{}", host),
            project: None,
            repository: repository(&parts),
        });
    }

    None
}

/// `az` arguments locating the repository: `--org` (plus `--project` and
/// `--repository`, which az stops auto-detecting once the org is explicit)
/// when the remote URL could be parsed, `--detect` otherwise.
fn azure_location_args(azure: Option<&AzureRemote>) -> Vec<&str> {
    let Some(azure) = azure else {
        return vec!["--detect"];
    };
    let mut args = vec!["--org", azure.org_url.as_str()];
    if let Some(project) = &azure.project {
        args.extend(["--project", project.as_str()]);
    }
    if let Some(repository) = &azure.repository {
        args.extend(["--repository", repository.as_str()]);
    }
    args
}

/// Build a `Command` for the Azure CLI.
///
/// On Windows `az` usually ships as `az.cmd`/`az.bat`, which `CreateProcess`
/// cannot start directly. Naming the script explicitly lets std run it via
/// `cmd.exe` with every argument escaped, where a hand-rolled `cmd /C az`
/// would let cmd expand `%VAR%` and reparse quotes inside PR titles.
fn az_command() -> Command {
    Command::new(az_program())
}

fn az_program() -> &'static str {
    static PROGRAM: OnceLock<&'static str> = OnceLock::new();
    PROGRAM.get_or_init(|| {
        if !cfg!(windows) {
            return "az";
        }
        ["az.cmd", "az.bat"]
            .into_iter()
            .find(|name| on_path(name))
            .unwrap_or("az")
    })
}

/// True when some `PATH` directory holds `file`.
fn on_path(file: &str) -> bool {
    std::env::var_os("PATH")
        .is_some_and(|path| std::env::split_paths(&path).any(|dir| dir.join(file).is_file()))
}

/// Push to Azure DevOps: push the plan's branches, then look after their PRs.
///
/// An existing PR is reported as is (`az repos pr update` cannot change its
/// target); a missing one is created with `az repos pr create`, which opens
/// the browser on it. A stacked branch never reaches here — see
/// [`refuse_stacked_azure`].
fn push_azure(
    repo: &Repository,
    workdir: &Path,
    remote: &str,
    plan: &PushPlan,
    info: &repo::RepoInfo,
    force: bool,
) -> Result<()> {
    push_plain(workdir, remote, plan, force)?;

    let start = Instant::now();
    let az_check = az_command().arg("--version").output();
    let az_available = az_check.as_ref().is_ok_and(|o| o.status.success());
    let duration_ms = start.elapsed().as_millis();
    loom_trace::log_command("az", "--version", duration_ms, az_available, "");

    if !az_available {
        msg::warn(
            "Install 'az' CLI to create pull requests: \
             https://learn.microsoft.com/cli/azure/install-azure-cli",
        );
        return Ok(());
    }

    // Extract the org URL so we can pass --org explicitly rather than relying
    // on --detect, which produces a misleading "need to login" error when it
    // fails to infer the organisation from the remote URL.
    let azure = extract_azure_remote(repo, remote);

    for (layer, republish) in plan.pr_layers() {
        if let Some(pr_url) = find_existing_azure_pr(workdir, &layer.branch, azure.as_ref()) {
            msg::success(&format!("PR updated: {}", pr_url));
            continue;
        }
        if republish {
            continue;
        }

        // Post-mutation: the branch is already pushed, and PR creation opens a
        // browser or prompts for a title — never do that behind an agent's
        // back (see spec 019).
        if agent_mode::enabled() {
            msg::warn(&format!(
                "Skipped creating a PR for `{}` (agent mode)\n\
                 Create it on Azure DevOps, or run `loom push {}` interactively",
                layer.branch, layer.branch
            ));
            continue;
        }

        let (title, description) =
            pr_title_and_description(repo, info, &layer.branch, &layer.base)?;
        create_azure_pr(workdir, layer, &title, &description, azure.as_ref())?;
    }

    Ok(())
}

/// Run `az repos pr create` for one layer, with `--open` so the browser
/// shows the new PR.
fn create_azure_pr(
    workdir: &Path,
    layer: &Layer,
    title: &str,
    description: &str,
    azure: Option<&AzureRemote>,
) -> Result<()> {
    // Write description to a temp file and pass `--description @<path>` to az,
    // so lines that start with `-` (e.g. `---` separators) are never taken
    // for options.
    let mut desc_file = tempfile::Builder::new()
        .suffix(".txt")
        .tempfile()
        .context("Failed to create temp file for PR description")?;
    write!(desc_file, "{}", description).context("Failed to write PR description")?;
    let desc_path = desc_file.path().to_string_lossy().into_owned();
    let desc_arg = format!("@{}", desc_path);

    // `--open` shows the new PR in the browser, so nothing reads stdout back.
    let mut args: Vec<&str> = vec![
        "repos",
        "pr",
        "create",
        "--open",
        "--source-branch",
        &layer.branch,
        "--target-branch",
        &layer.base,
        "--title",
        title,
    ];

    args.extend(azure_location_args(azure));

    if !description.is_empty() {
        args.push("--description");
        args.push(&desc_arg);
    }

    let start = Instant::now();
    let output = az_command().current_dir(workdir).args(&args).output()?;
    let duration_ms = start.elapsed().as_millis();
    loom_trace::log_command(
        "az",
        &args.join(" "),
        duration_ms,
        output.status.success(),
        &String::from_utf8_lossy(&output.stderr),
    );

    if !output.status.success() {
        msg::warn(&format!(
            "Could not create a PR for `{}` — see `loom trace`",
            layer.branch
        ));
    }

    Ok(())
}

/// Browser URL of an Azure DevOps PR, built from its structured fields since
/// the API URL uses GUIDs and lacks the `/pullrequest/` path.
fn azure_pr_url(pr: &serde_json::Value) -> Option<String> {
    let repo_url = pr["repository"]["url"].as_str()?;
    let org = repo_url
        .strip_prefix("https://dev.azure.com/")?
        .split('/')
        .next()?;
    let project = pr["repository"]["project"]["name"].as_str()?;
    let repo = pr["repository"]["name"].as_str()?;
    let pr_id = pr["pullRequestId"].as_u64()?;

    Some(format!(
        "https://dev.azure.com/{org}/{project}/_git/{repo}/pullrequest/{pr_id}"
    ))
}

/// The web URL of an existing Azure DevOps PR for the source branch, or
/// `None` when there is none or the check fails.
fn find_existing_azure_pr(
    workdir: &Path,
    branch: &str,
    azure: Option<&AzureRemote>,
) -> Option<String> {
    let mut cmd = az_command();
    cmd.current_dir(workdir);
    cmd.args([
        "repos",
        "pr",
        "list",
        "--source-branch",
        branch,
        "--output",
        "json",
    ]);
    cmd.args(azure_location_args(azure));
    let output = cmd.output().ok()?;

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

    let stdout = String::from_utf8_lossy(&output.stdout);
    let prs: serde_json::Value = serde_json::from_str(stdout.trim()).ok()?;
    azure_pr_url(prs.get(0)?)
}

/// Push to Gerrit without creating a review (plain force push). A branch not
/// already `wip/`-prefixed prompts first, since deleting a non-wip remote
/// branch later needs a Gerrit admin: push as-is, push as `wip/<branch>`, or
/// cancel.
fn push_gerrit_no_pr(workdir: &Path, remote: &str, branch: &str, force: bool) -> Result<()> {
    if branch.starts_with("wip/") {
        return push_plain(workdir, remote, &PushPlan::single(branch), force);
    }

    let opt_as_is = format!("Push as `{}` (admin required to delete it later)", branch);
    let opt_wip = format!("Push as `wip/{}` instead", branch);

    let choice = msg::select(
        &format!(
            "Branch `{}` is not prefixed with `wip/` — a Gerrit admin will be needed to delete the remote branch later",
            branch
        ),
        vec![opt_as_is.clone(), opt_wip.clone(), "Cancel".to_string()],
        "no flag answers this — ask the user; rename with `loom reword <branch> -m wip/<branch>` or re-run interactively",
    )?;

    if choice == opt_as_is {
        push_plain(workdir, remote, &PushPlan::single(branch), force)
    } else if choice == opt_wip {
        let wip_name = format!("wip/{}", branch);
        let refspec = format!("{}:{}", branch, wip_name);
        let mut args = vec!["push"];
        args.extend_from_slice(force_args(force));
        args.extend_from_slice(&[remote, &refspec]);
        git::run_git(workdir, &args)?;
        msg::success(&format!(
            "Pushed `{}` to `{}` as `{}`",
            branch, remote, wip_name
        ));
        Ok(())
    } else {
        Err(msg::cancelled())
    }
}

/// Push to Gerrit with the `refs/for/` refspec, surfacing the review URLs
/// Gerrit prints in the push output.
fn push_gerrit(workdir: &Path, remote: &str, branch: &str, target_branch: &str) -> Result<()> {
    let refspec = format!("{}:refs/for/{}", branch, target_branch);

    let stderr = run_push_capture(workdir, &["push", remote, &refspec])?;

    let mut message = format!(
        "Pushed `{}` to `{}` (Gerrit: `refs/for/{}`)",
        branch, remote, target_branch
    );
    append_remote_urls(&mut message, &stderr);
    msg::success(&message);

    Ok(())
}

#[cfg(test)]
#[path = "push_test.rs"]
mod tests;