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
//! `ngit init` State A "Fresh" — successor to legacy
//! `tests/legacy/ngit_init.rs::state_a_fresh::*`.
//!
//! State A is the absence of a `nostr.repo` git config: a brand-new repo
//! that has never been associated with a Nostr coordinate.
//! `validate_pre_fetch` (init.rs:472-475) therefore takes the State A
//! short-circuit and runs `validate_fresh` (init.rs:342) before any
//! network round-trip — so error cases here are observable without any
//! relay or grasp interaction having to happen, and the success case is
//! a pure announcement publish.
//!
//! ## Coverage
//!
//! - **Errors** (4 tests, no shared setup — each error is a different `ngit
//!   init` invocation with its own arg shape):
//!   - no configured signer → fails instead of repeatedly attempting an nsec
//!     prompt in non-interactive mode
//!   - `bare_no_flags` → "missing required fields"
//!   - `name_only_missing_server_infra` → "missing --grasp-server"
//!   - `relays_only_missing_name_and_servers` → "missing required fields" (the
//!     "two missing" branch)
//! - **Success — grasp path** (1 captured snapshot, 7 rstest cases asserting on
//!   different tags of the produced kind-30617). Setup runs once per test
//!   binary via [`tokio::sync::OnceCell`]; every case is a read-only assertion
//!   on the captured `Snapshot`. Same discipline as `tests/send_patch.rs` and
//!   `tests/git_push_state/fresh_repo.rs` — see those files' module-level docs
//!   for the rationale.
//! - **Success — self-lead** (1 standalone test —
//!   `lead_maintainer_self_emits_uppercase_m_role_tag`): `ngit init
//!   --lead-maintainer <own npub>` end-to-end — clap flag through
//!   `resolve_fields` to `RepoRef::to_event` — asserting the announcement
//!   carries the publisher as an untimed `M` role tag. The collapse and
//!   `--force` semantics for a non-self lead are pinned by the
//!   `apply_lead_to_maintainers` unit tests in init.rs.
//! - **Success — non-grasp clone path** (1 standalone test —
//!   `vanilla_clone_url_passes_through_to_announcement`): drives `ngit init
//!   --name --additional-clone <vanilla_url> --additional-relay <ws>` against a
//!   harness-managed [`VanillaGitServer`](test_harness::VanillaGitServer),
//!   exercising the `is_grasp_server_clone_url == false` arm of init.rs +
//!   repo_ref.rs. Single test rather than an OnceCell snapshot because the
//!   non-grasp shape has only one tag assertion worth pinning here (the
//!   verbatim clone-URL pass-through) plus a server-liveness probe — sharing
//!   buys nothing.
//! - **Success — pre-existing `origin` on a reachable vanilla git server** (1
//!   standalone test —
//!   `pre_existing_origin_with_tag_promotes_to_nostr_and_state_event_covers_tag`):
//!   sets up an `origin` remote pointing at a harness-managed
//!   [`VanillaGitServer`](test_harness::VanillaGitServer), pushes `main` plus
//!   an annotated tag to it, then runs `ngit init` and checks (a) the `origin`
//!   URL is rewritten to `nostr://`, (b) the first kind-30618 state event
//!   covers the pre-existing tag without the user passing it on the CLI. Plugs
//!   the gap left by legacy `state_d_*` tests, which only used an *unreachable*
//!   origin and never exercised the origin-state-extraction branch in
//!   init.rs:1213-1257.
//!
//! ## Error-message brittleness
//!
//! The error tests assert on `ngit`'s stderr containing a specific
//! substring (e.g. `"missing required fields"`). The harness rules ban
//! *exact*-stdout assertions; substring assertions on a stable error-
//! prefix are tolerated as a regression-catching shortcut for tests
//! whose entire contract *is* "this validation arm fired". The strings
//! are produced by `cli_error` in `src/bin/ngit/sub_commands/init.rs`
//! and have not changed since the legacy tests were written; if init
//! starts wording the messages differently, these tests will fail loudly
//! and the assertions can be updated in the same change.

use std::{sync::Arc, time::Duration};

use anyhow::{Context, Result, bail};
use nostr_sdk::prelude::*;
use rstest::*;
use test_harness::Harness;
use tokio::sync::OnceCell;

const DISPLAY_NAME: &str = "My Project";
/// `ngit init` slugifies `--name` into the `d` tag by replacing spaces
/// with hyphens — `"My Project"` → `"My-Project"`. The producer side
/// lives in `src/bin/ngit/sub_commands/init.rs`'s identifier-derivation
/// logic. Captured here so a regression in either direction (missing
/// slugification, different separator) shows up as a tag mismatch.
const EXPECTED_IDENTIFIER: &str = "My-Project";

// ---------------------------------------------------------------------------
// Errors — one #[tokio::test] each, no shared setup
// ---------------------------------------------------------------------------

#[tokio::test]
async fn no_signer_fails_without_retrying_interactive_login() -> Result<()> {
    let harness = Harness::builder(
        env!("CARGO_BIN_EXE_ngit"),
        env!("CARGO_BIN_EXE_git-remote-nostr"),
    )
    .build()
    .await?;
    let repo = harness.fresh_repo()?;
    let commit = repo
        .git(["commit", "--allow-empty", "-m", "initial commit"])
        .output()
        .await
        .context("failed to create initial commit")?;
    assert!(commit.status.success(), "failed to create initial commit");

    let mut init = repo.ngit(["init"]);
    init.kill_on_drop(true);
    let out = tokio::time::timeout(Duration::from_secs(5), init.output())
        .await
        .context("`ngit init` did not fail promptly without a configured signer")?
        .context("failed to spawn ngit init")?;

    assert!(
        !out.status.success(),
        "expected `ngit init` to fail without a configured signer"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("nostr account required"),
        "expected account-required error, got: {stderr}"
    );
    assert!(
        stderr.contains("ngit account login") && stderr.contains("ngit account create"),
        "expected login and account creation guidance, got: {stderr}"
    );
    assert!(
        !stderr.contains("error getting fresh signer from nsec"),
        "non-interactive init unexpectedly attempted fresh login: {stderr}"
    );
    Ok(())
}

/// Equivalent of legacy `state_a_fresh::errors::bare_no_flags`. Bare
/// `ngit init` against a fresh repo trips `validate_fresh`'s "two
/// missing" branch (no name + no grasp), surfacing as
/// "missing required fields".
#[tokio::test]
async fn bare_no_flags_errors_missing_required_fields() -> Result<()> {
    let harness = Harness::builder(
        env!("CARGO_BIN_EXE_ngit"),
        env!("CARGO_BIN_EXE_git-remote-nostr"),
    )
    .with_relay("default")
    .build()
    .await?;

    let (repo, _state) = harness.arrange_init_state_a_fresh().await?;
    let out = repo
        .ngit(["init"])
        .output()
        .await
        .context("failed to spawn ngit init")?;

    assert!(
        !out.status.success(),
        "expected `ngit init` to fail with no flags in State A; \
         exited successfully\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        combined.contains("missing required fields"),
        "expected 'missing required fields' error, got: {combined}",
    );
    Ok(())
}

/// Equivalent of legacy
/// `state_a_fresh::errors::name_only_missing_server_infra`. With only
/// `--name` provided, `validate_fresh` falls into the "one missing"
/// branch — the message names the specific missing flag rather than
/// the umbrella "missing required fields".
#[tokio::test]
async fn name_only_errors_missing_grasp_server() -> Result<()> {
    let harness = Harness::builder(
        env!("CARGO_BIN_EXE_ngit"),
        env!("CARGO_BIN_EXE_git-remote-nostr"),
    )
    .with_relay("default")
    .build()
    .await?;

    let (repo, _state) = harness.arrange_init_state_a_fresh().await?;
    let out = repo
        .ngit(["init", "--name", DISPLAY_NAME])
        .output()
        .await
        .context("failed to spawn ngit init --name")?;

    assert!(
        !out.status.success(),
        "expected `ngit init --name` to fail in State A; exited successfully",
    );
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        combined.contains("missing --grasp-server"),
        "expected 'missing --grasp-server' error, got: {combined}",
    );
    Ok(())
}

/// Equivalent of legacy
/// `state_a_fresh::errors::relays_only_missing_name_and_servers`. With
/// only `--additional-relay` provided (and no `--additional-clone` /
/// `--grasp-server`),
/// `validate_fresh` lists *both* missing flags and falls back to the
/// umbrella message.
#[tokio::test]
async fn relays_only_errors_missing_required_fields() -> Result<()> {
    let harness = Harness::builder(
        env!("CARGO_BIN_EXE_ngit"),
        env!("CARGO_BIN_EXE_git-remote-nostr"),
    )
    .with_relay("default")
    .build()
    .await?;

    let (repo, _state) = harness.arrange_init_state_a_fresh().await?;
    // Use the harness's default relay URL rather than a hard-coded
    // localhost port: any reachable ws URL satisfies `--additional-relay`
    // *parser*, and we want the test's success path to depend only on
    // hitting the validate_fresh "two missing" branch — not on whether
    // a particular hardcoded relay happens to be alive.
    let relay_url = harness.relay("default").url().to_string();
    let out = repo
        .ngit(["init", "--additional-relay", &relay_url])
        .output()
        .await
        .context("failed to spawn ngit init --additional-relay")?;

    assert!(
        !out.status.success(),
        "expected `ngit init --additional-relay <url>` to fail in State A; exited successfully",
    );
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        combined.contains("missing required fields"),
        "expected 'missing required fields' error, got: {combined}",
    );
    Ok(())
}

// ---------------------------------------------------------------------------
// Success — shared snapshot, one rstest function per asserted property
// ---------------------------------------------------------------------------

/// Captured side-effects of one `ngit init --name "My Project"
/// --grasp-server <url>` invocation against a State A repo.
///
/// Holds the announcement event itself (rather than pre-extracted tag
/// values) so future cases asserting on additional tags don't have to
/// re-run setup; the maintainer npub + grasp URL prefix are surfaced
/// alongside because more than one case asserts on them.
struct Snapshot {
    announcement: Event,
    /// `http://127.0.0.1:<port>` — the grasp's URL the test passed to
    /// `--grasp-server`. Cloned URLs in the announcement should start
    /// with this prefix (and end with `/<npub>/<identifier>.git`).
    grasp_http_url: String,
    /// `ws://127.0.0.1:<port>` — the grasp's relay endpoint, expected
    /// to be one of the values in the announcement's `relays` tag.
    grasp_relay_url: String,
    /// Maintainer's npub — used by the `clone url contains npub` case.
    maintainer_npub: String,
    /// Root commit oid captured during arrange. The `r euc` tag on the
    /// announcement should equal this.
    root_oid: String,
}

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

#[fixture]
async fn snapshot() -> Arc<Snapshot> {
    SNAPSHOT
        .get_or_init(|| async {
            Arc::new(
                capture_snapshot()
                    .await
                    .expect("init_state_fresh fixture: capture_snapshot failed"),
            )
        })
        .await
        .clone()
}

async fn capture_snapshot() -> Result<Snapshot> {
    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 (repo, state) = harness.arrange_init_state_a_fresh().await?;

    let grasp = harness.grasp("repo");
    let grasp_http_url = grasp.url().to_string();
    let grasp_relay_url = grasp.relay_url();

    // No `--identifier`, no `--description` — match legacy
    // `state_a_fresh::success::with_name_and_grasp_server`'s shape so
    // identifier-derivation, default-empty-description, etc. are all
    // exercised exactly as legacy did.
    let init_out = repo
        .ngit([
            "init",
            "--name",
            DISPLAY_NAME,
            "--grasp-server",
            &grasp_http_url,
        ])
        .output()
        .await
        .context("failed to spawn ngit init --name --grasp-server")?;
    if !init_out.status.success() {
        bail!(
            "ngit init exited non-zero ({:?})\nstdout: {}\nstderr: {}",
            init_out.status,
            String::from_utf8_lossy(&init_out.stdout),
            String::from_utf8_lossy(&init_out.stderr),
        );
    }

    // Query the **vanilla default relay** for the announcement, not
    // the grasp: `ngit-grasp` routes new announcements to purgatory
    // until git data arrives, and under `NGITTEST=TRUE` the post-init
    // `git push` is short-circuited (init.rs:1195) — see
    // `tests/init_grasp.rs`'s module-level doc-comment for the chain.
    // The default relay always materialises the kind-30617 because
    // ngit fans out to the user's relay-list on publish.
    let announcements = harness
        .relay("default")
        .events(
            Filter::new()
                .author(state.keys.public_key())
                .kind(Kind::GitRepoAnnouncement),
        )
        .await?;
    let announcement = announcements
        .into_iter()
        .find(|e| tag_value(e, "d").as_deref() == Some(EXPECTED_IDENTIFIER))
        .with_context(|| {
            format!(
                "no kind-30617 with `d` = {EXPECTED_IDENTIFIER:?} on the default \
                 relay after `ngit init --name`"
            )
        })?;

    Ok(Snapshot {
        announcement,
        grasp_http_url,
        grasp_relay_url,
        maintainer_npub: state.npub,
        root_oid: state.root_oid,
    })
}

/// Equivalent of legacy
/// `with_name_and_grasp_server::identifier_derived_from_name`. The `d`
/// tag is the slug-cased `--name` argument.
#[rstest]
#[tokio::test]
async fn identifier_derived_from_name(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    assert_eq!(
        tag_value(&s.announcement, "d").as_deref(),
        Some(EXPECTED_IDENTIFIER),
    );
    Ok(())
}

/// Equivalent of legacy `with_name_and_grasp_server::name_tag_matches`.
/// The `name` tag carries the raw (un-slugified) `--name` argument.
#[rstest]
#[tokio::test]
async fn name_tag_matches(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    assert_eq!(
        tag_value(&s.announcement, "name").as_deref(),
        Some(DISPLAY_NAME)
    );
    Ok(())
}

/// Equivalent of legacy `with_name_and_grasp_server::description_empty`.
/// No `--description` was passed, so the `description` tag is the empty
/// string (the producer always emits the tag, even when blank — see
/// `RepoRef::to_event`).
#[rstest]
#[tokio::test]
async fn description_empty(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    assert_eq!(
        tag_value(&s.announcement, "description").as_deref(),
        Some("")
    );
    Ok(())
}

/// Equivalent of legacy
/// `with_name_and_grasp_server::clone_url_derived_from_grasp_server`.
/// Three sub-properties of the same `clone` tag:
///
/// - exactly one URL emitted (`--grasp-server` was passed once, and no
///   `--additional-clone` was added),
/// - URL starts with the grasp's HTTP base,
/// - URL ends with `/<identifier>.git`,
/// - URL contains the maintainer's npub (the `<git_data_path>/<npub>/...`
///   layout that ngit-grasp's announcement policy provisions).
#[rstest]
#[tokio::test]
async fn clone_url_derived_from_grasp_server(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    let clone_urls = tag_values(&s.announcement, "clone");
    assert_eq!(
        clone_urls.len(),
        1,
        "expected exactly one clone url; got {clone_urls:?}",
    );
    let url = &clone_urls[0];
    assert!(
        url.starts_with(&format!("{}/", s.grasp_http_url)),
        "clone url should start with grasp HTTP base ({}/); got: {url}",
        s.grasp_http_url,
    );
    assert!(
        url.ends_with(&format!("/{EXPECTED_IDENTIFIER}.git")),
        "clone url should end with /{EXPECTED_IDENTIFIER}.git; got: {url}",
    );
    assert!(
        url.contains(&s.maintainer_npub),
        "clone url should contain maintainer npub ({}); got: {url}",
        s.maintainer_npub,
    );
    Ok(())
}

/// Equivalent of legacy
/// `with_name_and_grasp_server::relays_include_grasp_derived`. The
/// announcement's `relays` tag contains only the grasp's ws URL (added by
/// `apply_grasp_infrastructure`); account/default relays are not copied in as
/// additional repository relays.
#[rstest]
#[tokio::test]
async fn relays_include_grasp_derived(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    let relays = tag_values(&s.announcement, "relays");
    assert_eq!(
        relays,
        vec![s.grasp_relay_url.clone()],
        "a grasp-backed repository should not gain default additional relays",
    );
    Ok(())
}

/// A fresh one-person repository uses NIP-34's implicit-author form. It does
/// not need an indexed role or deprecated compatibility roster until another
/// role is introduced.
#[rstest]
#[tokio::test]
async fn sole_maintainer_is_implicit(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    let membership_tags: Vec<Vec<String>> = s
        .announcement
        .tags
        .iter()
        .map(|t| t.as_slice().to_vec())
        .filter(|tag| {
            matches!(
                tag.first().map(String::as_str),
                Some("M" | "m" | "o" | "maintainers")
            )
        })
        .collect();
    assert_eq!(
        membership_tags,
        Vec::<Vec<String>>::new(),
        "the announcement author should remain the implicit sole maintainer",
    );
    Ok(())
}

/// Equivalent of legacy
/// `with_name_and_grasp_server::earliest_unique_commit_is_root`. The
/// `r ... euc` tag value matches the captured root commit oid — caught
/// dynamically against the arrange's `root_oid`.
#[rstest]
#[tokio::test]
async fn earliest_unique_commit_is_root(#[future] snapshot: Arc<Snapshot>) -> Result<()> {
    let s = snapshot.await;
    let euc = s
        .announcement
        .tags
        .iter()
        .find_map(|t| {
            let parts = t.as_slice();
            if parts.first().map(String::as_str) == Some("r")
                && parts.len() > 2
                && parts.get(2).map(String::as_str) == Some("euc")
            {
                parts.get(1).cloned()
            } else {
                None
            }
        })
        .context("announcement missing the `r <oid> euc` tag")?;
    assert_eq!(euc, s.root_oid);
    Ok(())
}

// ---------------------------------------------------------------------------
// Success — additional clone + relay (non-grasp clone path)
// ---------------------------------------------------------------------------

/// `--name X --additional-clone <vanilla> --additional-relay <ws>` exercises
/// the non-grasp clone-URL arm — the `is_grasp_server_clone_url == false`
/// branches throughout `init.rs` (e.g. line 274) and `repo_ref.rs`. The
/// harness-managed [`VanillaGitServer`](test_harness::VanillaGitServer)
/// stands in for "any plain git host". The URL must round-trip through
/// ngit's clone-URL handling without being rewritten or rejected, and the
/// initial push must treat the server's successful empty advertisement as a
/// valid baseline without manufacturing private-repository authorization.
///
/// Three things this pins:
///
/// 1. Harness integration: `with_vanilla_git_server("host")` starts an empty
///    bare server reachable at `Harness::vanilla_git_server("host").url()`. The
///    role label here is purely a harness lookup key — the server is **not**
///    added as a git remote anywhere in this test, so naming it after a git
///    remote (`"origin"`) would be misleading.
/// 2. `git ls-remote <vanilla_url>` returns exit 0 with empty output — proves
///    the in-process Smart-HTTP server is actually serving requests during the
///    test, not just that `VanillaGitServer::start_empty` produced a URL
///    string.
/// 3. ngit takes `--additional-clone + --additional-relay` together as
///    satisfying `validate_fresh`'s server-infra requirement (no
///    `--grasp-server` needed), accepts the vanilla URL, and emits it
///    **verbatim** in the announcement's `clone` tag — without the
///    `<npub>/<identifier>.git` suffix synthesis that the grasp path applies
///    (cf. `clone_url_derived_from_grasp_server` above).
/// 4. The successful empty listing receives no NIP-98 authorization and the
///    initial `main` branch is pushed to the mirror.
///
/// Uses a fresh `#[tokio::test(flavor = "multi_thread")]` rather than
/// joining the shared snapshot above because the snapshot is keyed on
/// `--grasp-server` and merging both shapes into one `ngit init` call
/// would mask which arm produced which tag.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn vanilla_clone_url_passes_through_to_announcement() -> Result<()> {
    let harness = Harness::builder(
        env!("CARGO_BIN_EXE_ngit"),
        env!("CARGO_BIN_EXE_git-remote-nostr"),
    )
    .with_relay("default")
    .with_vanilla_git_server("host")
    .build()
    .await?;

    let (repo, state) = harness.arrange_init_state_a_fresh().await?;

    let vanilla_url = harness.vanilla_git_server("host").url().to_string();
    let default_relay_url = harness.relay("default").url().to_string();

    // Belt-and-braces liveness probe: ls-remote the empty bare repo
    // *before* driving ngit. Catches a regression in the harness
    // integration ("with_vanilla_git_server registered but never bound
    // to a listener") at a clearly-attributable spot, separate from any
    // ngit-side failure mode.
    let ls = tokio::process::Command::new("git")
        .args(["ls-remote", &vanilla_url])
        .output()
        .await
        .context("failed to spawn git ls-remote against vanilla server")?;
    assert!(
        ls.status.success(),
        "ls-remote against harness-managed vanilla git server failed: stdout={} stderr={}",
        String::from_utf8_lossy(&ls.stdout),
        String::from_utf8_lossy(&ls.stderr),
    );
    assert!(
        String::from_utf8_lossy(&ls.stdout).trim().is_empty(),
        "empty bare repo should advertise zero refs; got: {}",
        String::from_utf8_lossy(&ls.stdout),
    );

    // The additional clone + relay together satisfy validate_fresh's
    // server-infra requirement (`has_both_relays_and_clone_url`). No
    // `--grasp-server`, and this harness registers no grasp server, so the
    // default set ngit would otherwise supplement with is empty — the
    // announcement exercises the non-grasp clone-URL arm exclusively.
    let init_out = repo
        .ngit([
            "init",
            "--name",
            DISPLAY_NAME,
            "--additional-clone",
            &vanilla_url,
            "--additional-relay",
            &default_relay_url,
        ])
        .output()
        .await
        .context("failed to spawn ngit init with additional clone and relay")?;
    if !init_out.status.success() {
        bail!(
            "ngit init exited non-zero ({:?})\nstdout: {}\nstderr: {}",
            init_out.status,
            String::from_utf8_lossy(&init_out.stdout),
            String::from_utf8_lossy(&init_out.stderr),
        );
    }

    let announcements = harness
        .relay("default")
        .events(
            Filter::new()
                .author(state.keys.public_key())
                .kind(Kind::GitRepoAnnouncement),
        )
        .await?;
    let announcement = announcements
        .into_iter()
        .find(|e| tag_value(e, "d").as_deref() == Some(EXPECTED_IDENTIFIER))
        .with_context(|| {
            format!(
                "no kind-30617 with `d` = {EXPECTED_IDENTIFIER:?} on the default \
                 relay after `ngit init` with additional clone and relay"
            )
        })?;

    let clone_urls = tag_values(&announcement, "clone");
    assert!(
        clone_urls.iter().any(|u| u == &vanilla_url),
        "expected vanilla URL {vanilla_url:?} verbatim in announcement's \
         clone tag (no <npub>/<id>.git synthesis on the non-grasp path); \
        got {clone_urls:?}",
    );
    assert_eq!(
        harness
            .vanilla_git_server("host")
            .nostr_authorization_requests(),
        0,
        "a public mirror must not receive private-repository HTTP authorization",
    );
    let mirror = git2::Repository::open_bare(harness.vanilla_git_server("host").repo_path())?;
    assert_eq!(
        mirror.refname_to_id("refs/heads/main")?.to_string(),
        state.head_oid,
        "the initial branch must be pushed after an empty advertisement",
    );
    Ok(())
}

// ---------------------------------------------------------------------------
// Success — pre-existing `origin` remote on a vanilla git server, with
// a branch and tag pushed *before* `ngit init` runs
// ---------------------------------------------------------------------------

/// Pre-populate a vanilla git server with `main` *and* an annotated tag,
/// wire it up as the repo's `origin` remote, then run `ngit init`. Two
/// behaviours pinned in one test because they're produced by the same
/// `ngit init` invocation and pre-creating refs on a server is the
/// expensive part of the arrange:
///
/// 1. **`origin` URL is rewritten to `nostr://`** — `ngit init` Step 7
///    (init.rs:1310-1317) does `remote_set_url("origin", &nostr_url)`
///    when an origin already exists, so the post-init `remote.origin.url`
///    config key starts with `nostr://`. Legacy tests in `state_d_*`
///    used an unreachable `https://localhost:1000` origin and never
///    exercised the *reachable*-origin variant; this test plugs that gap.
///
/// 2. **The first kind-30618 state event covers the pre-existing tag** even
///    though the tag was never passed on the CLI. `ngit init`'s origin-state
///    branch (init.rs:1213-1257) runs `list_from_remote` against the existing
///    `origin`, filters to `refs/heads/*` + `refs/tags/*` + `HEAD`, and bakes
///    those into the `RepoState::build` event added to the publish batch. The
///    tag being present in the state event without ever appearing on the `ngit
///    init` command line is the property the user asked for: "the first state
///    event pushed should take the existing state of an existing git server".
///
/// The arrange uses [`Repo::git`] (sync git operations against the
/// vanilla server's plain HTTP URL) rather than the harness's
/// [`Repo::nostr_push`] timing wrapper, because nothing in this arrange
/// emits a kind-30618 — those pushes don't go through
/// `git-remote-nostr`, so there's no same-second event-id collision
/// risk to dodge.
///
/// Multi-thread runtime: the vanilla server's accept loop runs as a
/// tokio task, and the test thread spawns blocking `git push`
/// subprocesses against it; on a single-worker `current_thread`
/// executor the test thread blocks the runtime before the accept loop
/// gets to poll, which deadlocks. Two workers is the minimum that
/// makes the wire path live.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pre_existing_origin_with_tag_promotes_to_nostr_and_state_event_covers_tag() -> Result<()> {
    /// Tag pushed to the vanilla server before `ngit init` runs. Annotated
    /// rather than lightweight so the produced kind-30618 has to carry the
    /// `<tag-object-oid>` (not the commit's oid) under the
    /// `refs/tags/<TAG_NAME>` slot — `list_from_remote` reports whatever
    /// the server advertises for the ref, and `git push origin tag <name>`
    /// of an annotated tag advertises the tag-object oid. Catches a
    /// regression where init.rs starts unwrapping annotated tags to their
    /// commit before baking into the state event.
    const TAG_NAME: &str = "v0.1.0";

    let harness = Harness::builder(
        env!("CARGO_BIN_EXE_ngit"),
        env!("CARGO_BIN_EXE_git-remote-nostr"),
    )
    .with_relay("default")
    .with_vanilla_git_server("host")
    .build()
    .await?;

    let (repo, state) = harness.arrange_init_state_a_fresh().await?;
    let vanilla_url = harness.vanilla_git_server("host").url().to_string();
    let default_relay_url = harness.relay("default").url().to_string();

    // Step 1: wire vanilla server up as `origin` and push the existing
    // history to it. This is the "pre-existing remote with content"
    // shape the test name describes.
    let out = repo
        .git(["remote", "add", "origin", &vanilla_url])
        .output()
        .await
        .context("failed to spawn git remote add origin")?;
    if !out.status.success() {
        bail!(
            "git remote add origin exited non-zero ({:?})\nstdout: {}\nstderr: {}",
            out.status,
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr),
        );
    }
    let out = repo
        .git(["push", "origin", "main"])
        .output()
        .await
        .context("failed to spawn git push origin main")?;
    if !out.status.success() {
        bail!(
            "git push origin main exited non-zero ({:?})\nstdout: {}\nstderr: {}",
            out.status,
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr),
        );
    }

    // Annotated tag so the server advertises the tag-object oid, not
    // the commit oid. `-m` makes it annotated rather than lightweight;
    // see TAG_NAME's doc for why this matters.
    let out = repo
        .git(["tag", "-a", TAG_NAME, "-m", "release v0.1.0"])
        .output()
        .await
        .context("failed to spawn git tag -a")?;
    if !out.status.success() {
        bail!(
            "git tag -a exited non-zero ({:?})\nstdout: {}\nstderr: {}",
            out.status,
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr),
        );
    }
    let out = repo
        .git(["push", "origin", "tag", TAG_NAME])
        .output()
        .await
        .context("failed to spawn git push origin tag")?;
    if !out.status.success() {
        bail!(
            "git push origin tag {TAG_NAME} exited non-zero ({:?})\nstdout: {}\nstderr: {}",
            out.status,
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr),
        );
    }

    // Liveness/pre-condition probe: the tag is on the server *before*
    // ngit init runs. Failing this proves the test's setup is wrong
    // rather than ngit's read of the server.
    let ls = tokio::process::Command::new("git")
        .args(["ls-remote", "--tags", &vanilla_url])
        .output()
        .await
        .context("failed to spawn git ls-remote --tags against vanilla server")?;
    assert!(
        ls.status.success(),
        "ls-remote against vanilla server failed: stdout={} stderr={}",
        String::from_utf8_lossy(&ls.stdout),
        String::from_utf8_lossy(&ls.stderr),
    );
    let tag_listing = String::from_utf8_lossy(&ls.stdout);
    assert!(
        tag_listing.contains(&format!("refs/tags/{TAG_NAME}")),
        "expected refs/tags/{TAG_NAME} on vanilla server before ngit init; \
         ls-remote --tags reported: {tag_listing}",
    );

    // Step 2: run `ngit init`. The additional clone + relay together satisfy
    // `validate_fresh`'s server-infra requirement (init.rs:362-370); the
    // origin remote is already pointing at this URL so the origin-state
    // branch (init.rs:1213-1257) is the one we want to fire.
    let init_out = repo
        .ngit([
            "init",
            "--name",
            DISPLAY_NAME,
            "--additional-clone",
            &vanilla_url,
            "--additional-relay",
            &default_relay_url,
        ])
        .output()
        .await
        .context("failed to spawn ngit init")?;
    if !init_out.status.success() {
        bail!(
            "ngit init exited non-zero ({:?})\nstdout: {}\nstderr: {}",
            init_out.status,
            String::from_utf8_lossy(&init_out.stdout),
            String::from_utf8_lossy(&init_out.stderr),
        );
    }

    // Assertion 1: origin remote URL rewritten to nostr://. This Step
    // runs unconditionally (init.rs:1310-1317) regardless of NGITTEST,
    // so it's the cheap half of the test to verify.
    let origin_url = repo
        .config("remote.origin.url")
        .await
        .context("failed to read remote.origin.url after ngit init")?
        .context("remote.origin.url was unset after ngit init")?;
    assert!(
        origin_url.starts_with("nostr://"),
        "expected `remote.origin.url` rewritten from {vanilla_url:?} to a \
         nostr:// URL after ngit init Step 7; got {origin_url:?}",
    );

    // Assertion 2: a kind-30618 state event was published, and it
    // covers the tag we pushed to the vanilla server pre-init. The
    // event lives on the default relay because `send_events` fans out
    // to the user's relay-list.
    let state_events = harness
        .relay("default")
        .events(
            Filter::new()
                .author(state.keys.public_key())
                .kind(Kind::Custom(30618)),
        )
        .await?;
    let state_event = state_events
        .into_iter()
        .find(|e| tag_value(e, "d").as_deref() == Some(EXPECTED_IDENTIFIER))
        .with_context(|| {
            format!(
                "no kind-30618 state event with `d` = {EXPECTED_IDENTIFIER:?} on \
                 the default relay after `ngit init` against a repo with a \
                 pre-existing reachable `origin` remote — the origin-state \
                 branch in init.rs:1213-1257 should have fired"
            )
        })?;

    // The state event encodes each ref as a tag whose name slot is the
    // full ref-path (e.g. `refs/tags/v0.1.0`) and whose value slot is
    // the oid the server advertised. We only need to check the tag is
    // there — the exact oid is whatever git assigned, which is opaque
    // to this assertion.
    let ref_tag_names: Vec<String> = state_event
        .tags
        .iter()
        .filter_map(|t| {
            let s = t.as_slice();
            s.first().and_then(|name| {
                if name.starts_with("refs/heads/") || name.starts_with("refs/tags/") {
                    Some(name.clone())
                } else {
                    None
                }
            })
        })
        .collect();
    assert!(
        ref_tag_names
            .iter()
            .any(|n| n == &format!("refs/tags/{TAG_NAME}")),
        "expected first kind-30618 to cover refs/tags/{TAG_NAME} taken from \
         the existing origin's state (the user never passed the tag on the \
         `ngit init` command line); got ref-name tags: {ref_tag_names:?}",
    );

    // Assertion 3: the origin-derived push records remote-tracking refs
    // for the branches the committed state now serves, like `git push`
    // would have. `origin` names the nostr remote at this point, so the
    // pre-nostr server's stale tracking entries must be replaced by the
    // committed state's view of `main`.
    let snapshot = repo.snapshot()?;
    let local_main = snapshot
        .refs
        .get("refs/heads/main")
        .context("refs/heads/main missing after ngit init")?;
    let tracking_main = snapshot.refs.get("refs/remotes/origin/main").context(
        "refs/remotes/origin/main missing after ngit init — the \
         origin-derived state push should record tracking refs for the \
         branches it published",
    )?;
    assert_eq!(
        tracking_main, local_main,
        "expected refs/remotes/origin/main to match the pushed main tip",
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// Success — self-lead through the repository-edit API
// ---------------------------------------------------------------------------

/// `repo edit --lead-maintainer` with the publisher's own npub keeps the
/// listing intact and asserts the publisher as lead. Their implicit sole-
/// maintainer history becomes an untimed `M` interval instead of a fabricated
/// closed `m` interval followed by a newly started `M` interval.
#[tokio::test]
async fn lead_maintainer_self_emits_uppercase_m_role_tag() -> 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 (repo, state) = harness.arrange_init_state_a_fresh().await?;
    let grasp_http_url = harness.grasp("repo").url().to_string();

    let init_out = repo
        .ngit([
            "init",
            "--name",
            DISPLAY_NAME,
            "--grasp-server",
            &grasp_http_url,
        ])
        .output()
        .await
        .context("failed to spawn ngit init")?;
    if !init_out.status.success() {
        bail!(
            "ngit init exited non-zero ({:?})\nstdout: {}\nstderr: {}",
            init_out.status,
            String::from_utf8_lossy(&init_out.stdout),
            String::from_utf8_lossy(&init_out.stderr),
        );
    }
    repo.nostr_push(["-u", "origin", "main"])
        .await
        .context("graduate sole-maintainer announcement")?;
    let edit_out = repo
        .ngit(["repo", "edit", "--lead-maintainer", &state.npub])
        .output()
        .await
        .context("failed to spawn ngit repo edit --lead-maintainer")?;
    if !edit_out.status.success() {
        bail!(
            "ngit repo edit --lead-maintainer exited non-zero ({:?})\nstdout: {}\nstderr: {}",
            edit_out.status,
            String::from_utf8_lossy(&edit_out.stdout),
            String::from_utf8_lossy(&edit_out.stderr),
        );
    }

    // same relay-selection rationale as `capture_snapshot`: the default
    // relay always materialises the kind-30617
    let announcements = harness
        .relay("default")
        .events(
            Filter::new()
                .author(state.keys.public_key())
                .kind(Kind::GitRepoAnnouncement),
        )
        .await?;
    let announcement = announcements
        .into_iter()
        .find(|e| tag_value(e, "d").as_deref() == Some(EXPECTED_IDENTIFIER))
        .with_context(|| {
            format!(
                "no kind-30617 with `d` = {EXPECTED_IDENTIFIER:?} on the default \
                 relay after `ngit repo edit --lead-maintainer`"
            )
        })?;

    let role_tags: Vec<Vec<String>> = announcement
        .tags
        .iter()
        .map(|t| t.as_slice().to_vec())
        .filter(|t| t.first().is_some_and(|name| name == "M" || name == "m"))
        .collect();
    let author = state.keys.public_key().to_string();
    assert_eq!(
        role_tags,
        vec![vec!["M".to_string(), author]],
        "the implicit sole maintainer should be lead from the beginning without m history",
    );
    assert_eq!(
        tag_values(&announcement, "maintainers"),
        vec![state.keys.public_key().to_string()],
        "deprecated `maintainers` tag should carry the same sole member",
    );
    Ok(())
}

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

/// First value of the first tag whose name slot equals `key`, if any.
fn tag_value(event: &Event, key: &str) -> Option<String> {
    event.tags.iter().find_map(|t| {
        let s = t.as_slice();
        if s.first().map(String::as_str) == Some(key) {
            s.get(1).cloned()
        } else {
            None
        }
    })
}

/// All values (slot 1+) of every tag whose name slot equals `key`. Used
/// for multi-value tags (`clone`, `relays`, `maintainers`).
fn tag_values(event: &Event, key: &str) -> Vec<String> {
    event
        .tags
        .iter()
        .find(|t| t.as_slice().first().map(String::as_str) == Some(key))
        .map(|t| t.as_slice()[1..].to_vec())
        .unwrap_or_default()
}