Skip to main content

liminal_protocol/
client.rs

1//! Transport-agnostic client participant state and sealed effects.
2//!
3//! The client aggregate owns correlation, detach replay, and the durability
4//! barrier for one outstanding operation. The authorized round-3 order is
5//! commit-seal, persist the committed resume record, then release executable
6//! authority; pending has no durable form.
7//!
8//! # `LP-CLIENT-GOAL` API-shape rationale
9//!
10//! The Phase 1 brief requires authority-safe shapes rather than caller-owned
11//! state parts. The resulting public shape is deliberate:
12//!
13//! 1. Replay and reconnect transitions consume and return the root aggregate so
14//!    their facts are persisted atomically; standalone state-part recomposition
15//!    is not representable.
16//! 2. [`ReconnectAggregate`] has no public constructor because fresh detached
17//!    reconnect state would separate permit identity from participant facts.
18//! 3. [`recover_reconnect_permit`] exists because an unissued committed cold
19//!    record must release its permit once without making permits cloneable.
20//! 4. Only the commit seal exposes a durable record; pending has no encoder. The
21//!    authorized round-3 order is commit-seal, persist committed `LPCR`, release.
22//! 5. The retained name [`crate::outcome::ReconnectDelayResult`] carries an
23//!    event, never a delay: the brief explicitly supersedes timer scheduling.
24//! 6. A different retained detach is refused while live, but terminal or
25//!    attach-superseded replay yields only to an exact newer-generation detach.
26//! 7. Terminalized-detach fixture construction remains `cfg(test)` only; wire
27//!    authority construction is not weakened in production.
28//! 8. Detach recording is atomic with [`record_operation`], so no public raw
29//!    envelope-to-replay mint or second caller-owned persistence step exists.
30//! 9. [`DetachTransportFate`] is closed to response unavailability because this
31//!    protocol crate owns no socket, runtime, or transport handle.
32//! 10. [`DetachReplayOutcome`] is exhaustive so a generic server value cannot be
33//!     relabeled by a caller as one of the three terminal detach outcomes.
34//! 11. Reconnect fresh-event producers are separate typed functions rather than
35//!     a generic event-injection seam, limiting minting to the brief's classes.
36//! 12. [`recover_expected_operation`] is the one-use post-restore counterpart to
37//!     the pending-to-commit barrier; detach recovery also marks replay in flight.
38//! 13. Replay inspection returns `None` only for its named Empty state; terminal
39//!     payloads remain lossless and distinct.
40//! 14. There is no speculative persistence format. A pending-window crash means
41//!     the operation did not happen and restart may record it again.
42//! 15. `RecordAdmission` responses are always ambiguous because wire identity is
43//!     insufficient; `ObserverRecovery` compares its echoed list. As the M7
44//!     companion rule, both tokenless classes resolve as typed abandoned on every
45//!     restore and are never re-released. A later sealed-transport-context SDK leg
46//!     may add outbound attempt tokens and lift this restriction.
47//! 16. A crash or restore that destroys live authority mints a serialized,
48//!     take-once [`LostAuthorityTestimony`] with no public constructor
49//!     (`LP-CLIENT-GOAL` piece 4, r2, 2026-07-18). Every public fate or
50//!     recovery entry point consumes either a live one-use correlation, a
51//!     one-use sealed attempt authority, or the pending serialized testimony;
52//!     no publicly constructible process-fate value exists, so a fate that
53//!     consumes neither is unrepresentable at the API surface.
54//! 17. Detached bindings retain the attach secret because the complete client
55//!     record must remain capable of a later credential attach after restart.
56//! 18. Expected recovery and replay-start atomically share one detach issuance
57//!     bit, guaranteeing one first-send authority in either call order.
58//! 19. Both pending atoms use the retain-in-bytes encode shape (`LP-CLIENT-GOAL`
59//!     piece 2, r2, 2026-07-18): encoding an aggregate that holds a pending
60//!     testimony or abandonment emits bytes that carry the atom, so
61//!     encode-without-take loses nothing and no checkpoint window is refused.
62//!     The refuse-while-pending shape was rejected because piece 4 requires the
63//!     testimony to round-trip losslessly through the aggregate encoding.
64//! 20. Re-recording the retained detach envelope requires replay-status
65//!     compatibility with a fresh first send: only `Parked` admits; superseded,
66//!     Leave-superseded, terminal, and in-flight statuses refuse with typed
67//!     [`ClientOperationRecordRefusalReason::DetachReplayIncompatible`]
68//!     (r2, 2026-07-18), closing the round-4 door that revived expected-detach
69//!     authority over an inactive replay.
70//! 21. [`ClientParticipantAggregate::lost_credential_attach`] is a pure READ of
71//!     pending testimony, added because [`resolve_lost_operation_authority`] is
72//!     destructive by design (#195, 2026-08-16). A recovery driver that owns one
73//!     operation class had no way to ask whether the pending testimony was its
74//!     class without already having spent the take-once atom on a path that
75//!     still needed it — detach replay, or a tokenless abandonment. It mints
76//!     nothing, consumes nothing, and moves no state, so it adds no row to the
77//!     audit below and cannot widen any existing one; it only lets a caller
78//!     decline a case without destroying it.
79//!
80//! # Exhaustive constructible-state audit
81//!
82//! Every state accepted by restore or reachable through a public apply path is
83//! listed here. The exhaustive conservation property test mechanically covers
84//! the **live authority** and **typed consumption** columns across 610 applied
85//! paths from a 4-operation × 11-action alphabet through depth 7, attempting
86//! every action at every step: 1041 attempts end in the crate's typed refusal
87//! and 1748 are unrepresentable because the consumed one-use value does not
88//! exist at the type level. Every row below is either reachable-and-tested or
89//! refused-by-construction with the refusing type named.
90//!
91//! | Owned state | Restore/apply acceptance | Live authority | Typed consumption / exit |
92//! |---|---|---:|---|
93//! | Binding `Unbound` | new, restore | 0 | enrollment/attach → `Bound`; identity-bound requests refuse |
94//! | Binding `Bound` | enrollment/attach, restore | 0 | detach result → `Detached`; Leave/Retired → `Left` |
95//! | Binding `Detached` | detach result, restore | 0 | exact-secret attach → `Bound`; Leave/Retired → `Left` |
96//! | Binding `Left` | correlated Leave/Retired, restore | 0 | permanent; inbound/outbound return `AlreadyDead` |
97//! | Expected `None` | new, abort, consumed outcome/fate, restore | 0 | one [`record_operation`] admission |
98//! | Tokenless expected, live process only | record/commit/release | 0 or 1 | exact response remains conservative; fate consumes; every restore converts it into the durable `TokenlessAfterCrash` abandonment atom below |
99//! | Token-bearing non-detach, unissued | committed `LPCR`, restore | 0 | [`recover_expected_operation`] issues once |
100//! | Token-bearing non-detach, issued | release/recovery, restore | 1 live, or serialized testimony after restore | correlated outcome/fate consumes the live correlation; restore mints the take-once testimony consumed only by [`resolve_lost_operation_authority`] |
101//! | Expected detach + replay `Parked` | commit, live fate, testimony resolution, restore only when exact and unissued | 0 | recovery or replay start issues exactly one effect |
102//! | Expected detach + replay `InFlight` | release/start, restore only when exact and issued | 1 live, or serialized testimony after restore | correlated outcome/fate consumes the live correlation; restore mints the take-once testimony whose [`resolve_lost_operation_authority`] resolution parks exact-token replay |
103//! | Expected detach + replay `Empty`, `Superseded`, `LeaveSuperseded`, or terminal | never accepted, unreachable by construction | 0 | refused at restore by `ClientResumeRestoreError::ExpectedDetachActiveReplayMismatch` and in live code by [`ClientOperationRecordRefusalReason::DetachReplayIncompatible`], which closes the only door that could re-couple an expected detach to an inactive replay |
104//! | Active replay without exact expected detach | never accepted | 0 | typed `ActiveReplayExpectedDetachMismatch` restore refusal; the write side refuses to encode the same decoupling with `ClientResumeRecordEncodeError::DecoupledDetachReplay` (field 2026-08-07: a generation-skipping attach once stranded a replay in exactly this shape) |
105//! | Replay `Empty` | new, abort, restore without expected detach | 0 | admitted detach records `Parked` atomically |
106//! | Replay `Superseded` | authority-consuming matching attach, restore | 0 | old generation terminal; exact newer generation may replace; same-envelope re-record refused by construction (`DetachReplayIncompatible`) |
107//! | Replay `LeaveSuperseded` | authority-consuming matching durable Leave, restore | 0 | proves only that matching Leave/retirement superseded replay; public [`apply_leave_durable`] does **not** change binding to `Left`; same-envelope re-record refused by construction (`DetachReplayIncompatible`) |
108//! | Replay terminal (three exact payload arms) | authority-consuming exact outcome, restore | 0 | lossless terminal; exact newer-generation detach may replace; same-envelope re-record refused by construction (`DetachReplayIncompatible`) |
109//! | Restored-loss testimony, operation slot | minted only by validated restore of an issued token-bearing operation; carried losslessly by encode/decode | counts as the destroyed authority | consumed exactly once by [`resolve_lost_operation_authority`]; coupling refusals in both directions: a serialized atom without its issued state (or with the wrong kind) is refused by construction by `ClientResumeRestoreError::LostAuthorityTestimonyMismatch`, and every live consumption of the testified state is refused reachable-and-tested by the typed `LostAuthorityPending` reasons on [`decide_correlated_inbound`], [`record_expected_operation_fate`], [`transport_fate`], [`apply_attach`], [`apply_leave_durable`], and [`apply_detach_outcome`] |
110//! | Restored-loss testimony, reconnect slot | minted only by validated restore of an issued permit or in-progress attempt; carried losslessly by encode/decode | counts as the destroyed authority | consumed exactly once by [`resolve_lost_reconnect_authority`]; coupling refusals in both directions: a serialized atom without its matching machine state is refused by construction by `ClientResumeRestoreError::LostAuthorityTestimonyMismatch`, and prior-process handles are refused reachable-and-tested by `ReconnectAttemptRefusalReason::LostAuthorityPending` and `ReconnectAttemptFateRefusalReason::LostAuthorityPending` |
111//! | Pending `TokenlessAfterCrash` abandonment | minted by restore of a tokenless expected operation; carried losslessly by encode/decode with its issued flag | `was_issued` marks a destroyed authority | taken exactly once by [`ClientParticipantAggregate::take_restored_operation_abandonment`]; a second take observes nothing; coupling refusals in both directions: a serialized abandonment beside a tokenless expected operation is refused by construction by `ClientResumeRestoreError::PendingAbandonmentConflict`, and tokenless admission while pending is refused reachable-and-tested by [`ClientOperationRecordRefusalReason::AbandonmentPending`] |
112//! | Reconnect `Parked` | new/failure/loss resolution, restore | 0 | typed fresh event → permit |
113//! | Reconnect permit unissued | committed restore testimony | 0 | one [`recover_reconnect_permit`] issue |
114//! | Reconnect permit issued | event/recovery, restore | 1 live, or serialized testimony after restore | held permit → attempt; restore mints the take-once testimony consumed only by [`resolve_lost_reconnect_authority`] |
115//! | Reconnect attempt | permit redemption, restore | 1 live, or serialized testimony after restore | held fate → `Online`/`Parked`; restore mints the take-once testimony consumed only by [`resolve_lost_reconnect_authority`] |
116//! | Reconnect `Online` | successful fate, restore | 0 | later typed fresh event → permit |
117
118use crate::wire::{ClientRequest, Generation, ParticipantAckEnvelope};
119
120/// Coarse client binding state without exposing credential-bearing state parts.
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
122pub enum ClientBindingStatus {
123    /// No participant binding has been established.
124    Unbound,
125    /// A live binding and attach credential are retained.
126    Bound,
127    /// The most recently correlated detach completed.
128    Detached,
129    /// A correlated durable Leave permanently retired the participant.
130    Left,
131}
132
133#[derive(Clone, Debug, PartialEq, Eq)]
134pub(super) enum ClientBindingState {
135    Unbound,
136    Bound {
137        conversation_id: u64,
138        participant_id: u64,
139        generation: Generation,
140        attach_secret: crate::wire::AttachSecret,
141        binding_epoch: crate::wire::BindingEpoch,
142    },
143    Detached {
144        conversation_id: u64,
145        participant_id: u64,
146        generation: Generation,
147        attach_secret: crate::wire::AttachSecret,
148    },
149    Left {
150        conversation_id: u64,
151        participant_id: u64,
152        generation: Generation,
153    },
154}
155
156impl ClientBindingState {
157    const fn status(&self) -> ClientBindingStatus {
158        match self {
159            Self::Unbound => ClientBindingStatus::Unbound,
160            Self::Bound { .. } => ClientBindingStatus::Bound,
161            Self::Detached { .. } => ClientBindingStatus::Detached,
162            Self::Left { .. } => ClientBindingStatus::Left,
163        }
164    }
165
166    const fn is_left(&self) -> bool {
167        matches!(self, Self::Left { .. })
168    }
169
170    fn matches_ack(&self, request: &ParticipantAckEnvelope) -> bool {
171        match self {
172            Self::Bound {
173                conversation_id,
174                participant_id,
175                generation,
176                ..
177            } => {
178                *conversation_id == request.conversation_id
179                    && *participant_id == request.participant_id
180                    && *generation == request.capability_generation
181            }
182            Self::Unbound | Self::Detached { .. } | Self::Left { .. } => false,
183        }
184    }
185
186    fn accepts_request(&self, request: &ClientRequest) -> bool {
187        if self.is_left() {
188            return false;
189        }
190        match request {
191            ClientRequest::Enrollment(_) => matches!(self, Self::Unbound),
192            ClientRequest::CredentialAttach(value) => {
193                matches!(self, Self::Unbound)
194                    || self.matches_credential(
195                        value.conversation_id,
196                        value.participant_id,
197                        value.capability_generation,
198                        value.attach_secret,
199                        true,
200                    )
201            }
202            ClientRequest::Detach(value) => self.matches_identity(
203                value.conversation_id,
204                value.participant_id,
205                value.capability_generation,
206                false,
207            ),
208            ClientRequest::ParticipantAck(value) => self.matches_identity(
209                value.conversation_id,
210                value.participant_id,
211                value.capability_generation,
212                false,
213            ),
214            ClientRequest::Leave(value) => self.matches_credential(
215                value.conversation_id,
216                value.participant_id,
217                value.capability_generation,
218                value.attach_secret,
219                true,
220            ),
221            ClientRequest::MarkerAck(value) => self.matches_identity(
222                value.conversation_id,
223                value.participant_id,
224                value.capability_generation,
225                false,
226            ),
227            ClientRequest::RecordAdmission(value) => self.matches_identity(
228                value.conversation_id,
229                value.participant_id,
230                value.capability_generation,
231                false,
232            ),
233            ClientRequest::ObserverRecovery(_) => true,
234        }
235    }
236
237    fn matches_identity(
238        &self,
239        conversation: u64,
240        participant: u64,
241        generation_value: Generation,
242        allow_detached: bool,
243    ) -> bool {
244        match self {
245            Self::Bound {
246                conversation_id,
247                participant_id,
248                generation,
249                ..
250            } => {
251                (*conversation_id, *participant_id, *generation)
252                    == (conversation, participant, generation_value)
253            }
254            Self::Detached {
255                conversation_id,
256                participant_id,
257                generation,
258                ..
259            } if allow_detached => {
260                (*conversation_id, *participant_id, *generation)
261                    == (conversation, participant, generation_value)
262            }
263            Self::Unbound | Self::Detached { .. } | Self::Left { .. } => false,
264        }
265    }
266
267    fn matches_credential(
268        &self,
269        conversation: u64,
270        participant: u64,
271        generation_value: Generation,
272        presented_secret: crate::wire::AttachSecret,
273        allow_detached: bool,
274    ) -> bool {
275        match self {
276            Self::Bound { attach_secret, .. } => {
277                *attach_secret == presented_secret
278                    && self.matches_identity(
279                        conversation,
280                        participant,
281                        generation_value,
282                        allow_detached,
283                    )
284            }
285            Self::Detached { attach_secret, .. } if allow_detached => {
286                *attach_secret == presented_secret
287                    && self.matches_identity(conversation, participant, generation_value, true)
288            }
289            Self::Unbound | Self::Detached { .. } | Self::Left { .. } => false,
290        }
291    }
292}
293
294/// Closed description of which live process-local authority was destroyed.
295///
296/// The kind is descriptive only: no caller-suppliable kind value gates any
297/// authority transition (`LP-CLIENT-GOAL` piece 4, r2, 2026-07-18).
298#[derive(Clone, Copy, Debug, PartialEq, Eq)]
299pub enum LostAuthorityKind {
300    /// An issued operation's one-use response correlation did not survive the
301    /// process.
302    IssuedOperationCorrelation,
303    /// An in-flight detach transport attempt did not survive the process.
304    DetachTransportAttempt,
305    /// An issued reconnect attempt permit did not survive the process.
306    ReconnectPermit,
307    /// An in-progress reconnect attempt did not survive the process.
308    ReconnectAttempt,
309}
310
311/// Serialized, take-once testimony that live process-local authority was
312/// destroyed by crash or restore (`LP-CLIENT-GOAL` piece 4, r2, 2026-07-18).
313///
314/// The crate mints this atom exactly when a validated cold restore accepts a
315/// state whose live authority did not survive the process. It is persisted in
316/// the aggregate encoding, so encode/decode round-trips it losslessly, and it
317/// is consumed exactly once by the one recovery path that resolves the loss:
318/// [`resolve_lost_operation_authority`] for the operation domain and
319/// [`resolve_lost_reconnect_authority`] for the reconnect domain. It has no
320/// public constructor, so a fate value that consumes neither a live one-use
321/// correlation nor this testimony is unrepresentable at the API surface.
322///
323/// ```compile_fail
324/// use liminal_protocol::client::{LostAuthorityKind, LostAuthorityTestimony};
325/// let _forged = LostAuthorityTestimony {
326///     kind: LostAuthorityKind::ReconnectPermit,
327/// };
328/// ```
329#[derive(Debug, PartialEq, Eq)]
330pub struct LostAuthorityTestimony {
331    kind: LostAuthorityKind,
332}
333
334impl LostAuthorityTestimony {
335    pub(super) const fn mint(kind: LostAuthorityKind) -> Self {
336        Self { kind }
337    }
338
339    /// Reports which destroyed authority this testimony records.
340    #[must_use]
341    pub const fn kind(&self) -> LostAuthorityKind {
342        self.kind
343    }
344}
345
346#[derive(Debug, PartialEq, Eq)]
347pub(super) struct ExpectedOperationState {
348    pub(super) request: ClientRequest,
349    pub(super) issued: bool,
350    pub(super) authorization: u64,
351    pub(super) lost: Option<LostAuthorityTestimony>,
352}
353
354/// Why a persisted expected operation was deliberately not re-released.
355#[derive(Clone, Copy, Debug, PartialEq, Eq)]
356pub enum RestoredExpectedOperationAbandonmentReason {
357    /// The operation class has no outbound attempt token and cannot be proven
358    /// unsent after a crash.
359    TokenlessAfterCrash,
360}
361
362/// Typed restore resolution for an operation that cannot safely be re-issued.
363///
364/// The abandonment is durable (`LP-CLIENT-GOAL` piece 4, r2, 2026-07-18): it
365/// is serialized in the aggregate encoding, survives encode-without-take, and
366/// is consumed exactly once by
367/// [`ClientParticipantAggregate::take_restored_operation_abandonment`].
368#[derive(Debug, PartialEq, Eq)]
369pub struct RestoredExpectedOperationAbandonment {
370    pub(super) request: ClientRequest,
371    pub(super) reason: RestoredExpectedOperationAbandonmentReason,
372    pub(super) was_issued: bool,
373}
374
375impl RestoredExpectedOperationAbandonment {
376    /// Borrows the exact operation the restore boundary abandoned.
377    #[must_use]
378    pub const fn request(&self) -> &ClientRequest {
379        &self.request
380    }
381
382    /// Reports the closed abandonment reason.
383    #[must_use]
384    pub const fn reason(&self) -> RestoredExpectedOperationAbandonmentReason {
385        self.reason
386    }
387
388    /// Reports whether the abandoned operation had been issued before the
389    /// crash, meaning a live send authority was destroyed with the process.
390    #[must_use]
391    pub const fn was_issued(&self) -> bool {
392        self.was_issued
393    }
394
395    /// Consumes the resolution into the request callers may explicitly re-record.
396    #[must_use]
397    pub fn into_request(self) -> ClientRequest {
398        self.request
399    }
400}
401
402/// Non-cloneable client participant state shell.
403///
404/// Its expected operation, credential-bearing binding, replay request, and
405/// reconnect state are private so callers must delegate every decision. This
406/// brief-required root ownership prevents callers from recombining independently
407/// persisted authorities into a state the crate never validated.
408#[derive(Debug, PartialEq, Eq)]
409pub struct ClientParticipantAggregate {
410    pub(super) binding: ClientBindingState,
411    pub(super) expected: Option<ExpectedOperationState>,
412    pub(super) next_operation_authorization: u64,
413    pub(super) detach_replay: SdkDetachReplayAggregate,
414    pub(super) reconnect: ReconnectAggregate,
415    pub(super) restored_abandonment: Option<RestoredExpectedOperationAbandonment>,
416}
417
418impl ClientParticipantAggregate {
419    /// Creates a fresh unbound client aggregate.
420    #[must_use]
421    pub const fn new() -> Self {
422        Self {
423            binding: ClientBindingState::Unbound,
424            expected: None,
425            next_operation_authorization: 0,
426            detach_replay: SdkDetachReplayAggregate::new(),
427            reconnect: ReconnectAggregate::new(),
428            restored_abandonment: None,
429        }
430    }
431
432    /// Reports binding status without exposing credential-bearing state.
433    #[must_use]
434    pub const fn binding_status(&self) -> ClientBindingStatus {
435        self.binding.status()
436    }
437
438    /// Reports whether one write-ahead operation is outstanding.
439    #[must_use]
440    pub const fn has_expected_operation(&self) -> bool {
441        self.expected.is_some()
442    }
443
444    /// Borrows the detach replay aggregate for status inspection.
445    #[must_use]
446    pub const fn detach_replay(&self) -> &SdkDetachReplayAggregate {
447        &self.detach_replay
448    }
449
450    /// Borrows the reconnect aggregate for status inspection.
451    #[must_use]
452    pub const fn reconnect(&self) -> &ReconnectAggregate {
453        &self.reconnect
454    }
455
456    /// Takes the typed tokenless-operation resolution produced by cold restore.
457    ///
458    /// The expected slot is already empty when this value exists; taking the
459    /// event cannot mint or release executable authority. The abandonment is
460    /// durable until taken: encode-without-take retains it, and a second take
461    /// observes nothing (`LP-CLIENT-GOAL` piece 4, r2, 2026-07-18).
462    #[must_use]
463    pub const fn take_restored_operation_abandonment(
464        &mut self,
465    ) -> Option<RestoredExpectedOperationAbandonment> {
466        self.restored_abandonment.take()
467    }
468
469    /// Borrows the pending tokenless abandonment without consuming it.
470    #[must_use]
471    pub const fn restored_operation_abandonment(
472        &self,
473    ) -> Option<&RestoredExpectedOperationAbandonment> {
474        self.restored_abandonment.as_ref()
475    }
476
477    /// Borrows the pending operation-domain lost-authority testimony, if any.
478    ///
479    /// While this testimony is pending, every correlation-consuming operation
480    /// path refuses with a typed lost-authority reason; only
481    /// [`resolve_lost_operation_authority`] consumes it.
482    #[must_use]
483    pub const fn lost_operation_testimony(&self) -> Option<&LostAuthorityTestimony> {
484        match &self.expected {
485            Some(expected) => expected.lost.as_ref(),
486            None => None,
487        }
488    }
489
490    /// Borrows the pending reconnect-domain lost-authority testimony, if any.
491    ///
492    /// While this testimony is pending, permit redemption and attempt fates
493    /// refuse with a typed lost-authority reason; only
494    /// [`resolve_lost_reconnect_authority`] consumes it.
495    #[must_use]
496    pub const fn lost_reconnect_testimony(&self) -> Option<&LostAuthorityTestimony> {
497        self.reconnect.lost.as_ref()
498    }
499
500    /// Borrows the exact retained credential-attach envelope whose issued send
501    /// authority a restore testified destroyed.
502    ///
503    /// This is a DRIVER-SUPPORT READ and mints nothing: it releases no
504    /// authority, consumes no testimony, and moves no state. It exists because
505    /// [`resolve_lost_operation_authority`] is destructive — it consumes the
506    /// take-once testimony to hand back the request — so a recovery driver that
507    /// owns only ONE operation class has no way to discover whether the pending
508    /// testimony is its class without already having spent it on an operation
509    /// belonging to a different path. Detach's replay machinery and the
510    /// tokenless abandonment atom are exactly such paths, and a driver that
511    /// consumed their testimony to find out it should not have would destroy
512    /// the resolution they depend on (#195, 2026-08-16).
513    ///
514    /// `Some` requires all three facts together: the retained operation is a
515    /// [`ClientRequest::CredentialAttach`], it was ISSUED, and a lost-authority
516    /// testimony is pending against it. That triple is precisely the
517    /// killed-mid-attach orphan — the client's attach reached the server, the
518    /// answer that carries the rotated credential did not reach the client, and
519    /// the process died holding the retained envelope that can still be
520    /// re-presented inside the server's receipt window.
521    #[must_use]
522    pub const fn lost_credential_attach(&self) -> Option<&crate::wire::CredentialAttachRequest> {
523        match &self.expected {
524            Some(ExpectedOperationState {
525                request: ClientRequest::CredentialAttach(request),
526                issued: true,
527                lost: Some(_),
528                ..
529            }) => Some(request),
530            _ => None,
531        }
532    }
533
534    pub(super) const fn operation_loss_pending(&self) -> bool {
535        self.lost_operation_testimony().is_some()
536    }
537}
538
539impl Default for ClientParticipantAggregate {
540    fn default() -> Self {
541        Self::new()
542    }
543}
544
545mod barrier;
546mod correlation;
547mod inbound;
548mod reconnect;
549mod replay;
550mod resume;
551mod resume_decode;
552mod resume_encode;
553
554pub use barrier::*;
555pub use inbound::{
556    ClientCorrelatedInboundDecision, ClientCorrelatedInboundRefusal, ClientInboundApplied,
557    ClientInboundDecision, ClientInboundRefusal, ClientInboundRefusalReason,
558    decide_correlated_inbound, decide_inbound,
559};
560pub use reconnect::{
561    EstablishedConnectionTransportFate, ExplicitReconnectAction, LostReconnectAuthorityDecision,
562    ProvedOnlineTransition, ReconnectAggregate, ReconnectAttemptDecision, ReconnectAttemptFate,
563    ReconnectAttemptFateDecision, ReconnectAttemptFateRefusalReason, ReconnectAttemptPermit,
564    ReconnectAttemptRefusalReason, ReconnectFreshEvent, ReconnectInProgressAttempt,
565    ReconnectPermitDecision, ReconnectPermitRefusal, ReconnectPermitRefusalReason,
566    RecoveredReconnectPermitDecision, record_attempt_fate, record_explicit_reconnect,
567    record_online_transition, record_transport_fate, recover_reconnect_permit, redeem_attempt,
568    resolve_lost_reconnect_authority,
569};
570pub use replay::{
571    ApplyAttachDecision, ApplyDetachOutcomeDecision, ApplyLeaveDecision, DetachAuthorityRefused,
572    DetachReplayApplied, DetachReplayOutcome, DetachReplayRefusal, DetachReplayRefusalReason,
573    DetachReplayStatus, DetachReplayTerminal, DetachTransportAttempt,
574    DetachTransportAttemptDecision, DetachTransportFate, DetachTransportFateDecision,
575    SdkDetachReplayAggregate, apply_attach, apply_detach_outcome, apply_leave_durable,
576    transport_attempt_started, transport_fate,
577};
578pub use resume::{
579    ClientResumeRecord, ClientResumeRecordDecodeError, ClientResumeRecordEncodeError,
580    ClientResumeRecordSection, ClientResumeRestoreError,
581};
582
583#[cfg(test)]
584mod a5_settlement_correlation_tests;
585#[cfg(test)]
586mod authority_property_tests;
587#[cfg(test)]
588mod d1_flip_tests;
589#[cfg(test)]
590mod detach_authority_settlement_tests;
591#[cfg(test)]
592mod gen_skip_supersession_tests;
593#[cfg(test)]
594mod p0_62_stranded_handle_tests;
595#[cfg(test)]
596mod r2_tests;
597#[cfg(test)]
598mod resume_tests;
599#[cfg(test)]
600mod review_tests;
601#[cfg(test)]
602mod rider_tests;
603#[cfg(test)]
604mod round3_tests;
605#[cfg(test)]
606mod round4_tests;
607#[cfg(test)]
608mod tests;