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
//! Coverage for `git push --force` on top of an existing **patch-kind**
//! proposal after amending the tip commit — including a *second* force push
//! that produces a revision of a revision.
//!
//! ## Scenario
//!
//! Extends [`super::patch_update`]'s fast-forward push with two
//! amend-and-force-push steps.  A contributor publishes a two-commit patch
//! series via `ngit send --force-patch`; the maintainer then clones, checks
//! out the proposal branch, adds a commit as a fast-forward push, amends and
//! force-pushes (revision #1), then amends again and force-pushes a second
//! time (revision #2).
//!
//! Each force push triggers a **revision** of the patch series:
//! `generate_cover_letter_and_patch_events` is called (via
//! `generate_patches_or_pr_event_or_pr_updates`) with all commits ahead of
//! `main` and with `root_proposal = Some(original_root_patch)` as the
//! revision anchor.  Each revision produces three new `Kind::GitPatch`
//! events.
//!
//! ## Revision structure (no cover letter)
//!
//! With no cover letter the first commit's patch acts as the revision root.
//! For the 3-commit series [c1, c2, cN] re-published by a force push:
//!
//! * **c1 patch** (revision root) — carries:
//!   - `["t", "root"]`
//!   - `["t", "root-revision"]` (alias `"revision-root"` also accepted)
//!   - `["e", <original_root_patch_id>, _, "reply"]`
//! * **c2 patch** — carries:
//!   - `["e", <c1_patch_id>, _, "root"]`
//!   - `["e", <c1_patch_id>, _, "reply"]` (c1 is both thread root and direct
//!     parent)
//! * **cN patch** (amended tip) — carries:
//!   - `["e", <c1_patch_id>, _, "root"]`
//!   - `["e", <c2_patch_id>, _, "reply"]`
//!
//! ## Where does the *second* revision's `e reply` point?
//!
//! On every force push the remote helper calls
//! `find_proposal_and_patches_by_branch_name` (lib/utils.rs:271), which
//! searches the map returned by `get_all_proposals`.  That map *filters out*
//! events for which `event_is_revision_root` is true (lib/utils.rs:208), so
//! it can only ever return the **original** proposal root.  That event
//! becomes `effective_root` and is passed all the way down as
//! `root_proposal_id` to `generate_patch_event` (lib/git_events.rs:252),
//! which writes its id into the new revision root's `e reply` tag.
//!
//! Therefore the second revision root should reply to the *original* root
//! patch, **not** to the first revision root.  `revision_2_root_replies_to_
//! original_root` asserts this empirically.
//!
//! ## Assertions (one `#[rstest]` per)
//!
//! - `nine_patch_events_total` — 2 original + 1 first push + 3 revision #1 + 3
//!   revision #2 = 9
//! - `zero_pr_events` — no `KIND_PULL_REQUEST` emitted
//! - `zero_pr_update_events` — no `KIND_PULL_REQUEST_UPDATE` emitted
//! - `revision_root_has_t_root` — revision #1 root carries `["t", "root"]`
//! - `revision_root_has_t_revision_root` — carries `["t", "root-revision"]`
//! - `revision_root_replies_to_original_root` — `["e", <original_id>, _,
//!   "reply"]`
//! - `tip_patch_root_is_revision_root` — `["e", <revision_root_id>, _, "root"]`
//! - `tip_patch_replies_to_second_patch` — `["e", <revision_patch_2_id>, _,
//!   "reply"]`
//! - `revision_2_root_replies_to_original_root` — the **second** revision
//!   root's `e reply` points at the original root patch, *not* the first
//!   revision root
//! - `revision_2_tip_root_is_revision_2_root` — the second revision tip threads
//!   under the second revision root
//! - `fresh_clone_exactly_one_pr_branch` — a fresh `CloneLogin::None` clone
//!   advertises exactly one branch-shaped proposal ref of the form
//!   `(refs/heads/)?pr/<branch>(<shorthand>)`.  Two would mean `list.rs` is
//!   double-advertising the proposal (e.g. by treating a revision root as its
//!   own independent proposal); zero would mean `list.rs` lost the proposal.

use std::{collections::BTreeMap, sync::Arc};

use anyhow::{Context, Result, anyhow};
use nostr_sdk::prelude::*;
use rstest::*;
use test_harness::{
    CloneLogin, Harness, KIND_PULL_REQUEST, KIND_PULL_REQUEST_UPDATE, PublishPatchSeriesOpts,
    PublishRepoOpts, event_branch_name_tag, tag_value, tag_values_multiple,
};
use tokio::sync::OnceCell;

/// Identifier for this test repo — distinct from every other `git_push_pr`
/// scenario so the shared vanilla relay's REQ surface stays uncontaminated.
const IDENTIFIER: &str = "git-push-pr-patch-update-force";

/// Find the completed push's immediately-queryable patch events and assert
/// that they include `commit_oid`.
async fn find_patch_events(
    harness: &Harness,
    commit_oid: &str,
    minimum_event_count: usize,
) -> Result<Vec<Event>> {
    let events = harness
        .grasp("repo")
        .events(Filter::new().kind(Kind::GitPatch))
        .await?;
    anyhow::ensure!(
        events.len() >= minimum_event_count
            && events
                .iter()
                .any(|event| tag_value(event, "commit").as_deref() == Some(commit_oid)),
        "successful push returned before at least {minimum_event_count} GitPatch events, including \
         commit={commit_oid}, were queryable; observed {} event(s): {:?}",
        events.len(),
        events
            .iter()
            .map(|event| {
                format!(
                    "id={} commit={:?} root={:?}",
                    event.id,
                    tag_value(event, "commit"),
                    event.tags.iter().find_map(|tag| {
                        let values = tag.as_slice();
                        (values.first().map(String::as_str) == Some("e"))
                            .then(|| values.get(1).cloned())
                            .flatten()
                    }),
                )
            })
            .collect::<Vec<_>>(),
    );
    Ok(events)
}

// ---------------------------------------------------------------------------
// Snapshot
// ---------------------------------------------------------------------------

/// Everything observable after the publish → first-push → amend →
/// force-push → amend → force-push arrangement, captured once per test
/// binary via [`SNAPSHOT`] and shared read-only across all `#[rstest]`
/// cases.
struct Snapshot {
    /// All `Kind::GitPatch` events on the GRASP after both force pushes.
    /// Expected count: 9 (2 original + 1 first push + 3 revision #1 +
    /// 3 revision #2).
    all_patch_events: Vec<Event>,

    /// Revision-root patch from the **first** force push — the patch for
    /// `commits[0]` (t3.md).  Carries `["t", "root"]`,
    /// `["t", "root-revision"]`, and an
    /// `["e", <original_root_id>, _, "reply"]` tag.
    revision_root: Event,

    /// Second patch in the **first** force-push revision — covers
    /// `commits[1]` (t4.md), authored by the maintainer.  Disambiguated
    /// from the original contributor patch for the same commit OID by
    /// author pubkey.
    revision_patch_2: Event,

    /// Tip patch in the **first** force-push revision — covers the
    /// first-amend commit OID.
    revision_tip: Event,

    /// Revision-root patch from the **second** force push.  Identified
    /// as the `Kind::GitPatch` event carrying `["t", "root-revision"]`
    /// (or alias `"revision-root"`) with the *latest* `created_at`.
    revision_2_root: Event,

    /// Tip patch in the **second** force-push revision — covers the
    /// second-amend commit OID.  Unique among all patch events on the
    /// GRASP because the OID is new.
    revision_2_tip: Event,

    /// Event ID of the original series root patch published by
    /// [`Harness::publish_patch_series`] (the patch carrying the
    /// `branch-name` tag).  Both revision roots' `["e", _, _, "reply"]`
    /// tags should equal this — never the first revision root's id.
    original_root_patch_id: EventId,

    /// Count of `KIND_PULL_REQUEST` events on the GRASP.  Must be 0 — force
    /// pushing on top of a patch-kind root must not produce a PR.
    pr_count: usize,

    /// Count of `KIND_PULL_REQUEST_UPDATE` events on the GRASP.  Must be 0 —
    /// a PR-update event is only valid when the root proposal is PR-kind.
    pr_update_count: usize,

    /// Branch name of the original series — used to recognise branch-shaped
    /// proposal advertisements in [`Self::nostr_clone_ls_refs`].
    original_branch_name: String,

    /// Refs advertised by a fresh `git ls-remote origin` against the
    /// `nostr://` URL from a third clone with no nostr login
    /// (`CloneLogin::None`).  Each entry is `(ref_name, oid)`.
    ///
    /// `list.rs` advertises proposal branches as
    /// `(refs/heads/)?pr/<branch>(<shorthand>)` where the 8-char shorthand
    /// is derived from `event_to_cover_letter(proposal).event_id` — and
    /// `proposal` is always the original patch root because revision-root
    /// events are filtered out by `get_open_or_draft_proposals` at
    /// `utils.rs:144-149`.  After two force-push revisions there must still
    /// be exactly one such advertisement.
    nostr_clone_ls_refs: BTreeMap<String, String>,
}

static SNAPSHOT: OnceCell<Arc<Snapshot>> = OnceCell::const_new();

/// rstest fixture: run [`capture_snapshot`] exactly once per test binary via
/// [`SNAPSHOT`] and hand each case a cheap `Arc` clone.
#[fixture]
async fn snapshot() -> Arc<Snapshot> {
    SNAPSHOT
        .get_or_init(|| async {
            Arc::new(
                capture_snapshot()
                    .await
                    .expect("git_push_pr::patch_update_force fixture: capture_snapshot failed"),
            )
        })
        .await
        .clone()
}

// ---------------------------------------------------------------------------
// Arrange + act + capture
// ---------------------------------------------------------------------------

async fn capture_snapshot() -> Result<Snapshot> {
    // --- 1. Harness ----------------------------------------------------------
    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?;

    // --- 2. Maintainer publishes the repo ------------------------------------
    let (_publisher, published) = harness
        .publish_repo(PublishRepoOpts {
            display_name: Some("patch-update-force maintainer".into()),
            identifier: Some(IDENTIFIER.into()),
            ..Default::default()
        })
        .await?;

    let maintainer_keys = Keys::parse(&published.maintainer_nsec)
        .context("published.maintainer_nsec is not a valid key")?;
    let maintainer_pubkey = maintainer_keys.public_key();

    // --- 3. Contributor publishes a patch-series proposal --------------------
    //
    // Defaults: branch = "feature-1", two commits (t3.md, t4.md), no cover
    // letter.  `--force-patch` is set inside the helper, decoupling the test
    // from the default-kind heuristic in `ngit send`.
    let series = harness
        .publish_patch_series(&published, PublishPatchSeriesOpts::default())
        .await?;

    // --- 4. Identify the original series root --------------------------------
    //
    // The root is the first patch in the series — the only one whose
    // `branch-name` tag is set (added by `generate_patch_event` when
    // `events.is_empty()` in the per-commit loop).  Its event ID becomes
    // the `in_reply_to` anchor for the force-push revision.
    let original_root_patch = series
        .patch_events
        .iter()
        .find(|e| event_branch_name_tag(e).as_deref() == Some(series.branch_name.as_str()))
        .with_context(|| {
            format!(
                "no patch event with branch-name={:?} in publish_patch_series output; \
                 has the harness changed how it tags the series root?",
                series.branch_name,
            )
        })?;
    let original_root_patch_id = original_root_patch.id;
    let shorthand = &original_root_patch.id.to_hex()[..8];
    let remote_branch = format!("pr/{}({})", series.branch_name, shorthand);

    // --- 5. Maintainer clones ------------------------------------------------
    //
    // `AsMaintainer` reuses `published.maintainer_nsec` — the maintainer has
    // push permission on any proposal branch (push.rs:481-484).
    let maintainer_clone = harness
        .clone_published_repo(&published, CloneLogin::AsMaintainer)
        .await?;
    maintainer_clone
        .git_ok(
            ["config", "--local", "nostr.auto-pr-branches", "true"],
            "enable automatic PR branches for raw remote-ref checkout",
        )
        .await?;
    maintainer_clone
        .git_ok(["fetch", "origin"], "fetch automatic PR branches")
        .await?;

    // Verify the patch branch is advertised before attempting checkout.
    let snap = maintainer_clone
        .snapshot()
        .context("snapshotting maintainer clone before checkout")?;
    let remote_ref = format!("refs/remotes/origin/{remote_branch}");
    snap.refs.get(&remote_ref).with_context(|| {
        format!(
            "{remote_ref} missing from maintainer clone after `git clone` — \
             list.rs no longer advertises patch proposals as pr/<branch>(<shorthand>) \
             for non-author viewers?  Available refs: {:?}",
            snap.refs.keys().collect::<Vec<_>>(),
        )
    })?;

    // --- 6. Checkout proposal branch and commit ------------------------------
    maintainer_clone
        .git_ok(
            ["checkout", &remote_branch],
            &format!("git checkout {remote_branch}"),
        )
        .await?;

    std::fs::write(
        maintainer_clone.dir().join("maintainer-update.md"),
        "maintainer follow-up\n",
    )
    .context("failed to write maintainer-update.md")?;
    maintainer_clone
        .git_ok(
            ["add", "maintainer-update.md"],
            "git add maintainer-update.md",
        )
        .await?;

    maintainer_clone
        .git_ok(
            ["commit", "-m", "follow-up on patch series", "--no-gpg-sign"],
            "git commit maintainer-update.md",
        )
        .await?;

    let first_push_tip_oid = maintainer_clone
        .rev_parse("HEAD")
        .await
        .context("rev-parse HEAD before first push")?;

    // --- 7. First push (fast-forward) ----------------------------------------
    //
    // Adds one `Kind::GitPatch` event covering the new commit.
    maintainer_clone
        .nostr_push(["origin", &remote_branch])
        .await
        .context("nostr_push of maintainer follow-up (first push) failed")?;
    find_patch_events(&harness, &first_push_tip_oid, 3).await?;

    // --- 8. Amend the tip commit ---------------------------------------------
    //
    // Write new content and amend so that the commit OID changes.  The amend
    // is local-only — no push — so it creates the non-fast-forward divergence
    // that requires `-f` on the next push.
    std::fs::write(
        maintainer_clone.dir().join("maintainer-update.md"),
        "maintainer follow-up (amended)\n",
    )
    .context("failed to write amended maintainer-update.md")?;
    maintainer_clone
        .git_ok(
            ["add", "maintainer-update.md"],
            "git add maintainer-update.md (amend step)",
        )
        .await?;
    maintainer_clone
        .git_ok(
            [
                "commit",
                "--amend",
                "-m",
                "amended follow-up on patch series",
                "--no-gpg-sign",
            ],
            "git commit --amend",
        )
        .await?;

    let amended_tip_oid = maintainer_clone
        .rev_parse("HEAD")
        .await
        .context("rev-parse HEAD after amend")?;

    // --- 9. Force push (revision #1) -----------------------------------------
    //
    // The `-f` flag causes git to prefix the
    // refspec with `+`, which `push.rs:485` detects as a force push.  The
    // remote helper resolves all commits ahead of `main` (3 commits: the two
    // original contributor commits plus the amended maintainer commit) and
    // calls `generate_cover_letter_and_patch_events` with
    // `root_proposal = Some(original_root_patch)`, producing 3 new
    // `Kind::GitPatch` events as a revision.  Total patch events on GRASP: 6.
    maintainer_clone
        .nostr_push(["-f", "origin", &remote_branch])
        .await
        .context("nostr_push -f (force push after amend) failed")?;
    find_patch_events(&harness, &amended_tip_oid, 6).await?;

    // --- 10. Amend the tip commit again --------------------------------------
    //
    // Second amend — produces another non-fast-forward divergence requiring
    // a second force push.  The new commit OID is distinct from the first
    // amend OID, so the resulting revision tip patch is identifiable by its
    // `commit` tag alone.
    std::fs::write(
        maintainer_clone.dir().join("maintainer-update.md"),
        "maintainer follow-up (amended twice)\n",
    )
    .context("failed to write twice-amended maintainer-update.md")?;
    maintainer_clone
        .git_ok(
            ["add", "maintainer-update.md"],
            "git add maintainer-update.md (second amend step)",
        )
        .await?;
    maintainer_clone
        .git_ok(
            [
                "commit",
                "--amend",
                "-m",
                "twice-amended follow-up on patch series",
                "--no-gpg-sign",
            ],
            "git commit --amend (second)",
        )
        .await?;

    let amended_tip_2_oid = maintainer_clone
        .rev_parse("HEAD")
        .await
        .context("rev-parse HEAD after second amend")?;
    if amended_tip_2_oid == amended_tip_oid {
        return Err(anyhow!(
            "second amend produced the same commit OID as the first amend \
             ({amended_tip_2_oid}); the second force push will be a no-op and \
             the test will not exercise the intended path",
        ));
    }

    // --- 11. Force push (revision #2) ----------------------------------------
    //
    // Same code path as step 9, but now there is *already* a revision on the
    // relay.  The question this step answers: does the new revision root
    // reply to the *original* root patch, or to the first revision root?
    //
    // Prediction (from reading lib/utils.rs:208 + push.rs:472-502): the
    // original root.  `get_all_proposals` filters out revision roots, so
    // `find_proposal_and_patches_by_branch_name` can only return the
    // original.  Asserted empirically by
    // `revision_2_root_replies_to_original_root` below.
    //
    // Adds 3 more `Kind::GitPatch` events.  Total on GRASP: 9.
    maintainer_clone
        .nostr_push(["-f", "origin", &remote_branch])
        .await
        .context("nostr_push -f (second force push after second amend) failed")?;

    // --- 12. Query GRASP state -----------------------------------------------
    let all_patch_events = find_patch_events(&harness, &amended_tip_2_oid, 9).await?;

    let pr_count = harness
        .grasp("repo")
        .events(Filter::new().kind(KIND_PULL_REQUEST))
        .await?
        .len();

    let pr_update_count = harness
        .grasp("repo")
        .events(Filter::new().kind(KIND_PULL_REQUEST_UPDATE))
        .await?
        .len();

    // --- 13. Identify the two revision roots ---------------------------------
    //
    // Both force pushes produce a revision root carrying
    // `t=root-revision` (or alias `revision-root`).  Disambiguate by
    // `created_at`: earlier = revision #1, later = revision #2.  The
    // Event ordering deterministically distinguishes the two revisions.
    let mut revision_roots: Vec<Event> = all_patch_events
        .iter()
        .filter(|e| {
            tag_values_multiple(e, "t")
                .iter()
                .any(|v| v == "root-revision" || v == "revision-root")
        })
        .cloned()
        .collect();
    revision_roots.sort_by_key(|e| e.created_at);
    if revision_roots.len() != 2 {
        return Err(anyhow!(
            "expected exactly 2 Kind::GitPatch events on GRASP carrying \
             t={{root-revision,revision-root}} (one per force push); got {}. \
             all {} patch event ids: {:?}",
            revision_roots.len(),
            all_patch_events.len(),
            all_patch_events
                .iter()
                .map(|e| e.id.to_hex())
                .collect::<Vec<_>>(),
        ));
    }
    let revision_2_root = revision_roots.pop().expect("len == 2 checked above");
    let revision_root = revision_roots.pop().expect("len == 2 checked above");
    if revision_root.id == revision_2_root.id {
        return Err(anyhow!(
            "the two revision roots have identical event ids ({}); \
             the second force push appears to have re-published the first \
             revision root verbatim, defeating this test's purpose",
            revision_root.id.to_hex(),
        ));
    }

    // --- 14. Identify the revision-series mid + tip patches ------------------

    // (a) Intermediate patch in revision #1 — covers `commits[1]` (t4.md),
    //     authored by the maintainer.  The original series also has a patch
    //     for this commit OID (authored by the contributor), so disambiguate
    //     by author and (implicitly) by created_at via the revision #1
    //     window.  Here we just pick the earlier maintainer-authored patch
    //     for `commits[1]`; the second force push will have published a
    //     later one which we don't bind to a variable.
    let second_commit_oid = series
        .commits
        .get(1)
        .cloned()
        .context("series.commits has fewer than 2 entries; expected at least 2")?;
    let mut maintainer_patches_for_c2: Vec<Event> = all_patch_events
        .iter()
        .filter(|e| {
            e.pubkey == maintainer_pubkey
                && tag_value(e, "commit").as_deref() == Some(second_commit_oid.as_str())
        })
        .cloned()
        .collect();
    maintainer_patches_for_c2.sort_by_key(|e| e.created_at);
    let revision_patch_2 = maintainer_patches_for_c2.first().cloned().ok_or_else(|| {
        anyhow!(
            "no Kind::GitPatch event authored by maintainer ({}) with \
             commit tag = {second_commit_oid} found on GRASP after force push",
            maintainer_pubkey.to_hex(),
        )
    })?;

    // (b) Tip patch from revision #1 — covers the first-amend commit OID,
    //     which appears in exactly one patch event on the GRASP (the
    //     pre-amend OID was never re-published).
    let revision_tip = all_patch_events
        .iter()
        .find(|e| tag_value(e, "commit").as_deref() == Some(amended_tip_oid.as_str()))
        .cloned()
        .ok_or_else(|| {
            anyhow!(
                "no Kind::GitPatch event with commit tag = {amended_tip_oid} \
                 found on GRASP after force push",
            )
        })?;

    // (c) Tip patch from revision #2 — covers the second-amend commit OID,
    //     also unique among all events on the GRASP.
    let revision_2_tip = all_patch_events
        .iter()
        .find(|e| tag_value(e, "commit").as_deref() == Some(amended_tip_2_oid.as_str()))
        .cloned()
        .ok_or_else(|| {
            anyhow!(
                "no Kind::GitPatch event with commit tag = {amended_tip_2_oid} \
                 found on GRASP after second force push",
            )
        })?;

    // --- 15. Fresh nostr-URL clone: run `git ls-remote` ----------------------
    //
    // A third clone with no logged-in nostr identity (`CloneLogin::None`)
    // exercises `list.rs` end-to-end against the now-twice-revised patch
    // proposal.  We assert downstream that exactly one branch-shaped
    // proposal advertisement is exposed — even though there are three
    // patch-series roots on the GRASP (original + two revision roots),
    // revision-root events are filtered out by `utils.rs:144-149` so the
    // only `proposal` `list.rs` sees is the original patch root.
    let new_clone = harness
        .clone_published_repo(&published, CloneLogin::None)
        .await?;
    new_clone
        .git_ok(
            ["config", "--local", "nostr.auto-pr-branches", "true"],
            "enable automatic PR branches for ls-remote compatibility check",
        )
        .await?;
    let ls_out = new_clone
        .git(["ls-remote", "origin"])
        .output()
        .await
        .context("failed to spawn git ls-remote origin on fresh clone")?;
    anyhow::ensure!(
        ls_out.status.success(),
        "fresh-clone `git ls-remote origin` exited {:?}\nstdout: {}\nstderr: {}",
        ls_out.status,
        String::from_utf8_lossy(&ls_out.stdout),
        String::from_utf8_lossy(&ls_out.stderr),
    );
    let ls_stdout = String::from_utf8(ls_out.stdout)
        .context("fresh-clone `git ls-remote origin` stdout is not UTF-8")?;
    let nostr_clone_ls_refs: BTreeMap<String, String> = ls_stdout
        .lines()
        .filter(|l| !l.is_empty() && !l.starts_with("ref: "))
        .filter_map(|l| l.split_once('\t'))
        .map(|(oid, name)| (name.to_string(), oid.to_string()))
        .collect();

    Ok(Snapshot {
        all_patch_events,
        revision_root,
        revision_patch_2,
        revision_tip,
        revision_2_root,
        revision_2_tip,
        original_root_patch_id,
        pr_count,
        pr_update_count,
        original_branch_name: series.branch_name.clone(),
        nostr_clone_ls_refs,
    })
}

// ---------------------------------------------------------------------------
// Assertions — one #[rstest] per property
// ---------------------------------------------------------------------------

/// Exactly 9 `Kind::GitPatch` events on the GRASP: 2 from
/// `publish_patch_series`, 1 from the first (FF) push, 3 from the first
/// force-push revision, and 3 from the second force-push revision.
///
/// A count of 8 means one of the force pushes revised only the changed
/// commit rather than re-publishing the full series.  A count > 9 means
/// spurious duplicates.
#[rstest]
#[tokio::test]
async fn nine_patch_events_total(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    assert_eq!(
        s.all_patch_events.len(),
        9,
        "expected exactly 9 Kind::GitPatch events on GRASP \
         (2 original + 1 first push + 3 revision #1 + 3 revision #2); \
         got {} (event ids: {:?})",
        s.all_patch_events.len(),
        s.all_patch_events
            .iter()
            .map(|e| e.id.to_hex())
            .collect::<Vec<_>>(),
    );
    Ok(())
}

/// Zero `KIND_PULL_REQUEST` events — force pushing on top of a patch-kind
/// root must not produce a PR.
#[rstest]
#[tokio::test]
async fn zero_pr_events(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    assert_eq!(
        s.pr_count, 0,
        "expected zero KIND_PULL_REQUEST events on GRASP after force pushing on top \
         of a patch-kind proposal; got {}",
        s.pr_count,
    );
    Ok(())
}

/// Zero `KIND_PULL_REQUEST_UPDATE` events — a PR-update is only valid when
/// the root proposal is itself PR-kind.
#[rstest]
#[tokio::test]
async fn zero_pr_update_events(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    assert_eq!(
        s.pr_update_count, 0,
        "expected zero KIND_PULL_REQUEST_UPDATE events on GRASP; got {}",
        s.pr_update_count,
    );
    Ok(())
}

/// Revision root carries `["t", "root"]` — it is a new proposal root from
/// the threading perspective, even though it also carries a back-reference
/// via `revision-root`.
#[rstest]
#[tokio::test]
async fn revision_root_has_t_root(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    assert!(
        tag_values_multiple(&s.revision_root, "t")
            .iter()
            .any(|v| v == "root"),
        "revision root should carry `t root`; t tags: {:?}",
        tag_values_multiple(&s.revision_root, "t"),
    );
    Ok(())
}

/// Revision root carries `["t", "root-revision"]` or the alias
/// `["t", "revision-root"]` — the marker downstream clients use to
/// distinguish revisions from first-time proposals.
#[rstest]
#[tokio::test]
async fn revision_root_has_t_revision_root(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    let t_values = tag_values_multiple(&s.revision_root, "t");
    assert!(
        t_values
            .iter()
            .any(|v| v == "root-revision" || v == "revision-root"),
        "revision root should carry `t root-revision` (or alias `revision-root`); \
         t tags: {t_values:?}",
    );
    Ok(())
}

/// Revision root carries a 4-slot `["e", <original_root_patch_id>, _, "reply"]`
/// tag linking this revision back to the original proposal root.
#[rstest]
#[tokio::test]
async fn revision_root_replies_to_original_root(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    let reply_e = s
        .revision_root
        .tags
        .iter()
        .find(|t| {
            let v = t.as_slice();
            v.first().map(String::as_str) == Some("e")
                && v.len() == 4
                && v.get(3).map(String::as_str) == Some("reply")
        })
        .ok_or_else(|| {
            anyhow!(
                "revision root missing 4-slot `e ... reply` tag; \
                 all tags: {:?}",
                s.revision_root.tags,
            )
        })?;
    assert_eq!(
        reply_e.as_slice().get(1).map(String::as_str),
        Some(s.original_root_patch_id.to_hex().as_str()),
        "revision root's `e reply` should point at the original series root; \
         got {:?}, want {:?}",
        reply_e.as_slice().get(1),
        s.original_root_patch_id.to_hex(),
    );
    Ok(())
}

/// Tip patch carries a 4-slot `["e", <revision_root_id>, _, "root"]` tag —
/// the thread root for the entire revision series is the revision root patch,
/// not the original proposal root.
#[rstest]
#[tokio::test]
async fn tip_patch_root_is_revision_root(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    let root_e = s
        .revision_tip
        .tags
        .iter()
        .find(|t| {
            let v = t.as_slice();
            v.first().map(String::as_str) == Some("e")
                && v.len() == 4
                && v.get(3).map(String::as_str) == Some("root")
        })
        .ok_or_else(|| {
            anyhow!(
                "revision tip patch missing 4-slot `e ... root` tag; \
                 all tags: {:?}",
                s.revision_tip.tags,
            )
        })?;
    assert_eq!(
        root_e.as_slice().get(1).map(String::as_str),
        Some(s.revision_root.id.to_hex().as_str()),
        "revision tip patch's `e root` should point at the revision root; \
         got {:?}, want {:?}",
        root_e.as_slice().get(1),
        s.revision_root.id.to_hex(),
    );
    Ok(())
}

/// Tip patch carries a 4-slot `["e", <revision_patch_2_id>, _, "reply"]`
/// tag — the immediate predecessor in the revision series is the second
/// patch, not the revision root.
#[rstest]
#[tokio::test]
async fn tip_patch_replies_to_second_patch(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    let reply_e = s
        .revision_tip
        .tags
        .iter()
        .find(|t| {
            let v = t.as_slice();
            v.first().map(String::as_str) == Some("e")
                && v.len() == 4
                && v.get(3).map(String::as_str) == Some("reply")
        })
        .ok_or_else(|| {
            anyhow!(
                "revision tip patch missing 4-slot `e ... reply` tag; \
                 all tags: {:?}",
                s.revision_tip.tags,
            )
        })?;
    assert_eq!(
        reply_e.as_slice().get(1).map(String::as_str),
        Some(s.revision_patch_2.id.to_hex().as_str()),
        "revision tip patch's `e reply` should point at the second patch in the \
         revision series (not the revision root); got {:?}, want {:?}",
        reply_e.as_slice().get(1),
        s.revision_patch_2.id.to_hex(),
    );
    Ok(())
}

/// The **second** revision root's 4-slot `["e", _, _, "reply"]` tag points
/// at the **original** root patch — *not* at the first revision root.
///
/// Why: `get_all_proposals` (lib/utils.rs:208) filters events for which
/// `event_is_revision_root` is true.  The map it builds — keyed by
/// proposal id — therefore never contains a revision root.  When the
/// second force push calls `find_proposal_and_patches_by_branch_name`
/// (push.rs:472) the only candidate that can match the branch is the
/// original proposal root, so that event becomes `effective_root` and
/// flows down to `generate_patch_event` as `root_proposal_id`
/// (git_events.rs:252), which writes its id into the new revision root's
/// `e reply` tag.
///
/// If this assertion ever fails with the tag pointing at
/// `s.revision_root.id`, it means the lookup or filter logic has changed
/// to surface revision roots as proposals — at which point this test, the
/// docstring at the top of the module, and the comment block in section
/// 11 (revision #2 force push) of `capture_snapshot` all need revisiting
/// together.
#[rstest]
#[tokio::test]
async fn revision_2_root_replies_to_original_root(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    let reply_e = s
        .revision_2_root
        .tags
        .iter()
        .find(|t| {
            let v = t.as_slice();
            v.first().map(String::as_str) == Some("e")
                && v.len() == 4
                && v.get(3).map(String::as_str) == Some("reply")
        })
        .ok_or_else(|| {
            anyhow!(
                "second revision root missing 4-slot `e ... reply` tag; \
                 all tags: {:?}",
                s.revision_2_root.tags,
            )
        })?;
    let got = reply_e.as_slice().get(1).map(String::as_str);
    let want_original = s.original_root_patch_id.to_hex();
    let other_candidate = s.revision_root.id.to_hex();
    assert_eq!(
        got,
        Some(want_original.as_str()),
        "second revision root's `e reply` should point at the ORIGINAL root \
         patch ({want_original}), not the first revision root \
         ({other_candidate}); got {got:?}.\n\n\
         If got == first-revision-root id, the second force push is anchoring \
         on the latest revision instead of the original proposal — re-check \
         the filter in `get_all_proposals` (lib/utils.rs:208) and the lookup \
         in `find_proposal_and_patches_by_branch_name` (push.rs:472).",
    );
    Ok(())
}

/// The **second** revision tip's 4-slot `["e", _, _, "root"]` tag points
/// at the **second** revision root — i.e. each revision is its own
/// self-contained thread anchored on its own revision root, even though
/// every revision root's `e reply` resolves all the way back to the
/// original proposal.
#[rstest]
#[tokio::test]
async fn revision_2_tip_root_is_revision_2_root(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    let root_e = s
        .revision_2_tip
        .tags
        .iter()
        .find(|t| {
            let v = t.as_slice();
            v.first().map(String::as_str) == Some("e")
                && v.len() == 4
                && v.get(3).map(String::as_str) == Some("root")
        })
        .ok_or_else(|| {
            anyhow!(
                "second revision tip patch missing 4-slot `e ... root` tag; \
                 all tags: {:?}",
                s.revision_2_tip.tags,
            )
        })?;
    assert_eq!(
        root_e.as_slice().get(1).map(String::as_str),
        Some(s.revision_2_root.id.to_hex().as_str()),
        "second revision tip patch's `e root` should point at the second \
         revision root ({}); got {:?}.  If it points at the first revision \
         root ({}) or the original root ({}), the per-revision thread \
         boundary has been broken.",
        s.revision_2_root.id.to_hex(),
        root_e.as_slice().get(1),
        s.revision_root.id.to_hex(),
        s.original_root_patch_id.to_hex(),
    );
    Ok(())
}

// ---------------------------------------------------------------------------
// Fresh-clone `git ls-remote` — proposal branch advertisement
// ---------------------------------------------------------------------------
//
// `list.rs` exposes proposal branches under two namespaces:
//
// * `refs/pr/<branch>(<shorthand>)` — emitted by `get_all_proposals_state` for
//   every proposal regardless of status.
// * `refs/heads/pr/<branch>(<shorthand>)` — emitted by
//   `get_open_and_draft_proposals_state` only for open/draft proposals whose
//   tip commit is locally available.
//
// Either is acceptable for this test; we just want to count
// branch-shaped advertisements with the form `pr/<branch>(<shorthand>)`.

/// Helper: collect every ref whose name ends in `pr/<branch>(<8-hex>)` —
/// the branch-shaped proposal advertisement — from the fresh-clone
/// `ls-remote` map.  Excludes the `refs/pr/<full-event-id>/head`
/// canonical refs (those don't carry the human branch name).
fn branch_shaped_pr_refs<'a>(
    map: &'a std::collections::BTreeMap<String, String>,
    branch: &str,
) -> Vec<(&'a String, &'a String)> {
    let needle_prefix = format!("pr/{branch}(");
    map.iter()
        .filter(|(name, _)| {
            // Trim any leading `refs/heads/` or `refs/` so we match against
            // the suffix `pr/<branch>(<...>)`.
            let suffix = name
                .strip_prefix("refs/heads/")
                .or_else(|| name.strip_prefix("refs/"))
                .unwrap_or(name.as_str());
            suffix.starts_with(&needle_prefix) && suffix.ends_with(')')
        })
        .collect()
}

/// Exactly two branch-shaped proposal advertisements in the fresh clone's
/// `ls-remote` output — one per namespace:
///
/// * `refs/pr/<branch>(<shorthand>)` from `get_all_proposals_state`
/// * `refs/heads/pr/<branch>(<shorthand>)` from
///   `get_open_and_draft_proposals_state`
///
/// Four would mean `list.rs` is double-advertising the proposal — for
/// example, by treating one of the revision roots as its own
/// independent proposal (which would happen if revision-root filtering
/// in `utils.rs:144-149` stopped masking patch-kind revision roots).
/// Zero would mean the proposal disappeared entirely from the
/// catalogue, e.g. because all candidate roots got filtered out.
#[rstest]
#[tokio::test]
async fn fresh_clone_exactly_one_pr_branch(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    let pr_branch_refs = branch_shaped_pr_refs(&s.nostr_clone_ls_refs, &s.original_branch_name);
    assert_eq!(
        pr_branch_refs.len(),
        2,
        "expected exactly two branch-shaped proposal advertisements \
         (one each under `refs/pr/` and `refs/heads/pr/` for `{}`) in the \
         fresh clone after two force-push revisions; got {} \
         (full ls-remote map: {:#?})",
        s.original_branch_name,
        pr_branch_refs.len(),
        s.nostr_clone_ls_refs,
    );
    Ok(())
}