slancha-wire 0.17.0

Magic-wormhole for AI agents — bilateral signed-message bus over a mailbox relay
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
//! Multi-endpoint routing for v0.5.17 (dual-slot sessions).
//!
//! Each wire session can hold up to TWO slots:
//!   - **Federation** — on a public relay (default `https://wireup.net`),
//!     listed in the phonebook, reachable across machines.
//!   - **Local** — on a loopback relay (default `http://127.0.0.1:8771`,
//!     started with `wire relay-server --local-only`), invisible from
//!     off-box, sub-millisecond round-trip for same-machine sister-Claude
//!     traffic.
//!
//! Both slots are advertised to paired peers via the `pair_drop` body's
//! `endpoints[]` array (additive — v0.5.16-and-earlier peers see only
//! the federation endpoint at the top-level legacy fields, unchanged).
//!
//! Routing decision lives in `cmd_push`: walk a peer's pinned endpoints
//! in priority order (local first if we also have a local slot), POST
//! the event, fall back to the next endpoint on failure. Pulling: the
//! daemon reads from BOTH slots, dedupes by `event_id`.
//!
//! Storage shape in `relay_state.json`:
//!
//! ```jsonc
//! {
//!   "self": {
//!     // Self-slot still carries the flat triple (the #263 daemon-survival
//!     // fix synthesizes a sister's flat fields; self-collapse is Part A /
//!     // a separate slice — see RFC-006).
//!     "relay_url": "https://wireup.net",
//!     "slot_id":   "abc...",
//!     "slot_token":"...",
//!     "endpoints": [
//!       {"relay_url": "https://wireup.net",     "slot_id": "abc...",  "slot_token": "...", "scope": "federation"},
//!       {"relay_url": "http://127.0.0.1:8771",  "slot_id": "loop...", "slot_token": "...", "scope": "local"}
//!     ]
//!   },
//!   "peers": {
//!     "wire-mesh": {
//!       // RFC-006 Part B (#268): peers carry `endpoints[]` ONLY — the single
//!       // peer-routing source. The flat relay_url/slot_id/slot_token triple
//!       // is no longer written (it was the "stale flat beats fresh array"
//!       // routing hazard). All peer-pin readers resolve through
//!       // `peer_endpoints_in_priority_order` / `peer_primary_endpoint`.
//!       "endpoints": [...]
//!     }
//!   }
//! }
//! ```

use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Where this endpoint sits in the reachability graph.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EndpointScope {
    /// Public-facing relay (e.g. `https://wireup.net`). Crosses machines.
    Federation,
    /// Loopback-only relay (e.g. `http://127.0.0.1:8771`). Same-machine only.
    Local,
    /// LAN-bound relay (e.g. `http://192.168.1.50:8771`). Reachable from
    /// other machines on the same network without going through federation.
    /// v0.7.0-alpha.9: third scope for noble-creek-on-paul-mac ↔
    /// running-light-on-spark style across-the-room pairing without
    /// wireup.net hop. Visible to anyone who fetches the agent-card —
    /// opt-in per session (operator passes `--with-lan-relay <url>` at
    /// `wire session new` time).
    Lan,
    /// Unix Domain Socket (e.g. `unix:///path/to/local.sock`). Same-host,
    /// same-uid only. v0.7.0-alpha.16: framed primarily as a SECURITY
    /// boundary — no bound TCP port (no firewall surface), SO_PEERCRED
    /// kernel-attested peer uid (sister-session trust anchor), 0600
    /// socket permissions. Performance win over loopback HTTP is real
    /// but tiny (~1.3µs) and not the headline reason. Opt-in via
    /// `wire session new --with-uds`; Unix-only (Windows falls back to
    /// Local loopback).
    Uds,
}

/// One reachable address for a wire identity. Includes the bearer
/// `slot_token` because endpoints flow through the pair_drop body,
/// which is encrypted at protocol level (signed envelope + bilateral
/// pin gate from v0.5.14). Token is the slot's bearer credential; it
/// MUST stay private to the pair and is never published in the agent
/// card or phonebook.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Endpoint {
    pub relay_url: String,
    pub slot_id: String,
    pub slot_token: String,
    pub scope: EndpointScope,
}

impl Endpoint {
    pub fn federation(relay_url: String, slot_id: String, slot_token: String) -> Self {
        Self {
            relay_url,
            slot_id,
            slot_token,
            scope: EndpointScope::Federation,
        }
    }

    pub fn local(relay_url: String, slot_id: String, slot_token: String) -> Self {
        Self {
            relay_url,
            slot_id,
            slot_token,
            scope: EndpointScope::Local,
        }
    }

    /// v0.7.0-alpha.9: construct a LAN-scope endpoint.
    pub fn lan(relay_url: String, slot_id: String, slot_token: String) -> Self {
        Self {
            relay_url,
            slot_id,
            slot_token,
            scope: EndpointScope::Lan,
        }
    }

    /// v0.7.0-alpha.16: construct a UDS-scope endpoint.
    /// `relay_url` is a `unix:///abs/path/to/local.sock` URL (the
    /// `unix://` scheme is wire-internal; readers route to a UDS HTTP
    /// client rather than reqwest).
    pub fn uds(relay_url: String, slot_id: String, slot_token: String) -> Self {
        Self {
            relay_url,
            slot_id,
            slot_token,
            scope: EndpointScope::Uds,
        }
    }
}

/// Read all of a peer's pinned endpoints from `relay_state.json`,
/// sorted in routing priority order:
///
/// 1. Local endpoints first — only when we ALSO have a local slot
///    (i.e. our `self.endpoints` includes a local one with the same
///    relay_url). Otherwise local endpoints are skipped because we
///    can't reach them.
/// 2. Federation endpoints second.
///
/// RFC-006 Part B (#268): reads `endpoints[]` only — the single peer-routing
/// source. There is no flat-field synthesis fallback; a peer pin with no
/// `endpoints[]` array yields no endpoints (every real pin carries it).
pub fn peer_endpoints_in_priority_order(relay_state: &Value, peer_handle: &str) -> Vec<Endpoint> {
    let our_local_relay_url = relay_state
        .get("self")
        .and_then(|s| s.get("endpoints"))
        .and_then(Value::as_array)
        .and_then(|arr| {
            arr.iter()
                .find(|e| e.get("scope").and_then(Value::as_str) == Some("local"))
                .and_then(|e| e.get("relay_url"))
                .and_then(Value::as_str)
                .map(str::to_string)
        });

    let peer = match relay_state.get("peers").and_then(|p| p.get(peer_handle)) {
        Some(p) => p,
        None => return Vec::new(),
    };

    let mut all: Vec<Endpoint> = Vec::new();

    if let Some(arr) = peer.get("endpoints").and_then(Value::as_array) {
        for ep in arr {
            if let Ok(parsed) = serde_json::from_value::<Endpoint>(ep.clone()) {
                all.push(parsed);
            }
        }
    }

    // RFC-006 Part B: `endpoints[]` is the only peer-routing source. The
    // former flat-field synthesis fallback (for pre-v0.5.16 pins with no
    // `endpoints` array) is gone — every pin now carries `endpoints[]`
    // (`pin_peer_endpoints` writes it; invite-accept routes through it too).

    // Sort: UDS (same-host trust anchor) first, then local-loopback-
    // with-matching-self-local, then LAN (cross-machine same-network),
    // then federation. Drop unreachable scopes via the retain pass.
    //
    // v0.7.0-alpha.9: LAN endpoints sit between Local and Federation.
    // Faster than federation; not gated by "our_local matches" because
    // cross-machine peers won't have a matching our-local by definition.
    //
    // v0.7.0-alpha.16: UDS endpoints get rank 0 when peer + self share
    // a UDS socket path (we need to be able to connect to their socket
    // which means it must be readable by our uid). The "same-uid same-
    // host" sister-session trust shape this enforces is the whole
    // point of UDS — see project_wire_transport_substrate_research.
    let our_local = our_local_relay_url.clone();
    all.sort_by_key(|ep| match (ep.scope, &our_local) {
        (EndpointScope::Uds, _) => 0,
        (EndpointScope::Local, Some(our)) if &ep.relay_url == our => 1,
        (EndpointScope::Lan, _) => 2,
        (EndpointScope::Federation, _) => 3,
        _ => 4,
    });
    // Drop unreachable: Local needs matching loopback URL; UDS needs
    // the socket file to exist on our filesystem (the daemon-side
    // connect will surface a clearer error than a routing-time drop
    // would, but we still keep UDS in the routing list — failure
    // falls through to lower-priority scopes).
    all.retain(|ep| match (ep.scope, &our_local) {
        (EndpointScope::Local, None) => false,
        (EndpointScope::Local, Some(our)) => &ep.relay_url == our,
        (EndpointScope::Lan, _) => true,
        (EndpointScope::Uds, _) => true,
        (EndpointScope::Federation, _) => true,
    });
    all
}

/// All of OUR own endpoints from `relay_state.json`. Used by `cmd_push`
/// to find the local slot when routing local-first, and by the daemon's
/// pull loop to iterate every slot we should be reading from.
pub fn self_endpoints(relay_state: &Value) -> Vec<Endpoint> {
    let self_state = match relay_state.get("self") {
        Some(s) if !s.is_null() => s,
        _ => return Vec::new(),
    };
    let mut all: Vec<Endpoint> = Vec::new();
    if let Some(arr) = self_state.get("endpoints").and_then(Value::as_array) {
        for ep in arr {
            if let Ok(parsed) = serde_json::from_value::<Endpoint>(ep.clone()) {
                all.push(parsed);
            }
        }
    }
    if all.is_empty() {
        // Back-compat: synthesize a federation endpoint from legacy
        // top-level fields. Slot_token may be absent in some old
        // states; in that case the synthesized endpoint is partial
        // and downstream code must guard against empty token.
        let relay_url = self_state
            .get("relay_url")
            .and_then(Value::as_str)
            .unwrap_or("");
        let slot_id = self_state
            .get("slot_id")
            .and_then(Value::as_str)
            .unwrap_or("");
        let slot_token = self_state
            .get("slot_token")
            .and_then(Value::as_str)
            .unwrap_or("");
        if !relay_url.is_empty() && !slot_id.is_empty() {
            all.push(Endpoint::federation(
                relay_url.to_string(),
                slot_id.to_string(),
                slot_token.to_string(),
            ));
        }
    }
    all
}

/// v0.9 canonical single-reader for "my best inbound slot." Returns
/// the first endpoint from `self_endpoints()` — which is already
/// priority-ordered (UDS → Local-with-matching-self → LAN →
/// Federation) AND back-compat-falls-back to legacy top-level fields.
///
/// Replaces ad-hoc `self_state["relay_url"].as_str()` reads scattered
/// through the codebase. Pre-v0.9 those bare reads were the silent-
/// fail root cause: a session with only `self.endpoints[]` (no legacy
/// top-level fields) returned empty strings instead of the available
/// endpoint, and pair_drop_ack / pull / rotate-slot all silently
/// no-op'd. Always use this from new code.
pub fn self_primary_endpoint(relay_state: &Value) -> Option<Endpoint> {
    self_endpoints(relay_state).into_iter().next()
}

/// The single best (highest-priority) endpoint to reach `peer_handle`, or
/// `None` if the peer has no pinned endpoints. RFC-006 Part B: the canonical
/// replacement for reading the old flat `relay_url`/`slot_id`/`slot_token` peer
/// fields — every peer-pin reader resolves through this (or
/// `peer_endpoints_in_priority_order` when it needs failover).
pub fn peer_primary_endpoint(relay_state: &Value, peer_handle: &str) -> Option<Endpoint> {
    peer_endpoints_in_priority_order(relay_state, peer_handle)
        .into_iter()
        .next()
}

/// The `slot_token` of a peer's pinned **federation** endpoint on `relay_url`,
/// or `""` if there's no such endpoint (or it hasn't acked yet).
///
/// RFC-006 Part B: the canonical way to carry a peer's already-arrived reply
/// token forward across a re-pin. It replaces the old flat `peers[h].slot_token`
/// read — which Part B (#268) stopped *writing*, so any dial path still reading
/// it now reads `""` and silently wipes the peer's reply token on re-dial. Both
/// dial paths (`cli::pairing` and the MCP `tool_dial`) route through here so
/// they can't drift apart again.
pub fn peer_federation_token(relay_state: &Value, peer_handle: &str, relay_url: &str) -> String {
    relay_state
        .get("peers")
        .and_then(|p| p.get(peer_handle))
        .and_then(|e| e.get("endpoints"))
        .and_then(|a| serde_json::from_value::<Vec<Endpoint>>(a.clone()).ok())
        .unwrap_or_default()
        .into_iter()
        .find(|e| e.scope == EndpointScope::Federation && e.relay_url == relay_url)
        .map(|e| e.slot_token)
        .unwrap_or_default()
}

/// Pin a peer's full set of endpoints into `relay_state.json` under
/// `peers[handle]`. RFC-006 Part B (#268): writes `endpoints[]` ONLY — the
/// single peer-routing source. The flat `relay_url`/`slot_id`/`slot_token`
/// triple is no longer written. Durable non-routing fields
/// (`bilateral_completed_at`, `persona`, `profile`, `first_seen_at`,
/// `nostr_transport`) are preserved across re-pins (see below).
pub fn pin_peer_endpoints(
    relay_state: &mut Value,
    peer_handle: &str,
    endpoints: &[Endpoint],
) -> Result<()> {
    let peers = relay_state
        .as_object_mut()
        .map(|m| {
            m.entry("peers")
                .or_insert_with(|| Value::Object(Default::default()))
        })
        .ok_or_else(|| anyhow::anyhow!("relay_state.json root is not an object"))?
        .as_object_mut()
        .ok_or_else(|| anyhow::anyhow!("relay_state.peers is not an object"))?;
    // v0.14.2 (#162 fix #5): preserve durable peer state across re-pin
    // events. honey-pine observed `wire_peers` tier flapping
    // VERIFIED → PENDING_ACK; root cause is this `peers.insert(.., entry)`
    // wholesale-replacement losing any previously-set field. The fields
    // we explicitly retain here represent monotonic state — once
    // bilateral-pair is complete or the peer's published persona/profile
    // is known, those facts must NOT be wiped just because a fresh
    // pair_drop_ack carrying only endpoint data lands. Other fields
    // (`relay_url`, `slot_id`, `slot_token`, `endpoints`) are always
    // current-state and intentionally re-derived from the input below.
    let preserved: serde_json::Map<String, Value> = peers
        .get(peer_handle)
        .and_then(Value::as_object)
        .map(|m| {
            m.iter()
                .filter(|(k, _)| {
                    matches!(
                        k.as_str(),
                        "bilateral_completed_at"
                            | "persona"
                            | "profile"
                            | "first_seen_at"
                            // RFC-007 D3.4: a peer's Nostr transport coords are
                            // durable reachability state — must survive an
                            // HTTP-endpoint re-pin (same monotonic-state rule).
                            | "nostr_transport"
                    )
                })
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect()
        })
        .unwrap_or_default();
    // RFC-006 Part B: `endpoints[]` is the SINGLE peer-routing source. The
    // top-level flat `relay_url`/`slot_id`/`slot_token` fields are no longer
    // written — they were a redundant synthesized copy (the "stale flat beats
    // fresh array" routing hazard). All peer-pin readers now resolve through
    // `peer_endpoints_in_priority_order`. (Self-slot flat is a separate
    // representation, untouched here.)
    let mut entry = preserved;
    entry.insert("endpoints".into(), serde_json::to_value(endpoints)?);
    peers.insert(peer_handle.to_string(), Value::Object(entry));
    Ok(())
}

/// RFC-007 D3.4: record a peer's **Nostr transport** reachability — their
/// x-only npub (hex) + a `wss://` relay to reach them on — under
/// `peers[handle].nostr_transport`. Read-modify-write so it composes with
/// `pin_peer_endpoints` (which preserves this field). Reachability only; trust
/// is a separate pin. Idempotent.
pub fn pin_peer_nostr_transport(
    relay_state: &mut Value,
    peer_handle: &str,
    npub_hex: &str,
    relay_url: &str,
) -> Result<()> {
    let peers = relay_state
        .as_object_mut()
        .map(|m| {
            m.entry("peers")
                .or_insert_with(|| Value::Object(Default::default()))
        })
        .ok_or_else(|| anyhow::anyhow!("relay_state.json root is not an object"))?
        .as_object_mut()
        .ok_or_else(|| anyhow::anyhow!("relay_state.peers is not an object"))?;
    let entry = peers
        .entry(peer_handle.to_string())
        .or_insert_with(|| Value::Object(Default::default()))
        .as_object_mut()
        .ok_or_else(|| anyhow::anyhow!("relay_state.peers[{peer_handle}] is not an object"))?;
    entry.insert(
        "nostr_transport".into(),
        serde_json::json!({ "npub": npub_hex, "relay": relay_url }),
    );
    Ok(())
}

/// Read a peer's Nostr transport coords `(npub_hex, relay_url)`, or `None` if
/// the peer has no Nostr transport recorded.
pub fn peer_nostr_transport(relay_state: &Value, peer_handle: &str) -> Option<(String, String)> {
    let nt = relay_state
        .get("peers")?
        .get(peer_handle)?
        .get("nostr_transport")?;
    let npub = nt.get("npub")?.as_str()?.to_string();
    let relay = nt.get("relay")?.as_str()?.to_string();
    if npub.is_empty() || relay.is_empty() {
        return None;
    }
    Some((npub, relay))
}

/// RFC-007 D3: record a Nostr relay this session is *reachable on* — one we've
/// paired/fetched over (`wire nostr pair/accept/fetch --relay X`). Persisted as
/// the distinct set `self.nostr_relays[]`. The daemon pull-loop reads this as
/// the authoritative "where do peers publish my inbound" set: a peer sends to me
/// by publishing to a relay *I'm* reachable on, which isn't necessarily a relay
/// *I* reach *them* on (the asymmetric case the peer-transport set misses).
/// Read-modify-write, idempotent (dedups).
pub fn pin_self_nostr_relay(relay_state: &mut Value, relay_url: &str) -> Result<()> {
    if relay_url.is_empty() {
        return Ok(());
    }
    let self_obj = relay_state
        .as_object_mut()
        .map(|m| {
            m.entry("self")
                .or_insert_with(|| Value::Object(Default::default()))
        })
        .ok_or_else(|| anyhow::anyhow!("relay_state.json root is not an object"))?
        .as_object_mut()
        .ok_or_else(|| anyhow::anyhow!("relay_state.self is not an object"))?;
    let arr = self_obj
        .entry("nostr_relays")
        .or_insert_with(|| Value::Array(Vec::new()))
        .as_array_mut()
        .ok_or_else(|| anyhow::anyhow!("relay_state.self.nostr_relays is not an array"))?;
    if !arr.iter().any(|v| v.as_str() == Some(relay_url)) {
        arr.push(Value::String(relay_url.to_string()));
    }
    Ok(())
}

/// The distinct Nostr relays this session is reachable on (`self.nostr_relays[]`).
/// Empty when never paired over Nostr.
pub fn self_nostr_relays(relay_state: &Value) -> Vec<String> {
    relay_state
        .get("self")
        .and_then(|s| s.get("nostr_relays"))
        .and_then(Value::as_array)
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str())
                .filter(|s| !s.is_empty())
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default()
}

/// Infer an endpoint scope from a relay URL: `unix://` -> Uds, a loopback
/// host -> Local, otherwise Federation. LAN is never inferred (a private-
/// range IP is indistinguishable from a federation host by URL alone) and
/// must be requested explicitly.
pub fn infer_scope_from_url(url: &str) -> EndpointScope {
    if url.starts_with("unix://") {
        return EndpointScope::Uds;
    }
    let host = url
        .trim_start_matches("http://")
        .trim_start_matches("https://")
        .split('/')
        .next()
        .unwrap_or("")
        .split(':')
        .next()
        .unwrap_or("");
    if is_loopback_host(host) {
        EndpointScope::Local
    } else {
        EndpointScope::Federation
    }
}

/// True iff `host` (no scheme, no port) is a loopback address the E4 trust-path
/// gates treat as `Local` scope: `infer_scope_from_url`, the handle validator +
/// URL builder (`pair_profile::is_valid_domain` / `relay_url_for_domain`), and
/// the `is_known_relay_domain` phishing-warning suppression all key off THIS one
/// predicate so scheme + scope can never disagree. Keeping one predicate is
/// load-bearing: if these gates disagreed on "loopback", a handle could parse +
/// get an `http://` URL while being classified `Federation` (advertised off-box).
///
/// IPv4 `127.0.0.1` + `localhost` only. IPv6 `::1` is intentionally excluded — an
/// IPv6 authority needs bracketing (`[::1]:port`) the handle/URL path doesn't
/// carry, so `nick@::1:port` is rejected rather than half-accepted into a
/// malformed `http://::1:port`; use `127.0.0.1` for a loopback handle. Do not
/// broaden the IPv4 set to the full /8 here without updating every caller. (NB:
/// `session.rs::url_is_loopback` is a SEPARATE, deliberately-broader /8 predicate
/// for same-box session discovery — not a trust gate.)
pub fn is_loopback_host(host: &str) -> bool {
    host == "127.0.0.1" || host == "localhost"
}

/// True iff this endpoint set is reachable ONLY from the same box — every
/// endpoint resolves (by URL) to a loopback/`Local` or `Uds` address, with no
/// off-box `Federation`/LAN host. A peer pinned this way can't complete a
/// bilateral reply path with a *remote* peer: the reply has nowhere off-box to
/// land. This is the #277 honesty signal — `wire accept` reported
/// `bilateral_accepted` even when the resulting pin advertised only loopback
/// endpoints. Inferred from the URL (not the advertised `scope`) so a loopback
/// address mislabeled `federation` (exactly the #277 case) is still caught.
/// Empty set → false (no pin to judge).
pub fn endpoints_are_local_only(endpoints: &[Endpoint]) -> bool {
    !endpoints.is_empty()
        && endpoints.iter().all(|e| {
            matches!(
                infer_scope_from_url(&e.relay_url),
                EndpointScope::Local | EndpointScope::Uds
            )
        })
}

/// Build the `self` block for `relay_state.json` from an endpoint set:
/// the additive `endpoints[]` array plus legacy top-level
/// relay_url/slot_id/slot_token pointing at the federation endpoint (or,
/// absent one, the first endpoint) for v0.5.16-and-earlier back-compat.
fn build_self_value(eps: &[Endpoint]) -> Value {
    let legacy = eps
        .iter()
        .find(|e| e.scope == EndpointScope::Federation)
        .or_else(|| eps.first());
    let mut self_obj = serde_json::Map::new();
    if let Some(l) = legacy {
        self_obj.insert("relay_url".into(), Value::String(l.relay_url.clone()));
        self_obj.insert("slot_id".into(), Value::String(l.slot_id.clone()));
        self_obj.insert("slot_token".into(), Value::String(l.slot_token.clone()));
    }
    self_obj.insert(
        "endpoints".into(),
        serde_json::to_value(eps).unwrap_or(Value::Null),
    );
    Value::Object(self_obj)
}

/// Insert-or-replace one of OUR OWN endpoints in `relay_state["self"]`,
/// keyed by `relay_url` (re-binding the same relay updates it in place).
/// ADDITIVE: every other existing self endpoint is preserved, so an agent
/// can hold a local relay AND a federation relay at once. Rebuilds the
/// legacy top-level fields. Single source of truth for the self-slot write
/// shape — used by `cmd_bind_relay` and `init_self_idempotent`.
pub fn upsert_self_endpoint(relay_state: &mut Value, ep: Endpoint) {
    let mut eps = self_endpoints(relay_state);
    eps.retain(|e| e.relay_url != ep.relay_url);
    eps.push(ep);
    relay_state["self"] = build_self_value(&eps);
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn infer_scope_classifies_loopback_unix_and_federation() {
        assert_eq!(
            infer_scope_from_url("http://127.0.0.1:8771"),
            EndpointScope::Local
        );
        assert_eq!(
            infer_scope_from_url("http://localhost:8771"),
            EndpointScope::Local
        );
        assert_eq!(
            infer_scope_from_url("unix:///tmp/wire.sock"),
            EndpointScope::Uds
        );
        assert_eq!(
            infer_scope_from_url("https://wireup.net"),
            EndpointScope::Federation
        );
    }

    #[test]
    fn upsert_self_endpoint_is_additive_then_updates_in_place() {
        let mut state = json!({});
        upsert_self_endpoint(
            &mut state,
            Endpoint::federation("https://wireup.net".into(), "fed1".into(), "ft".into()),
        );
        upsert_self_endpoint(
            &mut state,
            Endpoint::local("http://127.0.0.1:8771".into(), "loc1".into(), "lt".into()),
        );
        // Both kept.
        assert_eq!(self_endpoints(&state).len(), 2);
        // Legacy fields point at federation.
        assert_eq!(state["self"]["relay_url"], "https://wireup.net");
        // Re-binding the same relay replaces that one entry, not appends.
        upsert_self_endpoint(
            &mut state,
            Endpoint::local("http://127.0.0.1:8771".into(), "loc2".into(), "lt2".into()),
        );
        let eps = self_endpoints(&state);
        assert_eq!(eps.len(), 2, "same-relay rebind replaces, not appends");
        let loc = eps
            .iter()
            .find(|e| e.scope == EndpointScope::Local)
            .unwrap();
        assert_eq!(loc.slot_id, "loc2", "local slot updated in place");
    }

    #[test]
    fn peer_endpoints_ignores_flat_only_pin_post_rfc006() {
        // RFC-006 Part B: `endpoints[]` is the single peer-routing source. A
        // peer with ONLY the old flat fields and no `endpoints[]` array yields
        // NO endpoints — the synthesis fallback was removed. (No users to
        // migrate; every real pin now carries `endpoints[]`.)
        let state = json!({
            "peers": {
                "alice": { "relay_url": "https://wireup.net", "slot_id": "abc", "slot_token": "tok" }
            }
        });
        assert!(peer_endpoints_in_priority_order(&state, "alice").is_empty());
    }

    #[test]
    fn self_nostr_relay_roundtrips_and_dedups() {
        let mut state = json!({});
        pin_self_nostr_relay(&mut state, "wss://r1").unwrap();
        pin_self_nostr_relay(&mut state, "wss://r2").unwrap();
        pin_self_nostr_relay(&mut state, "wss://r1").unwrap(); // dup → no-op
        pin_self_nostr_relay(&mut state, "").unwrap(); // empty → no-op
        assert_eq!(
            self_nostr_relays(&state),
            vec!["wss://r1".to_string(), "wss://r2".to_string()]
        );
        // Composes with an existing self block (doesn't clobber other self keys).
        let mut state2 = json!({"self": {"relay_url": "https://wireup.net", "slot_id": "s"}});
        pin_self_nostr_relay(&mut state2, "wss://x").unwrap();
        assert_eq!(state2["self"]["relay_url"], "https://wireup.net");
        assert_eq!(self_nostr_relays(&state2), vec!["wss://x".to_string()]);
        // Absent → empty.
        assert!(self_nostr_relays(&json!({})).is_empty());
    }

    #[test]
    fn endpoints_are_local_only_catches_loopback_pin_incl_mislabeled_scope() {
        // Empty → false (nothing to judge).
        assert!(!endpoints_are_local_only(&[]));
        // A loopback URL mislabeled `federation` (the #277 case) is still caught
        // — we infer from the URL, not the advertised scope.
        let mislabeled =
            Endpoint::federation("http://127.0.0.1:18791".into(), "s".into(), "t".into());
        assert!(endpoints_are_local_only(std::slice::from_ref(&mislabeled)));
        // A real federation host → reachable, not local-only.
        let fed = Endpoint::federation("https://wireup.net".into(), "s".into(), "t".into());
        assert!(!endpoints_are_local_only(std::slice::from_ref(&fed)));
        // Mixed (loopback + federation) → reachable off-box via the federation one.
        assert!(!endpoints_are_local_only(&[mislabeled.clone(), fed]));
        // UDS is same-host only → local-only.
        let uds = Endpoint::uds("unix:///tmp/wire.sock".into(), "s".into(), "t".into());
        assert!(endpoints_are_local_only(&[uds]));
    }

    #[test]
    fn peer_federation_token_carries_forward_from_endpoints_not_flat() {
        // RFC-006 Part B regression: re-dial must carry the peer's already-acked
        // reply token forward from `endpoints[]`. Reading the old flat
        // `slot_token` (which Part B stopped writing) returned "" and wiped it.
        let state = json!({
            "peers": {
                "alice": {
                    // A stale flat field must NOT be the source of truth...
                    "slot_token": "STALE_FLAT",
                    "endpoints": [
                        {"relay_url": "https://wireup.net", "slot_id": "s1", "slot_token": "REAL_TOK", "scope": "federation"},
                        {"relay_url": "http://127.0.0.1:8771", "slot_id": "l1", "slot_token": "LOCAL_TOK", "scope": "local"}
                    ]
                }
            }
        });
        // ...the federation endpoint's token on the matching relay is.
        assert_eq!(
            peer_federation_token(&state, "alice", "https://wireup.net"),
            "REAL_TOK"
        );
        // A different relay (no matching federation endpoint) → empty, not the
        // local token and not the stale flat field.
        assert_eq!(
            peer_federation_token(&state, "alice", "https://other.example"),
            ""
        );
        // Unknown peer → empty.
        assert_eq!(
            peer_federation_token(&state, "nobody", "https://wireup.net"),
            ""
        );
    }

    #[test]
    fn peer_endpoints_lan_beats_federation() {
        // v0.7.0-alpha.9: when a peer publishes both Lan and Federation
        // endpoints (and we have a matching local too), priority must be
        // Local(matched) > Lan > Federation. Lan is cross-machine same-
        // network, faster than federation but not as fast as loopback.
        let state = json!({
            "self": {
                "endpoints": [
                    {"relay_url": "http://127.0.0.1:8771", "slot_id": "self-loop", "slot_token": "t1", "scope": "local"},
                    {"relay_url": "https://wireup.net", "slot_id": "self-fed", "slot_token": "t2", "scope": "federation"}
                ]
            },
            "peers": {
                "alice": {
                    "endpoints": [
                        {"relay_url": "https://wireup.net", "slot_id": "a-fed", "slot_token": "ta-f", "scope": "federation"},
                        {"relay_url": "http://192.168.1.50:8771", "slot_id": "a-lan", "slot_token": "ta-l", "scope": "lan"},
                        {"relay_url": "http://127.0.0.1:8771", "slot_id": "a-loop", "slot_token": "ta-loop", "scope": "local"}
                    ]
                }
            }
        });
        let eps = peer_endpoints_in_priority_order(&state, "alice");
        assert_eq!(
            eps.len(),
            3,
            "Local(matched) + Lan + Federation all reachable"
        );
        assert_eq!(
            eps[0].scope,
            EndpointScope::Local,
            "loopback wins (same-machine)"
        );
        assert_eq!(
            eps[1].scope,
            EndpointScope::Lan,
            "Lan second (same-network)"
        );
        assert_eq!(
            eps[2].scope,
            EndpointScope::Federation,
            "Federation last (anywhere)"
        );
    }

    #[test]
    fn peer_endpoints_lan_kept_when_self_has_no_local() {
        // Cross-machine peer scenario: we have no Local, peer has Lan
        // and Federation. Lan must still be kept (we connect TO their
        // LAN address; we don't need a Local of our own to do so).
        let state = json!({
            "self": {
                "endpoints": [
                    {"relay_url": "https://wireup.net", "slot_id": "self-fed", "slot_token": "t1", "scope": "federation"}
                ]
            },
            "peers": {
                "alice": {
                    "endpoints": [
                        {"relay_url": "https://wireup.net", "slot_id": "a-fed", "slot_token": "ta-f", "scope": "federation"},
                        {"relay_url": "http://192.168.1.50:8771", "slot_id": "a-lan", "slot_token": "ta-l", "scope": "lan"}
                    ]
                }
            }
        });
        let eps = peer_endpoints_in_priority_order(&state, "alice");
        assert_eq!(eps.len(), 2);
        assert_eq!(
            eps[0].scope,
            EndpointScope::Lan,
            "Lan preferred over Federation"
        );
        assert_eq!(eps[1].scope, EndpointScope::Federation);
    }

    #[test]
    fn pin_peer_endpoints_writes_no_flat_fields_post_rfc006() {
        // RFC-006 Part B: pin writes `endpoints[]` ONLY — no synthesized
        // top-level relay_url/slot_id/slot_token. Routing reads the array.
        let mut state = json!({});
        let endpoints = vec![
            Endpoint::lan(
                "http://192.168.1.50:8771".to_string(),
                "lan-slot".to_string(),
                "lan-tok".to_string(),
            ),
            Endpoint::local(
                "http://127.0.0.1:8771".to_string(),
                "loop-slot".to_string(),
                "loop-tok".to_string(),
            ),
        ];
        pin_peer_endpoints(&mut state, "alice", &endpoints).unwrap();
        let alice = &state["peers"]["alice"];
        assert!(alice.get("relay_url").is_none(), "no flat relay_url");
        assert!(alice.get("slot_id").is_none(), "no flat slot_id");
        assert!(alice.get("slot_token").is_none(), "no flat slot_token");
        assert_eq!(
            alice["endpoints"].as_array().map(Vec::len),
            Some(2),
            "endpoints[] is the routing source"
        );
    }

    #[test]
    fn peer_endpoints_orders_local_first_when_self_has_matching_local() {
        let state = json!({
            "self": {
                "endpoints": [
                    {"relay_url": "https://wireup.net",    "slot_id": "self-fed",  "slot_token": "t1", "scope": "federation"},
                    {"relay_url": "http://127.0.0.1:8771", "slot_id": "self-loop", "slot_token": "t2", "scope": "local"}
                ]
            },
            "peers": {
                "alice": {
                    "endpoints": [
                        {"relay_url": "https://wireup.net",    "slot_id": "a-fed",  "slot_token": "ta1", "scope": "federation"},
                        {"relay_url": "http://127.0.0.1:8771", "slot_id": "a-loop", "slot_token": "ta2", "scope": "local"}
                    ]
                }
            }
        });
        let eps = peer_endpoints_in_priority_order(&state, "alice");
        assert_eq!(eps.len(), 2);
        assert_eq!(eps[0].scope, EndpointScope::Local);
        assert_eq!(eps[1].scope, EndpointScope::Federation);
    }

    #[test]
    fn peer_endpoints_drops_local_when_self_has_no_local() {
        let state = json!({
            "self": {
                "endpoints": [
                    {"relay_url": "https://wireup.net", "slot_id": "self-fed", "slot_token": "t1", "scope": "federation"}
                ]
            },
            "peers": {
                "alice": {
                    "endpoints": [
                        {"relay_url": "https://wireup.net",    "slot_id": "a-fed",  "slot_token": "ta1", "scope": "federation"},
                        {"relay_url": "http://127.0.0.1:8771", "slot_id": "a-loop", "slot_token": "ta2", "scope": "local"}
                    ]
                }
            }
        });
        let eps = peer_endpoints_in_priority_order(&state, "alice");
        // Only federation reachable: local was filtered.
        assert_eq!(eps.len(), 1);
        assert_eq!(eps[0].scope, EndpointScope::Federation);
    }

    #[test]
    fn peer_endpoints_drops_local_when_relay_urls_dont_match() {
        let state = json!({
            "self": {
                "endpoints": [
                    {"relay_url": "http://127.0.0.1:8771", "slot_id": "self-loop", "slot_token": "t2", "scope": "local"}
                ]
            },
            "peers": {
                "alice": {
                    "endpoints": [
                        {"relay_url": "http://127.0.0.1:9999", "slot_id": "a-loop", "slot_token": "ta2", "scope": "local"}
                    ]
                }
            }
        });
        // Our local is :8771, peer's local is :9999 — can't route there.
        let eps = peer_endpoints_in_priority_order(&state, "alice");
        assert_eq!(
            eps.len(),
            0,
            "different local relays cannot reach each other"
        );
    }

    #[test]
    fn pin_then_resolve_round_trips_through_endpoints_array() {
        // RFC-006 Part B: pin writes endpoints[]; routing resolves from it
        // (priority order), with NO flat fields involved on either side.
        let mut state = json!({"peers": {}});
        let endpoints = vec![
            Endpoint::federation("https://wireup.net".into(), "abc".into(), "tok".into()),
            Endpoint::local(
                "http://127.0.0.1:8771".into(),
                "loop".into(),
                "loop-tok".into(),
            ),
        ];
        pin_peer_endpoints(&mut state, "alice", &endpoints).unwrap();
        let alice = &state["peers"]["alice"];
        assert!(alice.get("relay_url").is_none(), "no flat fields written");
        assert_eq!(alice["endpoints"].as_array().map(Vec::len), Some(2));
        // Resolve from the array (no flat). Without a matching self-local relay,
        // the peer's loopback endpoint isn't reachable for us, so federation is
        // the primary route.
        // Priority order drops the unreachable loopback (no matching
        // self-local), leaving the federation route.
        let ordered = peer_endpoints_in_priority_order(&state, "alice");
        assert_eq!(ordered.len(), 1, "only the reachable federation route");
        let primary = peer_primary_endpoint(&state, "alice").unwrap();
        assert_eq!(primary.scope, EndpointScope::Federation);
        assert_eq!(primary.slot_id, "abc");
    }

    #[test]
    fn self_endpoints_back_compat_falls_back_to_legacy_fields() {
        let state = json!({
            "self": {
                "relay_url": "https://wireup.net",
                "slot_id": "self-fed",
                "slot_token": "t1"
            }
        });
        let eps = self_endpoints(&state);
        assert_eq!(eps.len(), 1);
        assert_eq!(eps[0].scope, EndpointScope::Federation);
        assert_eq!(eps[0].slot_id, "self-fed");
    }

    #[test]
    fn self_endpoints_returns_both_when_dual_slot() {
        let state = json!({
            "self": {
                "endpoints": [
                    {"relay_url": "https://wireup.net",    "slot_id": "self-fed",  "slot_token": "t1", "scope": "federation"},
                    {"relay_url": "http://127.0.0.1:8771", "slot_id": "self-loop", "slot_token": "t2", "scope": "local"}
                ]
            }
        });
        let eps = self_endpoints(&state);
        assert_eq!(eps.len(), 2);
    }

    // ── RFC-007 D3.4: per-peer Nostr transport reachability ──
    #[test]
    fn nostr_transport_roundtrips() {
        let mut state = serde_json::json!({});
        let npub = "a".repeat(64);
        pin_peer_nostr_transport(&mut state, "raven-kettle", &npub, "wss://relay.damus.io")
            .unwrap();
        assert_eq!(
            peer_nostr_transport(&state, "raven-kettle"),
            Some((npub.clone(), "wss://relay.damus.io".to_string()))
        );
        // Unknown peer → None.
        assert_eq!(peer_nostr_transport(&state, "nobody"), None);
    }

    #[test]
    fn nostr_transport_survives_endpoint_repin() {
        // The #162 hazard: a later HTTP-endpoint pin must NOT wipe the recorded
        // Nostr transport (it's monotonic reachability state).
        let mut state = serde_json::json!({});
        let npub = "b".repeat(64);
        pin_peer_nostr_transport(&mut state, "p", &npub, "wss://nos.lol").unwrap();
        pin_peer_endpoints(
            &mut state,
            "p",
            &[Endpoint::federation(
                "https://wireup.net".into(),
                "slot1".into(),
                "tok1".into(),
            )],
        )
        .unwrap();
        // Both survive.
        assert_eq!(
            peer_nostr_transport(&state, "p"),
            Some((npub, "wss://nos.lol".to_string()))
        );
        assert_eq!(peer_endpoints_in_priority_order(&state, "p").len(), 1);
    }

    #[test]
    fn nostr_transport_is_idempotent_and_updatable() {
        let mut state = serde_json::json!({});
        pin_peer_nostr_transport(&mut state, "p", &"c".repeat(64), "wss://a").unwrap();
        // Re-record with a new relay → updates.
        pin_peer_nostr_transport(&mut state, "p", &"c".repeat(64), "wss://b").unwrap();
        assert_eq!(
            peer_nostr_transport(&state, "p"),
            Some(("c".repeat(64), "wss://b".to_string()))
        );
    }
}