liminal-sdk 0.6.0

Application-facing SDK traits for liminal messaging clients
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
//! Remote participant state, durable client records, and typed transport outcomes.
//!
//! This module owns process mechanics only. Every participant lifecycle and
//! correlation decision is delegated to `liminal-protocol`; the SDK stores the
//! crate aggregate and its sealed one-use authorities without mirroring their
//! rules.

mod recovery;
mod replay_apply;

pub use recovery::{
    RemoteDetachReplayOutcome, RemoteExpectedOperationRecovery, RemoteLostOperationResolution,
    RemoteLostReconnectResolution, RemoteReconnectAttemptOutcome, RemoteReconnectPermitRecovery,
    RemoteReplayApplyOutcome, RemoteTransportLossOutcome,
};

use alloc::sync::Arc;
use core::fmt;
use core::time::Duration;

use liminal_protocol::client::{
    ClientCorrelatedInboundDecision, ClientInboundDecision, ClientInboundRefusalReason,
    ClientOperationRecordDecision, ClientOperationRecordRefusalReason, ClientParticipantAggregate,
    ClientResponseCorrelation, ClientResumeRecord, ClientResumeRecordDecodeError,
    ClientResumeRecordEncodeError, ClientResumeRestoreError, ExpectedOperationFateRefusalReason,
    ExpectedOperationTransportFate, ExpectedParticipantOperation, ReconnectPermitDecision,
    decide_correlated_inbound, decide_inbound, record_expected_operation_fate,
    record_transport_fate,
};
use liminal_protocol::outcome::ReconnectDelayResult;
use liminal_protocol::wire::{
    ClientRequest, DeliverySeq, ParticipantFrame, ServerPush, ServerValue,
};
use spin::Mutex;

use crate::SdkError;

use super::protocol::{ParticipantTransportFrame, RemoteTransport};
use super::{RemoteConfig, ServerAddress};

/// Storage boundary for canonical `LPCR` client resume bytes.
///
/// Implementations must replace the previously committed bytes durably before
/// returning `Ok(())`. The SDK calls this boundary after the protocol crate's
/// commit seal and before releasing executable operation authority.
pub trait ParticipantResumeStore: Send {
    /// Durably replaces the stored canonical client resume record.
    ///
    /// # Errors
    ///
    /// Returns [`SdkError::Store`] when the bytes were not durably committed.
    fn persist(&mut self, canonical_lpcr: &[u8]) -> Result<(), SdkError>;
}

/// Transport-layer testimony identifying the connection attempt that delivered a frame.
///
/// This is the sealed transport context anticipated by rationale 15 in
/// `LP-CLIENT-GOAL`. It does not alter the wire format or relax the protocol
/// crate's conservative `RecordAdmission` ambiguity.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ParticipantResponseProvenance {
    connection_id: u64,
    attempt_id: u64,
}

impl ParticipantResponseProvenance {
    #[cfg(feature = "std")]
    pub(super) const fn new(connection_id: u64, attempt_id: u64) -> Self {
        Self {
            connection_id,
            attempt_id,
        }
    }

    /// Returns the local identity of the established socket.
    #[must_use]
    pub const fn connection_id(self) -> u64 {
        self.connection_id
    }

    /// Returns the local identity of the real connection attempt.
    #[must_use]
    pub const fn attempt_id(self) -> u64 {
        self.attempt_id
    }
}

/// Failure at the SDK participant state, codec, storage, or transport boundary.
#[derive(Debug, thiserror::Error)]
pub enum RemoteParticipantError {
    /// A prior commit could not be persisted, so no aggregate authority remains reachable.
    #[error("participant state is unavailable after an unreleased durability failure")]
    StateUnavailable,
    /// The protocol crate could not encode the current aggregate as canonical LPCR.
    #[error("client resume record encode failed: {0:?}")]
    ResumeEncode(ClientResumeRecordEncodeError),
    /// Persisted bytes were not a canonical LPCR record.
    #[error("client resume record decode failed: {0:?}")]
    ResumeDecode(ClientResumeRecordDecodeError),
    /// Canonical facts violated a protocol restore invariant.
    #[error("client resume record restore failed: {0:?}")]
    ResumeRestore(ClientResumeRestoreError),
    /// The caller-owned durable store rejected a canonical record.
    #[error("client resume record persistence failed: {0}")]
    Storage(SdkError),
    /// The real transport failed outside a typed fate-reporting operation.
    #[error("participant transport failed: {0}")]
    Transport(SdkError),
    /// A client-to-server request appeared on the SDK receive side.
    #[error("participant transport decoded a request in the client receive direction")]
    InvalidInboundDirection,
    /// No live response correlation exists for a replay-specific input.
    #[error("no live participant response authority is held")]
    ResponseAuthorityUnavailable,
}

/// Opaque one-use operation released only after the SDK persisted sealed LPCR bytes.
#[derive(Debug)]
pub struct RemoteParticipantOperation {
    operation: ExpectedParticipantOperation,
    durability: OperationDurability,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum OperationDurability {
    WriteAhead,
    Continuous,
}

/// Result of admitting an outbound request through the crate write-ahead barrier.
#[derive(Debug)]
pub enum RemoteOperationRecordOutcome {
    /// Canonical LPCR bytes were persisted and one operation may now be sent.
    Recorded(RemoteParticipantOperation),
    /// A continuous acknowledgement bypassed the write-ahead slot by crate rule.
    Continuous(RemoteParticipantOperation),
    /// The crate refused the exact request without changing aggregate state.
    Refused {
        /// Exact refused request.
        request: ClientRequest,
        /// Closed protocol refusal reason.
        reason: ClientOperationRecordRefusalReason,
    },
}

/// Typed operation-domain consequence of an established transport loss.
#[derive(Debug, PartialEq, Eq)]
pub enum RemoteOperationTransportFate {
    /// A non-detach operation's response became unavailable.
    Recorded {
        /// Exact terminalized request.
        request: ClientRequest,
    },
    /// The exact detach was returned to parked replay.
    DetachParked,
    /// The crate retained the live correlation unchanged.
    Refused {
        /// Closed refusal reason from the generic operation-fate gate.
        reason: ExpectedOperationFateRefusalReason,
    },
    /// No response authority was outstanding.
    NotOutstanding,
}

/// Typed reconnect permit returned by a crate-authorized fresh event.
#[derive(Debug)]
pub struct RemoteReconnectPermit {
    pub(super) permit: liminal_protocol::client::ReconnectAttemptPermit,
}

/// Event-driven reconnect permit decision; there is no delay or timer arm.
#[derive(Debug)]
pub enum RemoteReconnectPermitOutcome {
    /// The crate minted one one-use permit.
    Permitted {
        /// Opaque permit for one real connection attempt.
        permit: RemoteReconnectPermit,
        /// Legacy-named crate result whose value is event-only.
        result: ReconnectDelayResult,
    },
    /// Existing authority was retained.
    Refused {
        /// Closed crate refusal reason.
        reason: liminal_protocol::client::ReconnectPermitRefusalReason,
        /// Event-only crate result.
        result: ReconnectDelayResult,
    },
}

/// Result of sending an operation on the participant transport.
#[derive(Debug)]
pub enum RemoteParticipantSendOutcome {
    /// The request bytes were written on this connection attempt.
    Sent {
        /// Sealed transport context for a later response.
        provenance: ParticipantResponseProvenance,
    },
    /// The write failed and both operation and reconnect fates were delegated.
    TransportLost {
        /// Concrete socket failure.
        error: SdkError,
        /// Crate-owned operation-fate result.
        operation_fate: RemoteOperationTransportFate,
        /// Crate-owned reconnect permit result.
        reconnect: RemoteReconnectPermitOutcome,
    },
}

/// Default quiet window for [`RemoteParticipantHandle::try_receive`].
///
/// Deliberately ONE steady-state transport receive window rather than a new
/// number of its own: that is the grain both transports already poll on, and it
/// is the shape consumers' drain loops were written against before a total
/// response deadline was layered above it. A pump that reports quiet after one
/// closed window is the behaviour they expect; the deadline above it is the
/// reply-owed protection they were never asking for.
pub const PARTICIPANT_PUMP_WINDOW: Duration = super::framing::IO_TIMEOUT;

/// Typed result of one decoded participant frame on the real receive path.
#[derive(Debug)]
pub enum RemoteParticipantInbound {
    /// The protocol crate correlated and applied a semantic response.
    Applied {
        /// Exact applied server value.
        value: ServerValue,
        /// Connection/attempt that delivered it.
        provenance: ParticipantResponseProvenance,
    },
    /// The protocol crate retained the response and aggregate unchanged.
    Refused {
        /// Exact refused server value.
        value: ServerValue,
        /// Closed crate refusal reason, including conservative ambiguity.
        reason: ClientInboundRefusalReason,
        /// Connection/attempt that delivered it.
        provenance: ParticipantResponseProvenance,
    },
    /// Server push decoded in the client direction; no correlation rule applies.
    Push {
        /// Exact pushed value.
        value: ServerPush,
        /// Connection/attempt that delivered it.
        provenance: ParticipantResponseProvenance,
    },
}

impl RemoteParticipantInbound {
    /// The record sequence the server assigned an admitted record, when this
    /// inbound is an APPLIED [`ServerValue::RecordCommitted`].
    ///
    /// This is the answer to a `RecordAdmission`, read off the exact wire value
    /// the protocol crate applied. It saves every caller destructuring the wire
    /// enum to reach the one number a record admission is asked for, without
    /// removing that value: [`Applied`](Self::Applied) still carries the whole
    /// `ServerValue`, so this is purely additive.
    ///
    /// `None` for everything else, and that includes a `RecordCommitted` the
    /// crate REFUSED. A refused commit carries a sequence on the wire while
    /// leaving the aggregate and its correlation untouched -- returning it here
    /// would report a commitment the crate deliberately declined to make. It is
    /// also `None` for a [`Push`](Self::Push), which is a delivery rather than
    /// a correlated response.
    #[must_use]
    pub const fn committed_delivery_seq(&self) -> Option<DeliverySeq> {
        match self {
            Self::Applied {
                value: ServerValue::RecordCommitted(committed),
                ..
            } => Some(committed.delivery_seq()),
            Self::Applied { .. } | Self::Refused { .. } | Self::Push { .. } => None,
        }
    }
}

pub(super) struct RemoteParticipantState<S> {
    pub(super) aggregate: Option<ClientParticipantAggregate>,
    pub(super) correlation: Option<ClientResponseCorrelation>,
    pub(super) reconnect_attempt: Option<liminal_protocol::client::ReconnectInProgressAttempt>,
    pub(super) store: S,
}

/// Remote participant entrypoint backed by protocol-crate state and canonical LPCR storage.
///
/// Records are deliberately not promised as generally successful: the reduced-B1
/// server surface fails fully authorized `RecordAdmission` and `Leave` closed until
/// live claim-frontier acquisition lands (`docs/design/LP-GAP-CLOSURE-GOAL.md:145`).
pub struct RemoteParticipantHandle<S> {
    pub(super) server_address: ServerAddress,
    pub(super) transport: Arc<dyn RemoteTransport>,
    pub(super) state: Mutex<RemoteParticipantState<S>>,
}

impl<S> fmt::Debug for RemoteParticipantHandle<S> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RemoteParticipantHandle")
            .field("server_address", &self.server_address)
            .finish_non_exhaustive()
    }
}

impl<S: ParticipantResumeStore> RemoteParticipantHandle<S> {
    /// Creates and durably checkpoints a fresh unbound participant.
    ///
    /// # Errors
    ///
    /// Returns a typed encode or storage error before the handle is exposed.
    pub fn new(config: &RemoteConfig, store: S) -> Result<Self, RemoteParticipantError> {
        Self::from_aggregate(config, store, ClientParticipantAggregate::new())
    }

    /// Decodes, validates, restores, and durably records crash testimony before exposure.
    ///
    /// # Errors
    ///
    /// Returns typed LPCR decode/restore, encode, or storage errors.
    pub fn restore(
        config: &RemoteConfig,
        store: S,
        canonical_lpcr: &[u8],
    ) -> Result<Self, RemoteParticipantError> {
        let record = ClientResumeRecord::decode_canonical(canonical_lpcr)
            .map_err(RemoteParticipantError::ResumeDecode)?;
        let aggregate = record
            .restore()
            .map_err(RemoteParticipantError::ResumeRestore)?;
        Self::from_aggregate(config, store, aggregate)
    }

    fn from_aggregate(
        config: &RemoteConfig,
        mut store: S,
        aggregate: ClientParticipantAggregate,
    ) -> Result<Self, RemoteParticipantError> {
        persist(&mut store, &aggregate)?;
        Ok(Self {
            server_address: config.server_address.clone(),
            transport: Arc::clone(&config.transport),
            state: Mutex::new(RemoteParticipantState {
                aggregate: Some(aggregate),
                correlation: None,
                reconnect_attempt: None,
                store,
            }),
        })
    }

    /// Runs `record_operation -> commit -> LPCR persist -> into_parts` exactly.
    ///
    /// # Errors
    ///
    /// Returns typed resume encoding or storage failures. A failed post-commit
    /// persistence leaves the handle unavailable and releases no authority.
    pub fn record_operation(
        &self,
        request: ClientRequest,
    ) -> Result<RemoteOperationRecordOutcome, RemoteParticipantError> {
        let mut state = self.state.lock();
        let aggregate = take_aggregate(&mut state)?;
        match liminal_protocol::client::record_operation(aggregate, request) {
            ClientOperationRecordDecision::Pending(pending) => {
                let commit = pending.commit();
                let record = commit
                    .resume_record()
                    .map_err(RemoteParticipantError::ResumeEncode)?;
                state
                    .store
                    .persist(&record.encode_canonical())
                    .map_err(RemoteParticipantError::Storage)?;
                let (aggregate, operation) = commit.into_parts();
                state.aggregate = Some(aggregate);
                Ok(RemoteOperationRecordOutcome::Recorded(
                    RemoteParticipantOperation {
                        operation,
                        durability: OperationDurability::WriteAhead,
                    },
                ))
            }
            ClientOperationRecordDecision::Continuous(continuous) => {
                let (aggregate, operation) = continuous.into_parts();
                state.aggregate = Some(aggregate);
                Ok(RemoteOperationRecordOutcome::Continuous(
                    RemoteParticipantOperation {
                        operation,
                        durability: OperationDurability::Continuous,
                    },
                ))
            }
            ClientOperationRecordDecision::Refused(refusal) => {
                let reason = refusal.reason();
                let (aggregate, request) = refusal.into_parts();
                state.aggregate = Some(aggregate);
                Ok(RemoteOperationRecordOutcome::Refused { request, reason })
            }
        }
    }

    /// Persists issued state, writes the exact operation, and retains correlation.
    ///
    /// # Errors
    ///
    /// Returns typed state, LPCR, or storage failures. Transport failures are
    /// returned as a typed outcome after crate fate delegation.
    pub fn send_operation(
        &self,
        operation: RemoteParticipantOperation,
    ) -> Result<RemoteParticipantSendOutcome, RemoteParticipantError> {
        let mut state = self.state.lock();
        let mut aggregate = take_aggregate(&mut state)?;
        if operation.durability == OperationDurability::WriteAhead {
            aggregate = persist_retaining(&mut state, aggregate)?;
        }
        let (request, correlation) = operation.operation.into_request();
        match self
            .transport
            .send_participant(&self.server_address, &request)
        {
            Ok(provenance) => {
                if operation.durability == OperationDurability::WriteAhead {
                    state.correlation = Some(correlation);
                }
                state.aggregate = Some(aggregate);
                Ok(RemoteParticipantSendOutcome::Sent { provenance })
            }
            Err(error) => {
                let operation_fate = if operation.durability == OperationDurability::WriteAhead {
                    record_operation_transport_fate(&mut state, aggregate, correlation)
                } else {
                    state.aggregate = Some(aggregate);
                    RemoteOperationTransportFate::NotOutstanding
                };
                let reconnect = record_connection_fate(&mut state)?;
                Ok(RemoteParticipantSendOutcome::TransportLost {
                    error,
                    operation_fate,
                    reconnect,
                })
            }
        }
    }

    /// Receives one real participant frame and delegates every `ServerValue` to the crate.
    ///
    /// # The contract, and why it is this one
    ///
    /// THIS IS THE REPLY-OWED DOOR. It blocks for up to the transport's full
    /// response deadline (60 s), because the caller it is written for has just
    /// sent a request and is waiting for the correlated answer — and there, a
    /// quiet connection means a slow server, not a dead one. Ending that wait
    /// early is the 2026-08-10 outage's client-side mechanism, so this method
    /// keeps the deadline unchanged and unconditionally.
    ///
    /// A consumer PUMPING an idle connection — looping to collect whatever the
    /// server pushes next, where silence is a normal state rather than a fault
    /// — must use [`receive_within`](Self::receive_within) or
    /// [`try_receive`](Self::try_receive) instead. That is not a preference: a
    /// drain loop built on this method waits out the full deadline on every
    /// quiet read, which is how a 30 s boot gate blows on a healthy server.
    ///
    /// The split is by CALLER INTENT and cannot be anything else. At a clean
    /// frame boundary with an empty buffer, a pump read and an outage-shaped
    /// reply-owed read are byte-for-byte identical states; only the caller
    /// knows which one it is making, so only the caller's choice of method can
    /// carry it. Inferring it from buffered bytes, or from whether an operation
    /// is outstanding, would silently shorten the deadline for some class of
    /// genuinely reply-owed read and re-open the outage for it.
    ///
    /// Pushed deliveries are at-least-once: the same
    /// `(conversation_id, delivery_seq)` may arrive more than once on one
    /// healthy connection, byte-identical each time — deduplicate on the pair
    /// (participant contract R-C3, amendment A3).
    ///
    /// # Errors
    ///
    /// Returns transport, direction, LPCR encoding, or storage failures.
    pub fn receive(&self) -> Result<RemoteParticipantInbound, RemoteParticipantError> {
        let frame = self
            .transport
            .receive_participant(&self.server_address)
            .map_err(RemoteParticipantError::Transport)?;
        self.classify_inbound(frame)
    }

    /// Receives one participant frame if one arrives within `budget`, reporting
    /// a quiet connection as `Ok(None)` instead of an error.
    ///
    /// THE PUMP DOOR — the lawful read for a consumer that is owed nothing.
    /// `Ok(None)` means "no frame within this window", which is a normal state
    /// on a healthy connection and never a fault; a real transport failure
    /// still returns `Err`, and a quiet window never surfaces a raw errno.
    ///
    /// `budget` is the CALLER'S bound and is spent across as many transport
    /// read windows as it takes. It never shortens anything else: a caller that
    /// uses this method to await a correlated answer simply names its own
    /// deadline, and passing one at or above the transport's 60 s response
    /// deadline reproduces [`receive`](Self::receive)'s patience with a typed
    /// silence at the end instead of an error.
    ///
    /// `Duration::ZERO` polls only what has already decoded, without arming a
    /// read. Bytes of a partly-arrived frame stay buffered across an
    /// `Ok(None)`, so a frame that was mid-flight when the budget expired is
    /// never lost — the next call resumes on it.
    ///
    /// # Errors
    ///
    /// Returns transport, direction, LPCR encoding, or storage failures. A
    /// quiet window is NOT one of them.
    pub fn receive_within(
        &self,
        budget: Duration,
    ) -> Result<Option<RemoteParticipantInbound>, RemoteParticipantError> {
        let Some(frame) = self
            .transport
            .receive_participant_within(&self.server_address, budget)
            .map_err(RemoteParticipantError::Transport)?
        else {
            return Ok(None);
        };
        self.classify_inbound(frame).map(Some)
    }

    /// One [`PARTICIPANT_PUMP_WINDOW`] of patience, then `Ok(None)`.
    ///
    /// The drain-loop convenience over [`receive_within`](Self::receive_within):
    /// a consumer that wants "give me the next frame, or tell me the connection
    /// is quiet" without choosing a number. Loop it until it answers `Ok(None)`
    /// and the backlog is drained.
    ///
    /// # Errors
    ///
    /// As [`receive_within`](Self::receive_within).
    pub fn try_receive(&self) -> Result<Option<RemoteParticipantInbound>, RemoteParticipantError> {
        self.receive_within(PARTICIPANT_PUMP_WINDOW)
    }

    /// Routes one decoded transport frame into the crate's inbound decisions.
    ///
    /// Shared by [`receive`](Self::receive) and
    /// [`receive_within`](Self::receive_within) so the two doors differ ONLY in
    /// how long they wait for a frame. Every correlation, application, and
    /// refusal rule below is reached identically by both — a pump read that
    /// does find a frame applies it exactly as a reply-owed read would.
    fn classify_inbound(
        &self,
        frame: ParticipantTransportFrame,
    ) -> Result<RemoteParticipantInbound, RemoteParticipantError> {
        let ParticipantTransportFrame { frame, provenance } = frame;
        match frame {
            ParticipantFrame::ServerPush(value) => {
                Ok(RemoteParticipantInbound::Push { value, provenance })
            }
            ParticipantFrame::ClientRequest(_) => {
                Err(RemoteParticipantError::InvalidInboundDirection)
            }
            ParticipantFrame::ServerValue(value) => self.apply_inbound(value, provenance),
        }
    }

    fn apply_inbound(
        &self,
        value: ServerValue,
        provenance: ParticipantResponseProvenance,
    ) -> Result<RemoteParticipantInbound, RemoteParticipantError> {
        let mut state = self.state.lock();
        let aggregate = take_aggregate(&mut state)?;
        if let Some(correlation) = state.correlation.take() {
            match decide_correlated_inbound(aggregate, value, correlation) {
                ClientCorrelatedInboundDecision::Applied(applied) => {
                    let (aggregate, value) = applied.into_parts();
                    let aggregate = persist_retaining(&mut state, aggregate)?;
                    state.aggregate = Some(aggregate);
                    Ok(RemoteParticipantInbound::Applied { value, provenance })
                }
                ClientCorrelatedInboundDecision::Refused(refusal) => {
                    let reason = refusal.reason();
                    let (aggregate, value, correlation) = refusal.into_parts();
                    state.aggregate = Some(aggregate);
                    state.correlation = Some(correlation);
                    Ok(RemoteParticipantInbound::Refused {
                        value,
                        reason,
                        provenance,
                    })
                }
            }
        } else {
            match decide_inbound(aggregate, value) {
                ClientInboundDecision::Applied(applied) => {
                    let (aggregate, value) = applied.into_parts();
                    let aggregate = persist_retaining(&mut state, aggregate)?;
                    state.aggregate = Some(aggregate);
                    Ok(RemoteParticipantInbound::Applied { value, provenance })
                }
                ClientInboundDecision::Refused(refusal) => {
                    let reason = refusal.reason();
                    let (aggregate, value) = refusal.into_parts();
                    state.aggregate = Some(aggregate);
                    Ok(RemoteParticipantInbound::Refused {
                        value,
                        reason,
                        provenance,
                    })
                }
            }
        }
    }
}

pub(super) fn take_aggregate<S>(
    state: &mut RemoteParticipantState<S>,
) -> Result<ClientParticipantAggregate, RemoteParticipantError> {
    state
        .aggregate
        .take()
        .ok_or(RemoteParticipantError::StateUnavailable)
}

pub(super) fn persist<S: ParticipantResumeStore>(
    store: &mut S,
    aggregate: &ClientParticipantAggregate,
) -> Result<(), RemoteParticipantError> {
    let record = aggregate
        .resume_record()
        .map_err(RemoteParticipantError::ResumeEncode)?;
    store
        .persist(&record.encode_canonical())
        .map_err(RemoteParticipantError::Storage)
}

/// Persists `aggregate`, returning it to the caller on success and RE-SEATING it
/// in `state` when encoding refused.
///
/// The two failure modes are not alike, and the difference is durability
/// ambiguity:
///
/// * [`RemoteParticipantError::Storage`] means the store was asked to commit
///   bytes and did not say it succeeded. Whether those bytes landed is unknown,
///   so no further authority may be released from this aggregate. The handle
///   is deliberately left bricked and the next call reports
///   [`StateUnavailable`](RemoteParticipantError::StateUnavailable) -- the
///   contract documented on that variant.
/// * [`RemoteParticipantError::ResumeEncode`] means `resume_record`, a pure
///   function of the aggregate, refused. Nothing was written and no authority
///   was released, so there is nothing ambiguous to protect. Dropping the
///   aggregate here converts a typed, catchable refusal into a permanently dead
///   participant.
///
/// The re-seat lives in this function rather than at each seam on purpose: the
/// SDK has ten `take_aggregate` -> persist -> re-seat sites, the `?` skips the
/// re-seat at every one of them, and a new seam would inherit the same bug.
/// Here it cannot be forgotten.
///
/// A caller that still needs the aggregate takes it back from the `Ok`; a
/// caller that does not re-seats it itself. On the `ResumeEncode` path the
/// aggregate is already seated, so callers must not seat it again.
pub(super) fn persist_retaining<S: ParticipantResumeStore>(
    state: &mut RemoteParticipantState<S>,
    aggregate: ClientParticipantAggregate,
) -> Result<ClientParticipantAggregate, RemoteParticipantError> {
    match aggregate.resume_record() {
        Ok(record) => state
            .store
            .persist(&record.encode_canonical())
            .map(|()| aggregate)
            .map_err(RemoteParticipantError::Storage),
        Err(error) => {
            state.aggregate = Some(aggregate);
            Err(RemoteParticipantError::ResumeEncode(error))
        }
    }
}

fn record_operation_transport_fate<S: ParticipantResumeStore>(
    state: &mut RemoteParticipantState<S>,
    aggregate: ClientParticipantAggregate,
    correlation: ClientResponseCorrelation,
) -> RemoteOperationTransportFate {
    match record_expected_operation_fate(
        aggregate,
        correlation,
        ExpectedOperationTransportFate::ResponseUnavailable,
    ) {
        liminal_protocol::client::ExpectedOperationFateDecision::Recorded {
            aggregate,
            request,
            ..
        } => {
            state.aggregate = Some(aggregate);
            RemoteOperationTransportFate::Recorded { request }
        }
        liminal_protocol::client::ExpectedOperationFateDecision::Refused {
            aggregate,
            correlation,
            reason: ExpectedOperationFateRefusalReason::DetachUsesReplayFate,
            ..
        } => match liminal_protocol::client::transport_fate(
            aggregate,
            correlation,
            liminal_protocol::client::DetachTransportFate::ResponseUnavailable,
        ) {
            liminal_protocol::client::DetachTransportFateDecision::Parked(applied) => {
                state.aggregate = Some(applied.into_aggregate());
                RemoteOperationTransportFate::DetachParked
            }
            liminal_protocol::client::DetachTransportFateDecision::Refused(refusal) => {
                let (aggregate, (correlation, _)) = refusal.into_parts();
                state.aggregate = Some(aggregate);
                state.correlation = Some(correlation);
                RemoteOperationTransportFate::Refused {
                    reason: ExpectedOperationFateRefusalReason::DetachUsesReplayFate,
                }
            }
        },
        liminal_protocol::client::ExpectedOperationFateDecision::Refused {
            aggregate,
            correlation,
            reason,
            ..
        } => {
            state.aggregate = Some(aggregate);
            state.correlation = Some(correlation);
            RemoteOperationTransportFate::Refused { reason }
        }
    }
}

pub(super) fn record_connection_fate<S: ParticipantResumeStore>(
    state: &mut RemoteParticipantState<S>,
) -> Result<RemoteReconnectPermitOutcome, RemoteParticipantError> {
    let aggregate = take_aggregate(state)?;
    let (aggregate, outcome) = match record_transport_fate(
        aggregate,
        liminal_protocol::client::EstablishedConnectionTransportFate::Lost,
    ) {
        ReconnectPermitDecision::Permitted {
            aggregate,
            permit,
            result,
        } => (
            aggregate,
            RemoteReconnectPermitOutcome::Permitted {
                permit: RemoteReconnectPermit { permit },
                result,
            },
        ),
        ReconnectPermitDecision::Refused(refusal) => {
            let reason = refusal.reason();
            let result = refusal.result();
            let (aggregate, _) = refusal.into_parts();
            (
                aggregate,
                RemoteReconnectPermitOutcome::Refused { reason, result },
            )
        }
    };
    let aggregate = persist_retaining(state, aggregate)?;
    state.aggregate = Some(aggregate);
    Ok(outcome)
}

#[cfg(test)]
mod tests;