car-sync 0.50.0

Multi-device sync core for Common Agent Runtime — replica-tagged append-only oplog + deterministic CRDT fold
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
//! Network sync backend — CAR's client for a **remote** relay + lease register
//! (the Parslee sync service), behind the same [`Relay`] / [`LeaseCoordinator`]
//! traits the local [`FsRelay`] / [`InMemoryLeaseCoordinator`] already satisfy.
//!
//! # Why
//!
//! `FsRelay` converges two devices only if they share a filesystem directory —
//! fine for one machine, useless for "my phone and my Mac". This module makes
//! the relay a *service*: [`NetworkRelay`] and [`NetworkLeaseCoordinator`] speak
//! to it over a pluggable [`SyncTransport`], scoped to the caller's Parslee
//! identity (`scope`, e.g. `user:<id>` or `org:<id>`). The Parslee backend holds
//! only what `FsRelay` holds — op metadata (`op_id`/`hlc`/`seq`) in the clear and
//! op *payloads* as E2E ciphertext (see [`crate::crypto`]) — so it can route and
//! GC without reading your config.
//!
//! # The transport seam
//!
//! [`SyncTransport`] is the wire contract (blocking, because [`Relay`] is sync;
//! an HTTP impl blocks inside these calls, which the daemon already runs off a
//! task). Two impls:
//!
//! - [`LoopbackTransport`] — an **in-process reference server**. Each scope is
//!   backed by a real [`FsRelay`] + [`InMemoryLeaseCoordinator`] over a temp
//!   dir, so `NetworkRelay`-over-loopback is *semantically identical* to
//!   `FsRelay` by construction (no re-implementation of the GC-floor / dedup /
//!   monotone-ack / dominance logic). It is the test double AND a usable
//!   single-host multi-process relay. `Clone` shares one server across N
//!   devices.
//! - `HttpTransport` (a later slice) — reqwest against the real Parslee endpoint.
//!   It must implement the exact same contract; the loopback is the executable
//!   spec.

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

use serde::{Deserialize, Serialize};

use crate::checkpoint::Checkpoint;
use crate::crypto::WrappedOrgKey;
use crate::lease::{InMemoryLeaseCoordinator, Lease, LeaseCoordinator, LeaseError};
use crate::oplog::{Hlc, OpRecord, WallClock};
use crate::org_key_directory::{
    FsOrgKeyDirectory, MemberPublicKey, OrgKeyDirectory, OrgKeyDirectoryError,
};
use crate::relay::{
    AckOutcome, Frontier, GcReport, PullResult, PushOutcome, Relay, RelayConfig, RelayError,
    RosterEntry,
};

/// A transport-level failure — the *service* was unreachable or misbehaved.
/// Distinct from an in-band verdict (a deduped push, a `Held` lease): those are
/// success returns, not errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransportError {
    /// The service could not be reached / timed out / returned a transport
    /// error (HTTP 5xx, connection reset, …).
    Unavailable(String),
    /// The caller is not authorized for `scope` (bad/expired Parslee token).
    Unauthorized(String),
    /// A reply could not be parsed into the expected shape (protocol drift).
    Protocol(String),
    /// A pull requested a frontier below the relay's GC floor for `device_id`
    /// (retained ops start at `dropped_below`). NOT a failure — the service's
    /// signal that the caller must **cold-bootstrap** from the latest
    /// checkpoint. Maps to [`RelayError::FrontierTruncated`], which
    /// [`crate::session::SyncSession::pump`] already handles by rebasing.
    FrontierTruncated {
        device_id: String,
        dropped_below: u64,
    },
}

impl std::fmt::Display for TransportError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TransportError::Unavailable(m) => write!(f, "sync transport unavailable: {m}"),
            TransportError::Unauthorized(m) => write!(f, "sync transport unauthorized: {m}"),
            TransportError::Protocol(m) => write!(f, "sync transport protocol error: {m}"),
            TransportError::FrontierTruncated {
                device_id,
                dropped_below,
            } => write!(
                f,
                "sync transport frontier truncated: device {device_id} ops below seq \
                 {dropped_below} were GC'd (cold-bootstrap from checkpoint)"
            ),
        }
    }
}
impl std::error::Error for TransportError {}

impl From<TransportError> for RelayError {
    fn from(e: TransportError) -> Self {
        match e {
            // The service's cold-bootstrap signal maps to the relay's own
            // FrontierTruncated, which the pump handles by rebasing.
            TransportError::FrontierTruncated {
                device_id,
                dropped_below,
            } => RelayError::FrontierTruncated {
                device_id,
                dropped_below,
            },
            // Everything else has no relay variant; surface it as an IO-ish
            // failure so the pump's best-effort loop treats it as "try later".
            other => RelayError::Io(std::io::Error::other(other.to_string())),
        }
    }
}

/// The serialized verdict of a lease-register call. Mirrors the coordinator's
/// `Result<_, LeaseError>` in a wire-portable shape; the client reconstructs the
/// real [`LeaseError`] from it (the `agent_id` is known client-side).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LeaseWire {
    /// `acquire`/`renew` granted this lease.
    Granted(Lease),
    /// `acquire` CAS-failed: a still-valid lease is held.
    Held {
        holder: String,
        epoch: u64,
        expires_at_ms: u64,
    },
    /// `renew`/`release` found the caller is no longer the holder at its epoch.
    Lost {
        claimed_epoch: u64,
        current_epoch: u64,
    },
    /// `release` succeeded.
    Released,
    /// `current` read (holder or unheld).
    Current(Option<Lease>),
}

/// The wire contract for a remote sync service, scoped per Parslee identity.
///
/// Every method takes a `scope` (`user:<id>` / `org:<id>`) so one service backs
/// many tenants. Blocking by design. Impls MUST be faithful to [`FsRelay`] /
/// [`InMemoryLeaseCoordinator`] semantics — [`LoopbackTransport`] is the spec.
pub trait SyncTransport: Send + Sync {
    fn enroll(&self, scope: &str, device_id: &str) -> Result<RosterEntry, TransportError>;
    fn push(
        &self,
        scope: &str,
        device_id: &str,
        ops: &[OpRecord],
    ) -> Result<PushOutcome, TransportError>;
    fn pull(
        &self,
        scope: &str,
        device_id: &str,
        since: &Frontier,
    ) -> Result<PullResult, TransportError>;
    fn ack(
        &self,
        scope: &str,
        device_id: &str,
        frontier: Hlc,
    ) -> Result<AckOutcome, TransportError>;
    fn checkpoint_put(
        &self,
        scope: &str,
        device_id: &str,
        checkpoint: &Checkpoint,
    ) -> Result<bool, TransportError>;
    fn checkpoint_get(&self, scope: &str) -> Result<Option<Checkpoint>, TransportError>;
    fn roster(&self, scope: &str) -> Result<Vec<RosterEntry>, TransportError>;
    fn stable_frontier(&self, scope: &str) -> Result<Option<Hlc>, TransportError>;
    fn gc(&self, scope: &str) -> Result<GcReport, TransportError>;

    // --- execution lease register (B5, distributed) ---
    fn lease_acquire(
        &self,
        scope: &str,
        agent_id: &str,
        device_id: &str,
        ttl_ms: u64,
    ) -> Result<LeaseWire, TransportError>;
    fn lease_renew(
        &self,
        scope: &str,
        agent_id: &str,
        device_id: &str,
        epoch: u64,
        ttl_ms: u64,
    ) -> Result<LeaseWire, TransportError>;
    fn lease_release(
        &self,
        scope: &str,
        agent_id: &str,
        device_id: &str,
        epoch: u64,
    ) -> Result<LeaseWire, TransportError>;
    fn lease_current(&self, scope: &str, agent_id: &str) -> Result<LeaseWire, TransportError>;
}

/// The scope-keyed wire form of [`crate::org_key_directory::OrgKeyDirectory`] —
/// the org-key analogue of [`SyncTransport`]. Kept SEPARATE from `SyncTransport`
/// for the same reason the local directory is separate from `Relay`: org-key
/// blobs are a key-value directory, not oplog ops, and routing them around the
/// op stream keeps the frontier/GC invariants clean. One backend (e.g.
/// [`LoopbackTransport`], and later `ParsleeSyncTransport`) implements BOTH
/// traits over the same `scope: "org:<id>"` tenant key.
///
/// Every method takes a leading `scope`; a [`NetworkOrgKeyDirectory`] binds one
/// scope and adapts this into the local `OrgKeyDirectory` trait (the
/// [`NetworkRelay`] analogue).
pub trait OrgKeyTransport: Send + Sync {
    fn publish_wrapped(&self, scope: &str, wrapped: &WrappedOrgKey) -> Result<(), TransportError>;
    fn fetch_wrapped(
        &self,
        scope: &str,
        epoch: u64,
        recipient_user_id: &str,
    ) -> Result<Option<WrappedOrgKey>, TransportError>;
    fn fetch_wrapped_for(
        &self,
        scope: &str,
        recipient_user_id: &str,
    ) -> Result<Vec<WrappedOrgKey>, TransportError>;
    fn publish_pubkey(
        &self,
        scope: &str,
        account_id: &str,
        public_hex: &str,
    ) -> Result<(), TransportError>;
    fn fetch_pubkeys(&self, scope: &str) -> Result<Vec<MemberPublicKey>, TransportError>;
}

/// A [`Relay`] backed by a remote [`SyncTransport`], scoped to one Parslee
/// identity. One per device; share the transport (`Arc`) across devices.
pub struct NetworkRelay {
    transport: Arc<dyn SyncTransport>,
    scope: String,
}

impl NetworkRelay {
    pub fn new(transport: Arc<dyn SyncTransport>, scope: impl Into<String>) -> Self {
        Self {
            transport,
            scope: scope.into(),
        }
    }
}

impl Relay for NetworkRelay {
    fn register(&mut self, device_id: &str) -> Result<RosterEntry, RelayError> {
        Ok(self.transport.enroll(&self.scope, device_id)?)
    }
    fn push(&mut self, device_id: &str, ops: &[OpRecord]) -> Result<PushOutcome, RelayError> {
        Ok(self.transport.push(&self.scope, device_id, ops)?)
    }
    fn pull(&mut self, device_id: &str, since: &Frontier) -> Result<PullResult, RelayError> {
        Ok(self.transport.pull(&self.scope, device_id, since)?)
    }
    fn ack(&mut self, device_id: &str, frontier: Hlc) -> Result<AckOutcome, RelayError> {
        Ok(self.transport.ack(&self.scope, device_id, frontier)?)
    }
    fn checkpoint_put(
        &mut self,
        device_id: &str,
        checkpoint: &Checkpoint,
    ) -> Result<bool, RelayError> {
        Ok(self
            .transport
            .checkpoint_put(&self.scope, device_id, checkpoint)?)
    }
    fn checkpoint_get(&mut self) -> Result<Option<Checkpoint>, RelayError> {
        Ok(self.transport.checkpoint_get(&self.scope)?)
    }
    fn roster(&mut self) -> Result<Vec<RosterEntry>, RelayError> {
        Ok(self.transport.roster(&self.scope)?)
    }
    fn stable_frontier(&mut self) -> Result<Option<Hlc>, RelayError> {
        Ok(self.transport.stable_frontier(&self.scope)?)
    }
    fn gc(&mut self) -> Result<GcReport, RelayError> {
        Ok(self.transport.gc(&self.scope)?)
    }
}

/// A [`LeaseCoordinator`] backed by a remote [`SyncTransport`] — the
/// **distributed** execution lease that makes "phone and Mac" mutually
/// exclusive on a given agent. Reconstructs the real [`LeaseError`] from the
/// transport's [`LeaseWire`] verdict.
pub struct NetworkLeaseCoordinator {
    transport: Arc<dyn SyncTransport>,
    scope: String,
}

impl NetworkLeaseCoordinator {
    pub fn new(transport: Arc<dyn SyncTransport>, scope: impl Into<String>) -> Self {
        Self {
            transport,
            scope: scope.into(),
        }
    }
}

fn wire_to_lease(agent_id: &str, wire: LeaseWire, ctx: &'static str) -> Result<Lease, LeaseError> {
    match wire {
        LeaseWire::Granted(l) => Ok(l),
        LeaseWire::Held {
            holder,
            epoch,
            expires_at_ms,
        } => Err(LeaseError::Held {
            agent_id: agent_id.to_string(),
            holder,
            epoch,
            expires_at_ms,
        }),
        LeaseWire::Lost {
            claimed_epoch,
            current_epoch,
        } => Err(LeaseError::Lost {
            agent_id: agent_id.to_string(),
            claimed_epoch,
            current_epoch,
        }),
        other => Err(LeaseError::Backend(format!(
            "{ctx}: unexpected lease verdict {other:?}"
        ))),
    }
}

impl LeaseCoordinator for NetworkLeaseCoordinator {
    fn acquire(
        &mut self,
        agent_id: &str,
        device_id: &str,
        ttl_ms: u64,
    ) -> Result<Lease, LeaseError> {
        let wire = self
            .transport
            .lease_acquire(&self.scope, agent_id, device_id, ttl_ms)
            .map_err(|e| LeaseError::Backend(e.to_string()))?;
        wire_to_lease(agent_id, wire, "acquire")
    }

    fn renew(
        &mut self,
        agent_id: &str,
        device_id: &str,
        epoch: u64,
        ttl_ms: u64,
    ) -> Result<Lease, LeaseError> {
        let wire = self
            .transport
            .lease_renew(&self.scope, agent_id, device_id, epoch, ttl_ms)
            .map_err(|e| LeaseError::Backend(e.to_string()))?;
        wire_to_lease(agent_id, wire, "renew")
    }

    fn release(&mut self, agent_id: &str, device_id: &str, epoch: u64) -> Result<(), LeaseError> {
        let wire = self
            .transport
            .lease_release(&self.scope, agent_id, device_id, epoch)
            .map_err(|e| LeaseError::Backend(e.to_string()))?;
        match wire {
            LeaseWire::Released => Ok(()),
            LeaseWire::Lost {
                claimed_epoch,
                current_epoch,
            } => Err(LeaseError::Lost {
                agent_id: agent_id.to_string(),
                claimed_epoch,
                current_epoch,
            }),
            other => Err(LeaseError::Backend(format!(
                "release: unexpected lease verdict {other:?}"
            ))),
        }
    }

    fn current(&mut self, agent_id: &str) -> Result<Option<Lease>, LeaseError> {
        let wire = self
            .transport
            .lease_current(&self.scope, agent_id)
            .map_err(|e| LeaseError::Backend(e.to_string()))?;
        match wire {
            LeaseWire::Current(l) => Ok(l),
            other => Err(LeaseError::Backend(format!(
                "current: unexpected lease verdict {other:?}"
            ))),
        }
    }
}

// ---------------------------------------------------------------------------
// LoopbackTransport — the in-process reference server.
// ---------------------------------------------------------------------------

struct ScopeBackend {
    relay: crate::relay::FsRelay,
    lease: InMemoryLeaseCoordinator,
    /// The scope's org-key directory — a sibling of the `FsRelay` in the same
    /// per-scope dir (distinct file names: `org-keys.json`/`.lock` vs.
    /// `relay-state.json`/`relay.lock`), so one server keeps org-key blobs
    /// tenant-isolated exactly as it does the oplog.
    org_keys: FsOrgKeyDirectory,
}

struct LoopbackInner {
    dir: tempfile::TempDir,
    wall: WallClock,
    config: RelayConfig,
    scopes: BTreeMap<String, ScopeBackend>,
}

/// An in-process [`SyncTransport`]: each scope is a real [`FsRelay`] +
/// [`InMemoryLeaseCoordinator`] over a temp dir, so it reproduces the canonical
/// relay/lease semantics exactly. `Clone` shares one server across devices.
#[derive(Clone)]
pub struct LoopbackTransport {
    inner: Arc<Mutex<LoopbackInner>>,
}

impl LoopbackTransport {
    /// A fresh reference server (system wall clock, no eviction horizon).
    pub fn new() -> std::io::Result<Self> {
        Self::with_config(RelayConfig::default(), crate::oplog::system_clock())
    }

    pub fn with_config(config: RelayConfig, wall: WallClock) -> std::io::Result<Self> {
        Ok(Self {
            inner: Arc::new(Mutex::new(LoopbackInner {
                dir: tempfile::TempDir::new()?,
                wall,
                config,
                scopes: BTreeMap::new(),
            })),
        })
    }

    /// Run `f` against the (lazily-created) backend for `scope`.
    fn with_scope<R>(
        &self,
        scope: &str,
        f: impl FnOnce(&mut ScopeBackend) -> Result<R, TransportError>,
    ) -> Result<R, TransportError> {
        let mut inner = self
            .inner
            .lock()
            .map_err(|_| TransportError::Unavailable("loopback lock poisoned".into()))?;
        if !inner.scopes.contains_key(scope) {
            // FsRelay dirs are per-scope so one server keeps tenants isolated.
            let dir = inner.dir.path().join(sanitize_scope(scope));
            std::fs::create_dir_all(&dir)
                .map_err(|e| TransportError::Unavailable(format!("loopback mkdir: {e}")))?;
            let relay = crate::relay::FsRelay::open(&dir, inner.config.clone(), inner.wall.clone())
                .map_err(|e| TransportError::Unavailable(format!("loopback FsRelay: {e}")))?;
            let org_keys = FsOrgKeyDirectory::open(&dir)
                .map_err(|e| TransportError::Unavailable(format!("loopback org-keys: {e}")))?;
            let lease = InMemoryLeaseCoordinator::new(inner.wall.clone());
            inner.scopes.insert(
                scope.to_string(),
                ScopeBackend {
                    relay,
                    lease,
                    org_keys,
                },
            );
        }
        let backend = inner.scopes.get_mut(scope).expect("just inserted");
        f(backend)
    }
}

/// Map a scope string to a filesystem-safe dir name (loopback only).
///
/// NOTE: lossy — `org:acme` and `org_acme` both collapse to `org_acme`, so two
/// *distinct* scopes could share a dir here. Harmless in the reference server
/// (test scopes are well-separated) and absent from the real transport (which
/// keys by scope directly), but do not lean on this for isolation.
fn sanitize_scope(scope: &str) -> String {
    scope
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
        .collect()
}

fn relay_err(e: RelayError) -> TransportError {
    TransportError::Unavailable(e.to_string())
}

impl SyncTransport for LoopbackTransport {
    fn enroll(&self, scope: &str, device_id: &str) -> Result<RosterEntry, TransportError> {
        self.with_scope(scope, |b| b.relay.register(device_id).map_err(relay_err))
    }
    fn push(
        &self,
        scope: &str,
        device_id: &str,
        ops: &[OpRecord],
    ) -> Result<PushOutcome, TransportError> {
        self.with_scope(scope, |b| b.relay.push(device_id, ops).map_err(relay_err))
    }
    fn pull(
        &self,
        scope: &str,
        device_id: &str,
        since: &Frontier,
    ) -> Result<PullResult, TransportError> {
        self.with_scope(scope, |b| b.relay.pull(device_id, since).map_err(relay_err))
    }
    fn ack(
        &self,
        scope: &str,
        device_id: &str,
        frontier: Hlc,
    ) -> Result<AckOutcome, TransportError> {
        self.with_scope(scope, |b| {
            b.relay.ack(device_id, frontier).map_err(relay_err)
        })
    }
    fn checkpoint_put(
        &self,
        scope: &str,
        device_id: &str,
        checkpoint: &Checkpoint,
    ) -> Result<bool, TransportError> {
        self.with_scope(scope, |b| {
            b.relay
                .checkpoint_put(device_id, checkpoint)
                .map_err(relay_err)
        })
    }
    fn checkpoint_get(&self, scope: &str) -> Result<Option<Checkpoint>, TransportError> {
        self.with_scope(scope, |b| b.relay.checkpoint_get().map_err(relay_err))
    }
    fn roster(&self, scope: &str) -> Result<Vec<RosterEntry>, TransportError> {
        self.with_scope(scope, |b| b.relay.roster().map_err(relay_err))
    }
    fn stable_frontier(&self, scope: &str) -> Result<Option<Hlc>, TransportError> {
        self.with_scope(scope, |b| b.relay.stable_frontier().map_err(relay_err))
    }
    fn gc(&self, scope: &str) -> Result<GcReport, TransportError> {
        self.with_scope(scope, |b| b.relay.gc().map_err(relay_err))
    }

    fn lease_acquire(
        &self,
        scope: &str,
        agent_id: &str,
        device_id: &str,
        ttl_ms: u64,
    ) -> Result<LeaseWire, TransportError> {
        self.with_scope(scope, |b| {
            Ok(match b.lease.acquire(agent_id, device_id, ttl_ms) {
                Ok(l) => LeaseWire::Granted(l),
                Err(LeaseError::Held {
                    holder,
                    epoch,
                    expires_at_ms,
                    ..
                }) => LeaseWire::Held {
                    holder,
                    epoch,
                    expires_at_ms,
                },
                Err(e) => return Err(TransportError::Unavailable(e.to_string())),
            })
        })
    }
    fn lease_renew(
        &self,
        scope: &str,
        agent_id: &str,
        device_id: &str,
        epoch: u64,
        ttl_ms: u64,
    ) -> Result<LeaseWire, TransportError> {
        self.with_scope(scope, |b| {
            Ok(match b.lease.renew(agent_id, device_id, epoch, ttl_ms) {
                Ok(l) => LeaseWire::Granted(l),
                Err(LeaseError::Lost {
                    claimed_epoch,
                    current_epoch,
                    ..
                }) => LeaseWire::Lost {
                    claimed_epoch,
                    current_epoch,
                },
                Err(e) => return Err(TransportError::Unavailable(e.to_string())),
            })
        })
    }
    fn lease_release(
        &self,
        scope: &str,
        agent_id: &str,
        device_id: &str,
        epoch: u64,
    ) -> Result<LeaseWire, TransportError> {
        self.with_scope(scope, |b| {
            Ok(match b.lease.release(agent_id, device_id, epoch) {
                Ok(()) => LeaseWire::Released,
                Err(LeaseError::Lost {
                    claimed_epoch,
                    current_epoch,
                    ..
                }) => LeaseWire::Lost {
                    claimed_epoch,
                    current_epoch,
                },
                Err(e) => return Err(TransportError::Unavailable(e.to_string())),
            })
        })
    }
    fn lease_current(&self, scope: &str, agent_id: &str) -> Result<LeaseWire, TransportError> {
        self.with_scope(scope, |b| {
            b.lease
                .current(agent_id)
                .map(LeaseWire::Current)
                .map_err(|e| TransportError::Unavailable(e.to_string()))
        })
    }
}

fn org_key_err(e: OrgKeyDirectoryError) -> TransportError {
    TransportError::Unavailable(e.to_string())
}

impl OrgKeyTransport for LoopbackTransport {
    fn publish_wrapped(&self, scope: &str, wrapped: &WrappedOrgKey) -> Result<(), TransportError> {
        self.with_scope(scope, |b| {
            b.org_keys.publish_wrapped(wrapped).map_err(org_key_err)
        })
    }
    fn fetch_wrapped(
        &self,
        scope: &str,
        epoch: u64,
        recipient_user_id: &str,
    ) -> Result<Option<WrappedOrgKey>, TransportError> {
        self.with_scope(scope, |b| {
            b.org_keys
                .fetch_wrapped(epoch, recipient_user_id)
                .map_err(org_key_err)
        })
    }
    fn fetch_wrapped_for(
        &self,
        scope: &str,
        recipient_user_id: &str,
    ) -> Result<Vec<WrappedOrgKey>, TransportError> {
        self.with_scope(scope, |b| {
            b.org_keys
                .fetch_wrapped_for(recipient_user_id)
                .map_err(org_key_err)
        })
    }
    fn publish_pubkey(
        &self,
        scope: &str,
        account_id: &str,
        public_hex: &str,
    ) -> Result<(), TransportError> {
        self.with_scope(scope, |b| {
            b.org_keys
                .publish_pubkey(account_id, public_hex)
                .map_err(org_key_err)
        })
    }
    fn fetch_pubkeys(&self, scope: &str) -> Result<Vec<MemberPublicKey>, TransportError> {
        self.with_scope(scope, |b| b.org_keys.fetch_pubkeys().map_err(org_key_err))
    }
}

/// An [`OrgKeyDirectory`] backed by a remote [`OrgKeyTransport`], bound to one
/// `scope` (e.g. `"org:<id>"`). The org-key analogue of [`NetworkRelay`]: it
/// adapts the scope-keyed wire trait into the single-directory local trait so a
/// client speaks the same `OrgKeyDirectory` API whether it is fs-backed or
/// transport-backed. `TransportError` maps via [`transport_err`]: an authz
/// refusal is preserved as [`OrgKeyDirectoryError::Unauthorized`] (a security
/// "no", not a retry), everything else funnels into `Io` — the org-key analogue
/// of how `NetworkRelay` preserves `FrontierTruncated` and funnels the rest.
pub struct NetworkOrgKeyDirectory {
    transport: Arc<dyn OrgKeyTransport>,
    scope: String,
}

impl NetworkOrgKeyDirectory {
    pub fn new(transport: Arc<dyn OrgKeyTransport>, scope: impl Into<String>) -> Self {
        Self {
            transport,
            scope: scope.into(),
        }
    }
}

fn transport_err(e: TransportError) -> OrgKeyDirectoryError {
    match e {
        // A backend authz refusal is a security "no", not a retry — preserve it
        // as the load-bearing distinct variant (see OrgKeyDirectoryError docs).
        TransportError::Unauthorized(m) => OrgKeyDirectoryError::Unauthorized(m),
        // Everything else is a transport blip; the directory has no dedicated
        // variant, so funnel it into Io (a "try later" for callers).
        other => OrgKeyDirectoryError::Io(std::io::Error::other(other.to_string())),
    }
}

impl OrgKeyDirectory for NetworkOrgKeyDirectory {
    fn publish_wrapped(&mut self, wrapped: &WrappedOrgKey) -> Result<(), OrgKeyDirectoryError> {
        self.transport
            .publish_wrapped(&self.scope, wrapped)
            .map_err(transport_err)
    }
    fn fetch_wrapped(
        &self,
        epoch: u64,
        recipient_user_id: &str,
    ) -> Result<Option<WrappedOrgKey>, OrgKeyDirectoryError> {
        self.transport
            .fetch_wrapped(&self.scope, epoch, recipient_user_id)
            .map_err(transport_err)
    }
    fn fetch_wrapped_for(
        &self,
        recipient_user_id: &str,
    ) -> Result<Vec<WrappedOrgKey>, OrgKeyDirectoryError> {
        self.transport
            .fetch_wrapped_for(&self.scope, recipient_user_id)
            .map_err(transport_err)
    }
    fn publish_pubkey(
        &mut self,
        account_id: &str,
        public_hex: &str,
    ) -> Result<(), OrgKeyDirectoryError> {
        self.transport
            .publish_pubkey(&self.scope, account_id, public_hex)
            .map_err(transport_err)
    }
    fn fetch_pubkeys(&self) -> Result<Vec<MemberPublicKey>, OrgKeyDirectoryError> {
        self.transport
            .fetch_pubkeys(&self.scope)
            .map_err(transport_err)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::org_key_directory::conformance;
    use crate::relay::Relay;

    fn loopback() -> Arc<LoopbackTransport> {
        let clock: WallClock = Arc::new(|| 1000);
        Arc::new(LoopbackTransport::with_config(RelayConfig::default(), clock).unwrap())
    }

    fn transport() -> Arc<dyn SyncTransport> {
        loopback()
    }

    #[test]
    fn loopback_org_key_directory_satisfies_the_shared_contract() {
        // The SAME conformance sequence the fs/in-memory references pass in
        // org_key_directory.rs, now driven through the scope-keyed transport +
        // NetworkOrgKeyDirectory adapter — proving the wire form is behaviourally
        // identical before a byte crosses into car-parslee.
        let mut dir = NetworkOrgKeyDirectory::new(loopback(), "org:acme");
        conformance::round_trip_suite(&mut dir);
    }

    #[test]
    fn org_key_scopes_are_tenant_isolated() {
        // One server, two org scopes: a wrap/pubkey published under org:acme must
        // never be visible under org:globex (per-scope FsOrgKeyDirectory dirs).
        let svc = loopback();
        let mut acme = NetworkOrgKeyDirectory::new(svc.clone(), "org:acme");
        let globex = NetworkOrgKeyDirectory::new(svc.clone(), "org:globex");

        let w = conformance::make_wrap("acme", 1, "alice");
        acme.publish_wrapped(&w).unwrap();
        acme.publish_pubkey("alice", "cafe").unwrap();

        assert_eq!(acme.fetch_wrapped(1, "alice").unwrap().as_ref(), Some(&w));
        assert!(globex.fetch_wrapped(1, "alice").unwrap().is_none());
        assert!(globex.fetch_wrapped_for("alice").unwrap().is_empty());
        assert!(globex.fetch_pubkeys().unwrap().is_empty());
    }

    #[test]
    fn org_keys_persist_across_transport_handles_at_same_scope() {
        // Two NetworkOrgKeyDirectory handles over the SAME shared transport +
        // scope see each other's writes (the "phone + Mac share one org key"
        // path — and the load-bearing half of the isolation claim above), and
        // reads are &self.
        let svc = loopback();
        let mut writer = NetworkOrgKeyDirectory::new(svc.clone(), "org:acme");
        let reader = NetworkOrgKeyDirectory::new(svc.clone(), "org:acme");
        let w = conformance::make_wrap("acme", 7, "bob");
        writer.publish_wrapped(&w).unwrap();
        assert_eq!(reader.fetch_wrapped(7, "bob").unwrap().as_ref(), Some(&w));
    }

    #[test]
    fn transport_err_preserves_unauthorized_and_funnels_the_rest() {
        // The security-critical mapping: a backend authz refusal must NOT be
        // seen as a retryable Io blip (slice 3 returns Unauthorized on rejected
        // publishes).
        assert!(matches!(
            transport_err(TransportError::Unauthorized("nope".into())),
            OrgKeyDirectoryError::Unauthorized(_)
        ));
        assert!(matches!(
            transport_err(TransportError::Unavailable("down".into())),
            OrgKeyDirectoryError::Io(_)
        ));
        assert!(matches!(
            transport_err(TransportError::Protocol("drift".into())),
            OrgKeyDirectoryError::Io(_)
        ));
    }

    #[test]
    fn two_devices_converge_through_a_shared_service() {
        // Mac and phone push through ONE remote service (shared Arc). Each pulls
        // the other's ops — the "phone + Mac" convergence, but over the network
        // relay rather than a shared folder.
        let svc = transport();
        let scope = "user:matt";
        let mut mac = NetworkRelay::new(svc.clone(), scope);
        let mut phone = NetworkRelay::new(svc.clone(), scope);

        mac.register("mac").unwrap();
        phone.register("phone").unwrap();

        // Build a real, content-addressed op (the relay verifies op_id == the
        // content hash, so it must go through OpRecord::new).
        let op = crate::oplog::OpRecord::new(
            Hlc {
                wall_ms: 1000,
                counter: 0,
                device_id: "mac".into(),
            },
            0,
            None,
            crate::oplog::Scope::Personal,
            crate::oplog::Surface::Routing,
            serde_json::json!({"hello": "phone"}),
        );
        let out = mac.push("mac", std::slice::from_ref(&op)).unwrap();
        assert_eq!(out.accepted, 1);

        // The phone pulls from empty and sees the Mac's op.
        let pulled = phone.pull("phone", &Frontier::new()).unwrap();
        assert_eq!(pulled.ops.len(), 1);
        assert_eq!(pulled.ops[0].op_id, op.op_id);

        // Tenant isolation: a different scope is a different, empty relay.
        let mut other = NetworkRelay::new(svc.clone(), "user:someone_else");
        assert!(other.pull("d", &Frontier::new()).unwrap().ops.is_empty());
    }

    #[test]
    fn frontier_truncation_maps_to_the_relay_cold_bootstrap_signal() {
        // The service's distinct truncation signal must become
        // RelayError::FrontierTruncated so the pump rebases (cold bootstrap),
        // not a generic IO error that would just retry forever.
        let te = TransportError::FrontierTruncated {
            device_id: "mac".into(),
            dropped_below: 7,
        };
        match RelayError::from(te) {
            RelayError::FrontierTruncated {
                device_id,
                dropped_below,
            } => {
                assert_eq!(device_id, "mac");
                assert_eq!(dropped_below, 7);
            }
            other => panic!("expected FrontierTruncated, got {other:?}"),
        }
    }

    #[test]
    fn distributed_lease_is_mutually_exclusive_across_devices() {
        // Mac and phone contend for the same agent's execution lease through the
        // one service. Only one holds it; the loser sees `Held`; on release the
        // other acquires with the next (monotone) epoch — the fencing token that
        // stops both devices double-running the agent.
        let svc = transport();
        let scope = "user:matt";
        let mut mac = NetworkLeaseCoordinator::new(svc.clone(), scope);
        let mut phone = NetworkLeaseCoordinator::new(svc.clone(), scope);

        let l1 = mac.acquire("milo", "mac", 10_000).unwrap();
        assert_eq!(l1.epoch, 1);
        assert_eq!(l1.holder, "mac");

        // Phone loses the CAS while the Mac's lease is valid.
        match phone.acquire("milo", "phone", 10_000) {
            Err(LeaseError::Held { holder, epoch, .. }) => {
                assert_eq!(holder, "mac");
                assert_eq!(epoch, 1);
            }
            other => panic!("expected Held, got {other:?}"),
        }

        // Both devices read the same holder.
        assert_eq!(phone.current("milo").unwrap().unwrap().holder, "mac");

        // Mac releases; phone now acquires with epoch 2 (never reused).
        mac.release("milo", "mac", 1).unwrap();
        let l2 = phone.acquire("milo", "phone", 10_000).unwrap();
        assert_eq!(l2.epoch, 2);
        assert_eq!(l2.holder, "phone");

        // The Mac (a zombie holding the stale epoch) learns it lost.
        match mac.renew("milo", "mac", 1, 10_000) {
            Err(LeaseError::Lost { current_epoch, .. }) => assert_eq!(current_epoch, 2),
            other => panic!("expected Lost, got {other:?}"),
        }
    }
}