ngit 3.0.2

nostr plugin for git
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
//! End-to-end coverage of `ngit pr merge` and its `ngit merge` alias.
//!
//! Both spellings create a no-ff merge commit of a PR branch onto the
//! repository's default branch with a `Merge #<id>: <title>` subject, records
//! the PR's nevent and a `PR-Author:` trailer (npub always; display name only
//! when the author's kind-0 metadata is cached), plus (unless
//! `--exclude-description`) the latest cover note or PR description in the
//! merge-commit body, leaves the default branch checked out, and does **not**
//! push anything (neither git data nor a nostr status event). Existing staged,
//! unstaged, and untracked work is preserved across the merge and checkout.
//! Linked worktrees may merge when they own the target branch; another
//! worktree owning that branch causes a refusal before either tree is changed.
//!
//! ## Scenario shape (shared by every test)
//!
//! - One vanilla relay (`"default"`) + one GRASP (`"repo"`).
//! - Maintainer publishes the repo via `harness.publish_repo`.
//! - A fresh contributor publishes three PR-kind proposals via
//!   `harness.publish_three_open_proposals`.
//! - The maintainer clone (`publisher`) is where the merge happens — it is on
//!   `main` with an `origin` remote, matching what a maintainer does.
//!
//! Assertions are on observable side-effects (refs/commits on disk, exit
//! status), never on literal stdout, per the harness boundary rules.

use std::path::Path;

use anyhow::{Context, Result};
use nostr::prelude::{Filter, FromBech32, Kind, Nip19Event, ToBech32};
use serde_json::Value;
use test_harness::{CloneLogin, Harness, PublishRepoOpts, PublishedPr, PublishedRepo, Repo};

struct Setup {
    harness: Harness,
    _published: PublishedRepo,
    prs: [PublishedPr; 3],
    publisher: Repo,
}

async fn setup() -> Result<Setup> {
    let harness = Harness::builder(
        env!("CARGO_BIN_EXE_ngit"),
        env!("CARGO_BIN_EXE_git-remote-nostr"),
    )
    .with_relay("default")
    .with_grasp_server("repo")
    .build()
    .await?;

    let (publisher, published) = harness
        .publish_repo(PublishRepoOpts {
            display_name: Some("merge maintainer".into()),
            identifier: Some("merge-repo".into()),
            ..Default::default()
        })
        .await?;

    let prs = harness.publish_three_open_proposals(&published).await?;

    Ok(Setup {
        harness,
        _published: published,
        prs,
        publisher,
    })
}

/// Long-form `pr/<branch>(<root-event-id-shorthand>)` branch name —
/// matches `CoverLetter::get_branch_name_with_pr_prefix_and_shorthand_id`.
fn expected_branch_name(pr: &PublishedPr) -> String {
    let hex = pr.event_id.to_hex();
    format!("pr/{}({})", pr.branch_name, &hex[..8])
}

async fn git_ok<I, S>(repo: &Repo, args: I, label: &str) -> Result<()>
where
    I: IntoIterator<Item = S>,
    S: AsRef<std::ffi::OsStr>,
{
    git_ok_at(repo, repo.dir(), args, label).await
}

async fn git_ok_at<I, S>(repo: &Repo, dir: &Path, args: I, label: &str) -> Result<()>
where
    I: IntoIterator<Item = S>,
    S: AsRef<std::ffi::OsStr>,
{
    let mut command = repo.git(args);
    command.current_dir(dir);
    let out = command
        .output()
        .await
        .with_context(|| format!("failed to spawn {label}"))?;
    anyhow::ensure!(
        out.status.success(),
        "{label} exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    Ok(())
}

async fn git_stdout_at(repo: &Repo, dir: &Path, args: &[&str], label: &str) -> Result<Vec<u8>> {
    let mut command = repo.git(args.iter().copied());
    command.current_dir(dir);
    let out = command
        .output()
        .await
        .with_context(|| format!("failed to spawn {label}"))?;
    anyhow::ensure!(
        out.status.success(),
        "{label} exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    Ok(out.stdout)
}

#[derive(Debug, PartialEq)]
struct DirtyWorktreeState {
    status: Vec<u8>,
    staged_diff: Vec<u8>,
    unstaged_diff: Vec<u8>,
    readme: Vec<u8>,
    untracked: Vec<u8>,
    stashes: Vec<u8>,
}

async fn dirty_worktree_state(repo: &Repo) -> Result<DirtyWorktreeState> {
    dirty_worktree_state_at(repo, repo.dir()).await
}

async fn dirty_worktree_state_at(repo: &Repo, dir: &Path) -> Result<DirtyWorktreeState> {
    Ok(DirtyWorktreeState {
        status: git_stdout_at(repo, dir, &["status", "--porcelain=v1"], "git status").await?,
        staged_diff: git_stdout_at(
            repo,
            dir,
            &["diff", "--cached", "--binary", "--no-ext-diff"],
            "git diff --cached",
        )
        .await?,
        unstaged_diff: git_stdout_at(
            repo,
            dir,
            &["diff", "--binary", "--no-ext-diff"],
            "git diff",
        )
        .await?,
        readme: std::fs::read(dir.join("README.md")).context("read README.md")?,
        untracked: std::fs::read(dir.join("dirty.md")).context("read dirty.md")?,
        stashes: git_stdout_at(
            repo,
            dir,
            &["stash", "list", "--format=%H%x09%gs"],
            "git stash list",
        )
        .await?,
    })
}

async fn make_worktree_staged_unstaged_and_untracked(repo: &Repo) -> Result<()> {
    make_worktree_staged_unstaged_and_untracked_at(repo, repo.dir()).await
}

async fn make_worktree_staged_unstaged_and_untracked_at(repo: &Repo, dir: &Path) -> Result<()> {
    std::fs::write(dir.join("README.md"), "staged change\n").context("write staged README.md")?;
    git_ok_at(repo, dir, ["add", "README.md"], "git add README.md").await?;
    std::fs::write(dir.join("README.md"), "staged change\nunstaged change\n")
        .context("write unstaged README.md")?;
    std::fs::write(dir.join("dirty.md"), "untracked change\n").context("write dirty.md")?;
    Ok(())
}

async fn rev_parse(repo: &Repo, rev: &str) -> Result<String> {
    rev_parse_at(repo, repo.dir(), rev).await
}

async fn rev_parse_at(repo: &Repo, dir: &Path, rev: &str) -> Result<String> {
    let mut command = repo.git(["rev-parse", rev]);
    command.current_dir(dir);
    let out = command
        .output()
        .await
        .with_context(|| format!("failed to spawn git rev-parse {rev}"))?;
    anyhow::ensure!(
        out.status.success(),
        "git rev-parse {rev} exited {:?}: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr),
    );
    Ok(String::from_utf8(out.stdout)
        .context("git rev-parse stdout not utf-8")?
        .trim()
        .to_string())
}

async fn current_branch(repo: &Repo) -> Result<String> {
    current_branch_at(repo, repo.dir()).await
}

async fn current_branch_at(repo: &Repo, dir: &Path) -> Result<String> {
    let mut command = repo.git(["symbolic-ref", "--short", "HEAD"]);
    command.current_dir(dir);
    let out = command
        .output()
        .await
        .context("failed to spawn git symbolic-ref HEAD")?;
    anyhow::ensure!(
        out.status.success(),
        "git symbolic-ref --short HEAD exited {:?}: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr),
    );
    Ok(String::from_utf8(out.stdout)
        .context("git symbolic-ref stdout not utf-8")?
        .trim()
        .to_string())
}

#[derive(Debug, PartialEq)]
struct LocalGitState {
    current_branch: String,
    head: String,
    branch_refs: Vec<u8>,
}

async fn local_git_state(repo: &Repo) -> Result<LocalGitState> {
    Ok(LocalGitState {
        current_branch: current_branch(repo).await?,
        head: rev_parse(repo, "HEAD").await?,
        branch_refs: git_stdout_at(
            repo,
            repo.dir(),
            &[
                "for-each-ref",
                "--format=%(refname) %(objectname)",
                "refs/heads",
            ],
            "git for-each-ref refs/heads",
        )
        .await?,
    })
}

async fn assert_refusal_preserves_local_state(
    repo: &Repo,
    out: &std::process::Output,
    expected: &LocalGitState,
    label: &str,
) -> Result<()> {
    assert!(
        !out.status.success(),
        "{label} must refuse the proposal\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    assert_eq!(
        &local_git_state(repo).await?,
        expected,
        "{label} must not change HEAD or any local branch ref",
    );
    Ok(())
}

/// Full commit message (subject + body) of `<rev>`.
async fn commit_message(repo: &Repo, rev: &str) -> Result<String> {
    let out = repo
        .git(["log", "-1", "--format=%B", rev])
        .output()
        .await
        .with_context(|| format!("failed to spawn git log {rev}"))?;
    anyhow::ensure!(
        out.status.success(),
        "git log {rev} exited {:?}: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr),
    );
    Ok(String::from_utf8(out.stdout)
        .context("git log stdout not utf-8")?
        .to_string())
}

/// Number of parents of `<rev>` — a no-ff merge commit has 2.
async fn parent_count(repo: &Repo, rev: &str) -> Result<usize> {
    let out = repo
        .git(["rev-list", "--parents", "-n", "1", rev])
        .output()
        .await
        .with_context(|| format!("failed to spawn git rev-list {rev}"))?;
    anyhow::ensure!(out.status.success(), "git rev-list {rev} failed");
    let line = String::from_utf8(out.stdout).context("git rev-list stdout not utf-8")?;
    // line = "<commit> <parent1> <parent2> ..."
    Ok(line.split_whitespace().count().saturating_sub(1))
}

async fn run_merge(repo: &Repo, args: &[&str]) -> Result<std::process::Output> {
    run_merge_at(repo, repo.dir(), args).await
}

async fn run_merge_at(repo: &Repo, dir: &Path, args: &[&str]) -> Result<std::process::Output> {
    let mut argv = vec!["merge"];
    argv.extend_from_slice(args);
    let mut command = repo.ngit(argv);
    command.current_dir(dir);
    command.output().await.context("failed to spawn ngit merge")
}

async fn run_pr_merge(repo: &Repo, args: &[&str]) -> Result<std::process::Output> {
    let mut argv = vec!["pr", "merge"];
    argv.extend_from_slice(args);
    repo.ngit(argv)
        .output()
        .await
        .context("failed to spawn ngit pr merge")
}

async fn add_linked_worktree(repo: &Repo, dir: &Path, branch: &str) -> Result<()> {
    let mut command = repo.git(["worktree", "add"]);
    command.arg(dir).arg(branch);
    let out = command
        .output()
        .await
        .context("failed to spawn git worktree add")?;
    anyhow::ensure!(
        out.status.success(),
        "git worktree add exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    Ok(())
}

// ---------------------------------------------------------------------------
// 1. `ngit merge <hex>` from main creates a no-ff merge commit on the default
//    branch, leaves it checked out, records the PR in the body, no push.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn merge_by_id_creates_no_ff_merge_on_default_branch() -> Result<()> {
    let Setup {
        harness: _h,
        _published: _,
        prs,
        publisher,
    } = setup().await?;
    let pr = &prs[0];

    let main_before = rev_parse(&publisher, "main").await?;

    let out = run_merge(&publisher, &[&pr.event_id.to_hex()]).await?;
    anyhow::ensure!(
        out.status.success(),
        "ngit merge exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    // left checked out on the default branch
    assert_eq!(
        current_branch(&publisher).await?,
        "main",
        "should be left on the default branch after merge",
    );

    // a new commit advanced main
    let main_after = rev_parse(&publisher, "main").await?;
    assert_ne!(
        main_after, main_before,
        "main should have a new merge commit"
    );

    // it is a real merge commit (2 parents)
    assert_eq!(
        parent_count(&publisher, "main").await?,
        2,
        "no-ff merge should produce a 2-parent merge commit",
    );

    // the PR tip is an ancestor of the merge commit (it was merged in)
    let branch = expected_branch_name(pr);
    let pr_tip = rev_parse(&publisher, &branch).await?;
    assert_eq!(
        pr_tip, pr.tip,
        "local pr branch should sit at the published tip"
    );

    // commit subject is `Merge #<hex8>: <title>`; body records the nevent (as
    // a bare `nostr:` URI) and the PR description under a header.
    let msg = commit_message(&publisher, "main").await?;
    let shorthand = &pr.event_id.to_hex()[..8];
    let expected_subject = format!("Merge #{shorthand}: proposal");
    assert!(
        msg.lines()
            .next()
            .unwrap_or_default()
            .starts_with(&expected_subject),
        "merge commit subject should start with '{expected_subject}', got:\n{msg}",
    );
    assert!(
        msg.contains("nostr:nevent1"),
        "merge commit body should contain the PR nevent as a nostr: URI, got:\n{msg}",
    );
    assert!(
        msg.contains("PR description:"),
        "merge commit body should contain the PR description header, got:\n{msg}",
    );

    // the PR author is attributed: a `PR-Author:` trailer carrying the
    // author's npub on its own bare `nostr:` URI line. The display name is
    // best-effort (only when kind-0 metadata is in cache) so it is not
    // asserted here; see `author_trailer_carries_author_npub`.
    let author_npub = pr
        .author_pubkey
        .to_bech32()
        .context("failed to bech32-encode PR author pubkey")?;
    assert!(
        msg.contains("PR-Author:"),
        "merge commit body should contain a PR-Author trailer, got:\n{msg}",
    );
    assert!(
        msg.contains(&format!("nostr:{author_npub}")),
        "merge commit body should attribute the author by npub, got:\n{msg}",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// 2. `ngit merge` without id while on the pr/ branch infers the PR and carries
//    staged, unstaged, and untracked work across the branch switch.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn merge_without_id_infers_pr_from_current_branch() -> Result<()> {
    let Setup {
        harness: _h,
        _published: _,
        prs,
        publisher,
    } = setup().await?;
    let pr = &prs[0];

    // check out the PR branch first
    let out = publisher
        .ngit(["pr", "checkout", &pr.event_id.to_hex()])
        .output()
        .await
        .context("failed to spawn ngit pr checkout")?;
    anyhow::ensure!(
        out.status.success(),
        "ngit pr checkout exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    let branch = expected_branch_name(pr);
    assert_eq!(current_branch(&publisher).await?, branch);

    // An automatic backup must not disturb an existing user stash.
    std::fs::write(publisher.dir().join("prior-stash.md"), "keep me\n")
        .context("write prior-stash.md")?;
    git_ok(
        &publisher,
        [
            "stash",
            "push",
            "--include-untracked",
            "--message",
            "existing user stash",
        ],
        "git stash push",
    )
    .await?;

    make_worktree_staged_unstaged_and_untracked(&publisher).await?;
    let dirty_before = dirty_worktree_state(&publisher).await?;

    // merge with no id — should infer the PR from the checked-out branch
    let out = run_merge(&publisher, &[]).await?;
    anyhow::ensure!(
        out.status.success(),
        "ngit merge (no id) exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    assert_eq!(
        current_branch(&publisher).await?,
        "main",
        "should be left on the default branch after merge",
    );
    assert_eq!(
        parent_count(&publisher, "main").await?,
        2,
        "no-ff merge should produce a 2-parent merge commit",
    );
    assert_eq!(
        dirty_worktree_state(&publisher).await?,
        dirty_before,
        "the branch switch and merge must preserve the exact staged, unstaged, untracked, and stash state",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// 3. `ngit merge <id>` also preserves a dirty target-branch worktree.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn dirty_target_worktree_is_preserved_after_merge() -> Result<()> {
    let Setup {
        harness: _h,
        _published: _,
        prs,
        publisher,
    } = setup().await?;
    let pr = &prs[0];

    let main_before = rev_parse(&publisher, "main").await?;

    make_worktree_staged_unstaged_and_untracked(&publisher).await?;
    let dirty_before = dirty_worktree_state(&publisher).await?;

    let out = run_merge(&publisher, &[&pr.event_id.to_hex()]).await?;
    anyhow::ensure!(
        out.status.success(),
        "ngit merge exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    assert_ne!(
        rev_parse(&publisher, "main").await?,
        main_before,
        "main should advance to the merge commit",
    );
    assert_eq!(
        dirty_worktree_state(&publisher).await?,
        dirty_before,
        "the merge must preserve the exact staged, unstaged, untracked, and stash state",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// 3a. A linked worktree can merge while it owns the target branch, preserving
//     the dirty state in that worktree and leaving the primary worktree alone.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn linked_target_worktree_preserves_dirty_state_after_merge() -> Result<()> {
    let Setup {
        harness: _h,
        _published: _,
        prs,
        publisher,
    } = setup().await?;
    let pr = &prs[0];

    let out = publisher
        .ngit(["pr", "checkout", &pr.event_id.to_hex()])
        .output()
        .await
        .context("failed to spawn ngit pr checkout")?;
    anyhow::ensure!(
        out.status.success(),
        "ngit pr checkout exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    git_ok(&publisher, ["checkout", "main"], "git checkout main").await?;
    git_ok(
        &publisher,
        ["checkout", "-b", "primary-parking"],
        "git checkout -b primary-parking",
    )
    .await?;

    let linked_parent = tempfile::tempdir().context("create linked-worktree parent")?;
    let linked = linked_parent.path().join("target-worktree");
    add_linked_worktree(&publisher, &linked, "main").await?;
    let main_before = rev_parse_at(&publisher, &linked, "main").await?;

    make_worktree_staged_unstaged_and_untracked_at(&publisher, &linked).await?;
    let dirty_before = dirty_worktree_state_at(&publisher, &linked).await?;

    let out = run_merge_at(&publisher, &linked, &[&pr.event_id.to_hex()]).await?;
    anyhow::ensure!(
        out.status.success(),
        "ngit merge from linked target worktree exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    assert_eq!(current_branch_at(&publisher, &linked).await?, "main");
    assert_eq!(
        current_branch(&publisher).await?,
        "primary-parking",
        "the primary worktree branch must not change",
    );
    assert_ne!(
        rev_parse_at(&publisher, &linked, "main").await?,
        main_before,
        "main should advance to the merge commit",
    );
    assert_eq!(
        dirty_worktree_state_at(&publisher, &linked).await?,
        dirty_before,
        "the linked worktree must retain its exact dirty state",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// 3b. If another worktree owns the target branch, merging from a PR worktree
//     must refuse before touching either worktree or the shared target ref.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn linked_source_worktree_refuses_when_target_is_checked_out_elsewhere() -> Result<()> {
    let Setup {
        harness: _h,
        _published: _,
        prs,
        publisher,
    } = setup().await?;
    let pr = &prs[0];

    let out = publisher
        .ngit(["pr", "checkout", &pr.event_id.to_hex()])
        .output()
        .await
        .context("failed to spawn ngit pr checkout")?;
    anyhow::ensure!(
        out.status.success(),
        "ngit pr checkout exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    let pr_branch = expected_branch_name(pr);
    git_ok(&publisher, ["checkout", "main"], "git checkout main").await?;

    let linked_parent = tempfile::tempdir().context("create linked-worktree parent")?;
    let linked = linked_parent.path().join("source-worktree");
    add_linked_worktree(&publisher, &linked, &pr_branch).await?;
    let main_before = rev_parse(&publisher, "main").await?;
    make_worktree_staged_unstaged_and_untracked_at(&publisher, &linked).await?;
    let dirty_before = dirty_worktree_state_at(&publisher, &linked).await?;

    let out = run_merge_at(&publisher, &linked, &[]).await?;
    assert!(
        !out.status.success(),
        "ngit merge must refuse when the target branch is checked out in another worktree",
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("main") && stderr.contains("another worktree"),
        "the error should identify the target and other worktree, got:\n{stderr}",
    );

    assert_eq!(
        rev_parse(&publisher, "main").await?,
        main_before,
        "main must not advance",
    );
    assert_eq!(current_branch(&publisher).await?, "main");
    assert_eq!(current_branch_at(&publisher, &linked).await?, pr_branch);
    assert_eq!(
        dirty_worktree_state_at(&publisher, &linked).await?,
        dirty_before,
        "the refused merge must leave the linked worktree untouched",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// 3c. If the saved changes cannot apply to the merged target, the merge is
//     rolled back and the source branch plus its exact dirty state are
//     restored.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn conflicting_saved_worktree_rolls_back_merge_and_restores_source() -> Result<()> {
    let Setup {
        harness: _h,
        _published: _,
        prs,
        publisher,
    } = setup().await?;
    let pr = &prs[0];
    let main_before = rev_parse(&publisher, "main").await?;

    git_ok(
        &publisher,
        ["checkout", "-b", "local-work"],
        "git checkout -b local-work",
    )
    .await?;
    std::fs::write(publisher.dir().join("README.md"), "local branch base\n")
        .context("write local branch README.md")?;
    git_ok(&publisher, ["add", "README.md"], "git add README.md").await?;
    git_ok(
        &publisher,
        ["commit", "-m", "local branch base", "--no-gpg-sign"],
        "git commit local branch base",
    )
    .await?;

    make_worktree_staged_unstaged_and_untracked(&publisher).await?;
    let dirty_before = dirty_worktree_state(&publisher).await?;

    let out = run_merge(&publisher, &[&pr.event_id.to_hex()]).await?;
    assert!(
        !out.status.success(),
        "ngit merge must fail when the saved work cannot apply cleanly to the merged target",
    );
    assert_eq!(
        current_branch(&publisher).await?,
        "local-work",
        "rollback should restore the source branch",
    );
    assert_eq!(
        rev_parse(&publisher, "main").await?,
        main_before,
        "rollback must remove the merge commit from main",
    );
    assert_eq!(
        dirty_worktree_state(&publisher).await?,
        dirty_before,
        "rollback must restore the exact staged, unstaged, untracked, and stash state",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// 4. --exclude-description omits the PR description footer but keeps the
//    subject and the nevent reference.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn exclude_description_omits_body_footer() -> Result<()> {
    let Setup {
        harness: _h,
        _published: _,
        prs,
        publisher,
    } = setup().await?;
    let pr = &prs[0];

    let out = run_merge(
        &publisher,
        &[&pr.event_id.to_hex(), "--exclude-description"],
    )
    .await?;
    anyhow::ensure!(
        out.status.success(),
        "ngit merge --exclude-description exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    let msg = commit_message(&publisher, "main").await?;
    let shorthand = &pr.event_id.to_hex()[..8];
    assert!(
        msg.starts_with(&format!("Merge #{shorthand}: ")),
        "subject should still be present, got:\n{msg}",
    );
    assert!(
        msg.contains("nostr:nevent1"),
        "nevent reference should still be present, got:\n{msg}",
    );
    assert!(
        !msg.contains("PR description:") && !msg.contains("CoverNote:"),
        "description footer should be omitted with --exclude-description, got:\n{msg}",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// 5b. the `PR-Author:` trailer attributes the author by npub and survives
//     --exclude-description (attribution is not free-form description prose).
// ---------------------------------------------------------------------------

#[tokio::test]
async fn author_trailer_carries_author_npub() -> Result<()> {
    let Setup {
        harness: _h,
        _published: _,
        prs,
        publisher,
    } = setup().await?;
    let pr = &prs[0];

    let out = run_merge(
        &publisher,
        &[&pr.event_id.to_hex(), "--exclude-description"],
    )
    .await?;
    anyhow::ensure!(
        out.status.success(),
        "ngit merge --exclude-description exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    let msg = commit_message(&publisher, "main").await?;
    let author_npub = pr
        .author_pubkey
        .to_bech32()
        .context("failed to bech32-encode PR author pubkey")?;

    // The `PR-Author:` label and the author's npub (as a bare `nostr:` URI on
    // its own line) are always present, even with --exclude-description: the
    // attribution is metadata, not the suppressible description prose.
    assert!(
        msg.contains("PR-Author:"),
        "PR-Author trailer should survive --exclude-description, got:\n{msg}",
    );
    assert!(
        msg.contains(&format!("\nnostr:{author_npub}")),
        "author npub should be on its own bare nostr: URI line, got:\n{msg}",
    );

    Ok(())
}
// ---------------------------------------------------------------------------
// 5. merge without id while not on a pr/ branch fails clearly.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn merge_without_id_off_pr_branch_fails() -> Result<()> {
    let Setup {
        harness: _h,
        _published: _,
        prs: _,
        publisher,
    } = setup().await?;

    // on main, not a pr/ branch
    git_ok(&publisher, ["checkout", "main"], "git checkout main").await?;

    let out = run_merge(&publisher, &[]).await?;
    assert!(
        !out.status.success(),
        "ngit merge with no id off a pr/ branch should fail",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// 6. both spellings refuse proposals whose lifecycle is closed or applied.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn canonical_and_alias_refuse_closed_and_applied_prs() -> Result<()> {
    let Setup {
        harness: _h,
        _published: _,
        prs,
        publisher,
    } = setup().await?;
    let closed = &prs[0];
    let applied = &prs[1];

    let closed_id = closed.event_id.to_hex();
    let close = publisher
        .ngit(["pr", "close", &closed_id])
        .output()
        .await
        .context("failed to spawn ngit pr close")?;
    anyhow::ensure!(
        close.status.success(),
        "ngit pr close exited {:?}\nstdout: {}\nstderr: {}",
        close.status,
        String::from_utf8_lossy(&close.stdout),
        String::from_utf8_lossy(&close.stderr),
    );

    let applied_id = applied.event_id.to_hex();
    let first_merge = run_pr_merge(&publisher, &[&applied_id]).await?;
    anyhow::ensure!(
        first_merge.status.success(),
        "initial ngit pr merge exited {:?}\nstdout: {}\nstderr: {}",
        first_merge.status,
        String::from_utf8_lossy(&first_merge.stdout),
        String::from_utf8_lossy(&first_merge.stderr),
    );
    publisher.nostr_push(["origin", "main"]).await?;

    let state_before = local_git_state(&publisher).await?;
    let closed_merge = run_pr_merge(&publisher, &[&closed_id]).await?;
    assert_refusal_preserves_local_state(
        &publisher,
        &closed_merge,
        &state_before,
        "canonical ngit pr merge of a closed PR",
    )
    .await?;

    let closed_alias = run_merge(&publisher, &[&closed_id]).await?;
    assert_refusal_preserves_local_state(
        &publisher,
        &closed_alias,
        &state_before,
        "top-level ngit merge of a closed PR",
    )
    .await?;

    let applied_canonical = run_pr_merge(&publisher, &[&applied_id]).await?;
    assert_refusal_preserves_local_state(
        &publisher,
        &applied_canonical,
        &state_before,
        "canonical ngit pr merge of an applied PR",
    )
    .await?;

    let applied_merge = run_merge(&publisher, &[&applied_id]).await?;
    assert_refusal_preserves_local_state(
        &publisher,
        &applied_merge,
        &state_before,
        "top-level ngit merge of an applied PR",
    )
    .await?;

    Ok(())
}

// ---------------------------------------------------------------------------
// 7. merge without id on a *bare* `pr/<name>` branch the current user pushed
//    themselves (via `git push -u origin pr/<name>`, which has no `(<id>)`
//    shorthand) infers the PR.
//
//    This is the "user submitted their own PR with plain git" workflow: the
//    local branch carries no event-id shorthand, but it is linked to the
//    published PR because the logged-in user authored it. `ngit merge` with no
//    id must resolve it the same way `git-remote-nostr` maps the branch on
//    push (`is_event_proposal_root_for_branch`).
// ---------------------------------------------------------------------------

#[tokio::test]
async fn pr_merge_without_id_infers_self_submitted_bare_pr_branch() -> Result<()> {
    let harness = Harness::builder(
        env!("CARGO_BIN_EXE_ngit"),
        env!("CARGO_BIN_EXE_git-remote-nostr"),
    )
    .with_relay("default")
    .with_grasp_server("repo")
    .build()
    .await?;

    let (_publisher, published) = harness
        .publish_repo(PublishRepoOpts {
            display_name: Some("merge maintainer".into()),
            identifier: Some("merge-bare-branch-repo".into()),
            ..Default::default()
        })
        .await?;

    // The PR author clones and logs in as their own (fresh) account. They are
    // both the author of the PR and the one running `ngit merge` — the only
    // configuration in which a bare `pr/<name>` branch can be linked back to a
    // published PR.
    let author = harness
        .clone_published_repo(
            &published,
            CloneLogin::AsContributor {
                display_name: "self merging contributor".into(),
            },
        )
        .await?;

    // Submit the PR exactly as a user would: a plain `pr/<name>` branch pushed
    // with `git push -u origin pr/<name>`. `git-remote-nostr` turns this into
    // a KIND_PULL_REQUEST. No `ngit send`, no `(<id>)` shorthand.
    let branch = "pr/my-feature";
    author
        .git_ok(["checkout", "-b", branch], "git checkout -b pr/my-feature")
        .await?;
    std::fs::write(author.dir().join("feat.md"), "some content\n").context("write feat.md")?;
    author.git_ok(["add", "feat.md"], "git add feat.md").await?;
    author
        .git_ok(
            ["commit", "-m", "add feat.md", "--no-gpg-sign"],
            "git commit feat.md",
        )
        .await?;

    let pr_tip = rev_parse(&author, "HEAD").await?;

    author
        .nostr_push(["-u", "origin", branch])
        .await
        .context("git push -u origin pr/my-feature (PR creation) failed")?;

    // Still on the bare `pr/my-feature` branch with no `(<id>)` shorthand.
    assert_eq!(current_branch(&author).await?, branch);

    // Merge with no id — must infer the PR from the self-submitted bare branch.
    let out = run_pr_merge(&author, &[]).await?;
    anyhow::ensure!(
        out.status.success(),
        "ngit pr merge (no id) on a self-submitted bare pr/ branch exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    assert_eq!(
        current_branch(&author).await?,
        "main",
        "should be left on the default branch after merge",
    );
    assert_eq!(
        parent_count(&author, "main").await?,
        2,
        "no-ff merge should produce a 2-parent merge commit",
    );

    // the pushed PR tip is a parent of the merge commit (it was merged in)
    let merged_in = rev_parse(&author, "main^2").await?;
    assert_eq!(
        merged_in, pr_tip,
        "the merge commit's second parent should be the pushed PR tip",
    );

    let applied = harness
        .grasp("repo")
        .events(Filter::new().kind(Kind::GitStatusApplied))
        .await?;
    assert!(
        applied.is_empty(),
        "a local PR merge must not publish an applied status before Git push",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// 8. a merge that conflicts is left in progress for manual resolution rather
//    than aborted as a hard error. `ngit merge` exits 0, the repository is left
//    mid-merge (MERGE_HEAD present) on the default branch, and the prepared
//    MERGE_MSG carries ngit's composed message (subject + nevent + PR-Author
//    trailer) so the user's eventual `git commit` keeps the nostr provenance
//    rather than git's generic conflict message.
// ---------------------------------------------------------------------------

/// Read the contents of a git-relative path (e.g. `MERGE_HEAD`, `MERGE_MSG`)
/// via `git rev-parse --git-path`, returning `None` when the file is absent.
async fn read_git_path(repo: &Repo, name: &str) -> Result<Option<String>> {
    let out = repo
        .git(["rev-parse", "--git-path", name])
        .output()
        .await
        .with_context(|| format!("failed to spawn git rev-parse --git-path {name}"))?;
    anyhow::ensure!(
        out.status.success(),
        "git rev-parse --git-path {name} exited {:?}: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr),
    );
    let rel = String::from_utf8(out.stdout)
        .context("git rev-parse stdout not utf-8")?
        .trim()
        .to_string();
    let path = repo.dir().join(rel);
    match std::fs::read_to_string(&path) {
        Ok(s) => Ok(Some(s)),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(e).with_context(|| format!("failed to read {path:?}")),
    }
}

#[tokio::test]
async fn conflicting_pr_merge_is_left_in_progress_for_manual_resolution() -> Result<()> {
    let Setup {
        harness: _h,
        _published: _,
        prs,
        publisher,
    } = setup().await?;
    let pr = &prs[0];

    // The first proposal (prefix "a") adds `a3.md`. Create a *conflicting*
    // `a3.md` on main so the no-ff merge of the PR cannot apply cleanly.
    std::fs::write(publisher.dir().join("a3.md"), "main side content\n")
        .context("write conflicting a3.md on main")?;
    publisher.git_ok(["add", "a3.md"], "git add a3.md").await?;
    publisher
        .git_ok(
            ["commit", "-m", "add a3.md (main side)", "--no-gpg-sign"],
            "git commit a3.md on main",
        )
        .await?;

    let main_before = rev_parse(&publisher, "main").await?;

    // The merge conflicts. ngit must NOT treat this as a hard failure: it
    // hands the in-progress merge back to the user, exiting 0.
    let out = run_pr_merge(&publisher, &[&pr.event_id.to_hex(), "--json"]).await?;
    anyhow::ensure!(
        out.status.success(),
        "ngit pr merge should exit 0 and leave the conflicted merge in progress, got {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    let json: Value = serde_json::from_slice(&out.stdout)
        .with_context(|| format!("conflicted merge stdout is not JSON: {:?}", out.stdout))?;
    assert_eq!(json["command_status"], "ok", "{json}");
    assert_eq!(json["action"], "conflicted", "{json}");
    assert_eq!(json["entity"], "pr", "{json}");
    let id = json["id"]
        .as_str()
        .with_context(|| format!("conflicted merge id is not a string: {json}"))?;
    assert_eq!(
        Nip19Event::from_bech32(id)
            .context("conflicted merge id is not a valid nevent")?
            .event_id,
        pr.event_id,
        "conflicted merge must identify the proposal: {json}",
    );
    assert!(json.get("ci").is_none(), "{json}");
    assert!(json.get("ci_warning").is_none(), "{json}");
    assert!(json.get("event").is_none(), "{json}");

    // Still on the default branch.
    assert_eq!(
        current_branch(&publisher).await?,
        "main",
        "should be left on the default branch with the merge in progress",
    );

    // main has NOT advanced — the merge commit is not yet created.
    assert_eq!(
        rev_parse(&publisher, "main").await?,
        main_before,
        "main must not advance until the user resolves and commits",
    );

    // A merge is in progress: MERGE_HEAD is present.
    assert!(
        read_git_path(&publisher, "MERGE_HEAD").await?.is_some(),
        "MERGE_HEAD should be present (merge in progress)",
    );

    // The prepared MERGE_MSG carries ngit's composed message, not git's
    // generic "Merge branch ... / Conflicts:" default — so the user's eventual
    // `git commit` keeps the nostr provenance.
    let merge_msg = read_git_path(&publisher, "MERGE_MSG")
        .await?
        .context("MERGE_MSG should be present (prepared by ngit)")?;
    let shorthand = &pr.event_id.to_hex()[..8];
    assert!(
        merge_msg.contains(&format!("Merge #{shorthand}: ")),
        "prepared MERGE_MSG should carry ngit's subject, got:\n{merge_msg}",
    );
    assert!(
        merge_msg.contains("nostr:nevent1"),
        "prepared MERGE_MSG should carry the PR nevent, got:\n{merge_msg}",
    );
    assert!(
        merge_msg.contains("PR-Author:"),
        "prepared MERGE_MSG should carry the PR-Author trailer, got:\n{merge_msg}",
    );

    // Completing the merge the normal way (resolve + add + commit) produces the
    // 2-parent merge commit carrying ngit's prepared message.
    std::fs::write(publisher.dir().join("a3.md"), "resolved content\n")
        .context("write resolved a3.md")?;
    publisher
        .git_ok(["add", "a3.md"], "git add resolved a3.md")
        .await?;
    publisher
        .git_ok(
            ["commit", "--no-edit", "--no-gpg-sign"],
            "git commit to finish the merge",
        )
        .await?;

    assert_eq!(
        parent_count(&publisher, "main").await?,
        2,
        "completing the resolved merge should produce a 2-parent merge commit",
    );
    let msg = commit_message(&publisher, "main").await?;
    assert!(
        msg.contains(&format!("Merge #{shorthand}: ")) && msg.contains("nostr:nevent1"),
        "the completed merge commit should carry ngit's prepared message, got:\n{msg}",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// 7. a local pr/ branch that has drifted ahead of the published PR tip
//    (unpushed local commits) aborts the merge. The autogenerated merge message
//    describes the *published* PR state and other maintainers can only
//    reproduce a merge of the published tip, so merging an un-published local
//    tip is refused: push first.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn local_branch_ahead_of_published_tip_aborts_merge() -> Result<()> {
    let Setup {
        harness: _h,
        _published: _,
        prs,
        publisher,
    } = setup().await?;
    let pr = &prs[0];

    // Check out the PR branch the normal way: this creates a local
    // `pr/<name>(<shorthand>)` branch at the published tip, which is the
    // branch `ngit merge` resolves and merges.
    let out = publisher
        .ngit(["pr", "checkout", &pr.event_id.to_hex()])
        .output()
        .await
        .context("failed to spawn ngit pr checkout")?;
    anyhow::ensure!(
        out.status.success(),
        "ngit pr checkout exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    let branch = expected_branch_name(pr);
    assert_eq!(current_branch(&publisher).await?, branch);

    // Add a *local* commit on top of the PR branch WITHOUT pushing/publishing
    // it. The local branch tip is now ahead of the published PR tip.
    std::fs::write(publisher.dir().join("more.md"), "unpushed\n").context("write more.md")?;
    publisher
        .git_ok(["add", "more.md"], "git add more.md")
        .await?;
    publisher
        .git_ok(
            ["commit", "-m", "add more.md (unpushed)", "--no-gpg-sign"],
            "git commit more.md",
        )
        .await?;

    let main_before = rev_parse(&publisher, "main").await?;

    // Merge with no id — must refuse because the local tip is ahead of the
    // published PR tip (unpushed local work).
    let out = run_merge(&publisher, &[]).await?;
    assert!(
        !out.status.success(),
        "ngit merge must abort when the local pr/ branch is ahead of the published tip\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    // main must not have advanced.
    assert_eq!(
        rev_parse(&publisher, "main").await?,
        main_before,
        "main must not advance when the merge is aborted",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// 8. a *bare* self-submitted `pr/<name>` branch (no shorthand) that has drifted
//    ahead of the published PR tip (unpushed local commits) also aborts the
//    merge. Previously the bare-branch path created a fresh
//    `pr/<name>(<shorthand>)` branch at the published tip and merged that,
//    silently bypassing the author's unpushed local work; the merge must now
//    detect the drift on the bare branch and abort.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn self_submitted_bare_branch_ahead_of_published_tip_aborts_merge() -> Result<()> {
    let harness = Harness::builder(
        env!("CARGO_BIN_EXE_ngit"),
        env!("CARGO_BIN_EXE_git-remote-nostr"),
    )
    .with_relay("default")
    .with_grasp_server("repo")
    .build()
    .await?;

    let (_publisher, published) = harness
        .publish_repo(PublishRepoOpts {
            display_name: Some("merge maintainer".into()),
            identifier: Some("merge-bare-drift-repo".into()),
            ..Default::default()
        })
        .await?;

    // The PR author clones, logs in as their own account, and submits a PR via
    // a plain pushed `pr/<name>` branch (no shorthand), as in test 6.
    let author = harness
        .clone_published_repo(
            &published,
            CloneLogin::AsContributor {
                display_name: "self merging drifting contributor".into(),
            },
        )
        .await?;

    let branch = "pr/bare-drift-feature";
    author
        .git_ok(
            ["checkout", "-b", branch],
            "git checkout -b pr/bare-drift-feature",
        )
        .await?;
    std::fs::write(author.dir().join("feat.md"), "some content\n").context("write feat.md")?;
    author.git_ok(["add", "feat.md"], "git add feat.md").await?;
    author
        .git_ok(
            ["commit", "-m", "add feat.md", "--no-gpg-sign"],
            "git commit feat.md",
        )
        .await?;

    // Publish this tip as the PR (still on the bare branch, no shorthand).
    author
        .nostr_push(["-u", "origin", branch])
        .await
        .context("git push -u origin pr/bare-drift-feature (PR creation) failed")?;
    assert_eq!(current_branch(&author).await?, branch);

    // Add a *local* commit on top of the bare branch WITHOUT pushing it. The
    // bare branch tip is now ahead of the published PR tip.
    std::fs::write(author.dir().join("more.md"), "unpushed\n").context("write more.md")?;
    author.git_ok(["add", "more.md"], "git add more.md").await?;
    author
        .git_ok(
            ["commit", "-m", "add more.md (unpushed)", "--no-gpg-sign"],
            "git commit more.md",
        )
        .await?;

    let main_before = rev_parse(&author, "main").await?;

    // Merge with no id — must refuse because the bare branch is ahead of the
    // published PR tip, rather than silently merging the published tip and
    // bypassing the unpushed local work.
    let out = run_merge(&author, &[]).await?;
    assert!(
        !out.status.success(),
        "ngit merge must abort when the bare self-submitted pr/ branch is ahead of the published tip\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    // main must not have advanced.
    assert_eq!(
        rev_parse(&author, "main").await?,
        main_before,
        "main must not advance when the merge is aborted",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// 9. a maintainer who checked out a *contributor's* PR under a bare `pr/<name>`
//    local branch (no `(<id>)` shorthand — e.g. created by hand from the
//    fetched PR tip) resolves the PR by matching the branch tip against the
//    published PR tips. The author-based bare-branch mapping cannot link it
//    because the maintainer did not author the PR, so this exercises the
//    tip-match fallback.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn merge_without_id_resolves_unauthored_bare_branch_by_tip() -> Result<()> {
    let Setup {
        harness: _h,
        _published: _,
        prs,
        publisher,
    } = setup().await?;
    let pr = &prs[0];

    // Explicit checkout makes the contributor's PR tip object locally
    // available under the standard shorthand branch. Return to main, then
    // create a bare `pr/<name>` branch at the published tip — what a
    // maintainer does when checking out a contributor's PR with plain git
    // under a friendly branch name.
    let checkout = publisher
        .ngit(["pr", "checkout", &pr.event_id.to_hex()])
        .output()
        .await
        .context("failed to spawn ngit pr checkout")?;
    anyhow::ensure!(
        checkout.status.success(),
        "ngit pr checkout exited {:?}\nstdout: {}\nstderr: {}",
        checkout.status,
        String::from_utf8_lossy(&checkout.stdout),
        String::from_utf8_lossy(&checkout.stderr),
    );
    publisher
        .git_ok(["checkout", "main"], "git checkout main")
        .await?;
    let bare_branch = format!("pr/{}", pr.branch_name);
    publisher
        .git_ok(
            ["checkout", "-b", &bare_branch, &pr.tip],
            "git checkout -b bare pr branch at published tip",
        )
        .await?;

    let out = run_merge(&publisher, &[]).await?;
    anyhow::ensure!(
        out.status.success(),
        "ngit merge (no id) on an unauthored bare pr/ branch exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    assert_eq!(
        current_branch(&publisher).await?,
        "main",
        "should be left on the default branch after merge",
    );
    assert_eq!(
        parent_count(&publisher, "main").await?,
        2,
        "no-ff merge should produce a 2-parent merge commit",
    );

    // the right PR was merged: the second parent is the published tip and the
    // subject carries this PR's event-id shorthand.
    let merged_in = rev_parse(&publisher, "main^2").await?;
    assert_eq!(
        merged_in, pr.tip,
        "the merge commit's second parent should be the published PR tip",
    );
    let msg = commit_message(&publisher, "main").await?;
    let shorthand = &pr.event_id.to_hex()[..8];
    assert!(
        msg.starts_with(&format!("Merge #{shorthand}: ")),
        "merge commit subject should carry the tip-matched PR's shorthand, got:\n{msg}",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// 10. a *logged-out* user on their own self-submitted bare `pr/<name>` branch
//     resolves the PR by tip match. The author-based mapping needs a logged-in
//     user; after logout only the tip comparison can link the branch to the
//     published PR.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn merge_without_id_resolves_bare_branch_by_tip_when_logged_out() -> Result<()> {
    let harness = Harness::builder(
        env!("CARGO_BIN_EXE_ngit"),
        env!("CARGO_BIN_EXE_git-remote-nostr"),
    )
    .with_relay("default")
    .with_grasp_server("repo")
    .build()
    .await?;

    let (_publisher, published) = harness
        .publish_repo(PublishRepoOpts {
            display_name: Some("merge maintainer".into()),
            identifier: Some("merge-tip-logged-out-repo".into()),
            ..Default::default()
        })
        .await?;

    // The PR author clones, logs in and submits a PR via a plain pushed
    // `pr/<name>` branch (no shorthand), as in test 6.
    let author = harness
        .clone_published_repo(
            &published,
            CloneLogin::AsContributor {
                display_name: "soon logged out contributor".into(),
            },
        )
        .await?;

    let branch = "pr/tip-match-feature";
    author
        .git_ok(
            ["checkout", "-b", branch],
            "git checkout -b pr/tip-match-feature",
        )
        .await?;
    std::fs::write(author.dir().join("feat.md"), "some content\n").context("write feat.md")?;
    author.git_ok(["add", "feat.md"], "git add feat.md").await?;
    author
        .git_ok(
            ["commit", "-m", "add feat.md", "--no-gpg-sign"],
            "git commit feat.md",
        )
        .await?;
    let pr_tip = rev_parse(&author, "HEAD").await?;
    author
        .nostr_push(["-u", "origin", branch])
        .await
        .context("git push -u origin pr/tip-match-feature (PR creation) failed")?;
    assert_eq!(current_branch(&author).await?, branch);

    // Log out so the author-based mapping has no user to match against.
    let out = author
        .ngit(["account", "logout"])
        .output()
        .await
        .context("failed to spawn ngit account logout")?;
    anyhow::ensure!(
        out.status.success(),
        "ngit account logout exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    // Precondition for the scenario: without this the author-based arm would
    // still resolve the PR and the tip-match fallback would go unexercised.
    let out = author
        .git(["config", "--get", "nostr.npub"])
        .output()
        .await
        .context("failed to spawn git config --get nostr.npub")?;
    anyhow::ensure!(
        !out.status.success(),
        "nostr.npub should be unset after logout",
    );

    // Merge with no id — must resolve the PR by matching the branch tip.
    let out = run_merge(&author, &[]).await?;
    anyhow::ensure!(
        out.status.success(),
        "ngit merge (no id) logged out on own bare pr/ branch exited {:?}\nstdout: {}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    assert_eq!(
        current_branch(&author).await?,
        "main",
        "should be left on the default branch after merge",
    );
    assert_eq!(
        parent_count(&author, "main").await?,
        2,
        "no-ff merge should produce a 2-parent merge commit",
    );
    let merged_in = rev_parse(&author, "main^2").await?;
    assert_eq!(
        merged_in, pr_tip,
        "the merge commit's second parent should be the pushed PR tip",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// 11. two open PRs sharing the same branch name AND the same tip commit cannot
//     be told apart by the tip-match fallback: merge without an id still bails
//     asking for an explicit event-id, and main is untouched.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn merge_without_id_ambiguous_name_and_tip_still_errors() -> Result<()> {
    let harness = Harness::builder(
        env!("CARGO_BIN_EXE_ngit"),
        env!("CARGO_BIN_EXE_git-remote-nostr"),
    )
    .with_relay("default")
    .with_grasp_server("repo")
    .build()
    .await?;

    let (publisher, published) = harness
        .publish_repo(PublishRepoOpts {
            display_name: Some("merge maintainer".into()),
            identifier: Some("merge-ambiguous-tip-repo".into()),
            ..Default::default()
        })
        .await?;

    // Contributor A submits `pr/dup` the plain-git way.
    let contributor_a = harness
        .clone_published_repo(
            &published,
            CloneLogin::AsContributor {
                display_name: "contributor a".into(),
            },
        )
        .await?;
    contributor_a
        .git_ok(["checkout", "-b", "pr/dup"], "git checkout -b pr/dup (a)")
        .await?;
    std::fs::write(contributor_a.dir().join("dup.md"), "duplicated work\n")
        .context("write dup.md")?;
    contributor_a
        .git_ok(["add", "dup.md"], "git add dup.md")
        .await?;
    contributor_a
        .git_ok(
            ["commit", "-m", "add dup.md", "--no-gpg-sign"],
            "git commit dup.md",
        )
        .await?;
    let shared_tip = rev_parse(&contributor_a, "HEAD").await?;
    contributor_a
        .nostr_push(["-u", "origin", "pr/dup"])
        .await
        .context("git push -u origin pr/dup (contributor a) failed")?;

    // Contributor B clones (contributor A's PR tip arrives via its advertised
    // canonical `pr/dup(<short>)` ref), recreates the *same* bare branch at
    // the *same* commit and pushes it. B did not author A's PR, so the push
    // maps to no existing proposal and publishes a second PR root with an
    // identical branch name and tip.
    let contributor_b = harness
        .clone_published_repo(
            &published,
            CloneLogin::AsContributor {
                display_name: "contributor b".into(),
            },
        )
        .await?;
    contributor_b
        .git_ok(
            ["config", "--local", "nostr.auto-pr-branches", "true"],
            "enable automatic PR branches for duplicate-tip setup",
        )
        .await?;
    contributor_b
        .git_ok(["fetch", "origin"], "fetch contributor A's PR tip")
        .await?;
    contributor_b
        .git_ok(
            ["checkout", "-b", "pr/dup", &shared_tip],
            "git checkout -b pr/dup at shared tip (b)",
        )
        .await?;
    contributor_b
        .nostr_push(["-u", "origin", "pr/dup"])
        .await
        .context("git push -u origin pr/dup (contributor b) failed")?;

    // Precondition: two distinct PR roots now exist for the repo.
    let pr_roots = harness
        .grasp("repo")
        .events(nostr::prelude::Filter::new().kind(ngit::git_events::KIND_PULL_REQUEST))
        .await?;
    anyhow::ensure!(
        pr_roots.len() == 2,
        "expected two same-named same-tip PR roots on the relay, got {}",
        pr_roots.len(),
    );

    // The maintainer checks out the shared tip under the bare name and asks
    // for a merge with no id.
    publisher
        .git_ok(
            ["config", "--local", "nostr.auto-pr-branches", "true"],
            "enable automatic PR branches for ambiguous-tip setup",
        )
        .await?;
    publisher
        .git_ok(["fetch", "origin"], "git fetch origin")
        .await?;
    publisher
        .git_ok(
            ["checkout", "-b", "pr/dup", &shared_tip],
            "git checkout -b pr/dup at shared tip (maintainer)",
        )
        .await?;
    let main_before = rev_parse(&publisher, "main").await?;

    let out = run_merge(&publisher, &[]).await?;
    assert!(
        !out.status.success(),
        "ngit merge must bail when two open PRs share the branch name and tip\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    // Explicit error-message contract: the failure names the branch and the
    // remedy (specify an event-id).
    let stderr = String::from_utf8_lossy(&out.stderr).to_lowercase();
    assert!(
        stderr.contains("pr/dup") && stderr.contains("event-id"),
        "error should name the branch and the event-id remedy, got:\n{stderr}",
    );

    // main must not have advanced and no merge is in progress.
    assert_eq!(
        rev_parse(&publisher, "main").await?,
        main_before,
        "main must not advance when the merge is refused",
    );

    Ok(())
}