polyc-state-connect 2026.8.3

State plane transport adapter: capability-specific Connect clients and server-trait glue mapping the generated wire types onto the polyc-state kernel — typed outcomes, per-call admission, and the conformance surface the authenticated shell proves itself against (docs/proposals/separated-planes.md).
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
//! The client half of the partition-journal surface.
//!
//! Callers speak the kernel's vocabulary in and out: a [`CommitJournalBatch`]
//! goes in, a [`Receipt`] or a [`StateError`] comes back. The generated types
//! never leave this crate, and neither does the transport's status code — a
//! caller reads the same variant the module refused with, whether it arrived as
//! an error detail or as a bare code the transport itself produced.
//!
//! Every request carries the active span's trace context, so a commit and the
//! decision that caused it land in one trace rather than two.

use connectrpc::client::{ClientConfig, ClientTransport};
use polyc_proto::proto::polychrome::state::v1 as pb;
use polyc_state::{
    error::StateError,
    id::{CommandId, PartitionId},
    journal::{
        self, CommitJournalBatch, DestroyPartition, ExcisePartitionRecords, GetJournalHead,
        GetJournalProof, GetJournalRoot, GetPartitionLastModified, JournalAttestation,
        JournalProof, JournalRange, ListJournalPartitions, PartitionLastModified, PartitionPage,
        QuarantinedRecord, ReadJournalRange, RepairOutcome, RepairPartition,
    },
    receipt::Receipt,
    revision::JournalHead,
};

use crate::{
    MAX_JOURNAL_WIRE_MESSAGE_BYTES,
    error::{TransportFallback, from_connect_error},
    journal::verify::{PartitionVerification, VerifyPartitionReplay},
    trace::{bounded_traced_options, bounded_traced_options_from_headers},
    wire::{DeclaredCall, Kernel},
};

/// A typed client for State's partition journal.
///
/// # Errors
///
/// Every method returns a [`StateError`]. When the listener refused with a
/// typed outcome, that is the exact variant it refused with. When the transport
/// refused before any handler ran — an oversized message, a spent deadline, a
/// draining or unreachable listener — the outcome is derived from the transport
/// code and keeps the retry class the design assigns it.
///
/// # Cancellation safety
///
/// Dropping a mutating future mid-await abandons the call, it does not undo it.
/// The batch may already have committed; what the drop destroys is only this
/// side's chance to hear the receipt. That is the same shape a lost
/// acknowledgement has and it has the same resolution: retry the identical
/// command identity and digest — never a fresh identity — and
/// [`JournalClient::receipt`] settles which it was. The read methods carry no
/// such risk: a dropped read loses an answer and no more.
pub struct JournalClient<T> {
    inner: pb::StateJournalServiceClient<T>,
}

impl<T> JournalClient<T>
where
    T: ClientTransport,
    <T::ResponseBody as connectrpc::http_body::Body>::Error: std::fmt::Display,
{
    /// Builds a client over `transport`, dialing whatever `config` names.
    ///
    /// The response bound matches the listener's own message bound for THIS
    /// family — [`MAX_JOURNAL_WIRE_MESSAGE_BYTES`], not the tight bound the
    /// other families carry — so a reply this build could not have accepted
    /// fails here rather than after an unbounded read, and a batch the kernel
    /// accepts is never refused by the caller's own transport first.
    pub fn new(transport: T, config: ClientConfig) -> Self {
        Self {
            inner: pb::StateJournalServiceClient::new(
                transport,
                config.with_default_max_message_size(MAX_JOURNAL_WIRE_MESSAGE_BYTES),
            ),
        }
    }

    /// Returns how a bare transport code should be read for a request of
    /// `attempted_bytes`.
    fn fallback(attempted_bytes: usize) -> TransportFallback {
        TransportFallback::new(
            journal::family(),
            MAX_JOURNAL_WIRE_MESSAGE_BYTES as u64,
            attempted_bytes as u64,
        )
    }

    /// Commits one atomic batch.
    ///
    /// # Errors
    ///
    /// Returns the typed outcome the batch earned; see the type-level note.
    /// Also [`StateError::BoundsExceeded`] naming the payload-bytes bound when
    /// the encoded request or its reply exceeds this protocol's wire bound —
    /// the transport refuses those before any handler runs, and the fallback
    /// reports them in the same vocabulary the module would have — and
    /// [`StateError::Malformed`] naming `receipt` when a listener answered
    /// successfully but carried none.
    ///
    /// # Cancellation safety
    ///
    /// Mutating: a dropped call may already have committed. Retry the same
    /// command identity, or retrieve its receipt.
    pub async fn commit(
        &self,
        declared: &DeclaredCall,
        batch: &CommitJournalBatch,
    ) -> Result<Receipt, StateError> {
        let (request, attempted) = Self::commit_request(declared, batch);
        let reply = self
            .inner
            .commit_journal_batch_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?
            .into_owned();
        receipt_of(reply.receipt)
    }

    /// Commits one batch with W3C headers captured by the caller before an
    /// isolated runtime boundary.
    ///
    /// Only the Control journal bridge needs this shape. It preserves the same
    /// method, State deadline, and body bounds as [`Self::commit`]; it merely
    /// avoids deriving the trace carrier from the bridge runtime's ambient span.
    ///
    /// The options stay spelled out at the dial rather than passed in, because
    /// the deadline guard reads this seam as source: it must see that this
    /// shape derives its transport budget from `declared` too. Only the request
    /// encoding is shared with [`Self::commit`]
    /// (`scripts/check_state_call_deadlines.py`).
    ///
    /// # Errors
    ///
    /// Returns the State transport or protocol error from the underlying commit.
    pub async fn commit_with_trace_headers(
        &self,
        declared: &DeclaredCall,
        batch: &CommitJournalBatch,
        headers: http::HeaderMap,
    ) -> Result<Receipt, StateError> {
        let (request, attempted) = Self::commit_request(declared, batch);
        let reply = self
            .inner
            .commit_journal_batch_with_options(
                request,
                bounded_traced_options_from_headers(declared, headers),
            )
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?
            .into_owned();
        receipt_of(reply.receipt)
    }

    /// Encodes one commit request and the attempted size its fallback reports.
    fn commit_request(
        declared: &DeclaredCall,
        batch: &CommitJournalBatch,
    ) -> (pb::CommitJournalBatchRequest, usize) {
        let request = pb::CommitJournalBatchRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            batch: buffa::MessageField::some(Kernel(batch).into()),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        (request, attempted)
    }

    /// Retrieves the durable receipt `partition` recorded under `command_id`.
    ///
    /// # Errors
    ///
    /// Returns the typed outcome the listener refused with. An identity that
    /// never committed to `partition` is [`None`], not an error.
    ///
    /// # Cancellation safety
    ///
    /// Read-only, and the resolution for every ambiguous commit above: dropping
    /// it changes nothing, and reissuing it is free.
    pub async fn receipt(
        &self,
        declared: &DeclaredCall,
        partition: &PartitionId,
        command_id: &CommandId,
    ) -> Result<Option<Receipt>, StateError> {
        let request = pb::GetJournalReceiptRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            command_id: command_id.as_str().to_owned(),
            partition: partition.as_str().to_owned(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_journal_receipt_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?
            .into_owned();
        reply
            .receipt
            .into_option()
            .map(|receipt| Kernel::<Receipt>::try_from(receipt).map(Kernel::into_inner))
            .transpose()
    }

    /// Reads one bounded range against an immutable prefix.
    ///
    /// # Errors
    ///
    /// Returns the typed outcome the listener refused with, including
    /// [`StateError::BoundsExceeded`] past the family's read bound.
    ///
    /// # Cancellation safety
    ///
    /// Read-only: dropping it loses the range and nothing else.
    pub async fn read_range(
        &self,
        declared: &DeclaredCall,
        range: &ReadJournalRange,
    ) -> Result<JournalRange, StateError> {
        let request = pb::ReadJournalRangeRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            range: buffa::MessageField::some(Kernel(range).into()),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .read_journal_range_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?
            .into_owned();
        Ok(Kernel::<JournalRange>::try_from(
            reply
                .range
                .into_option()
                .ok_or_else(|| missing("range", "a successful read carries its range"))?,
        )?
        .into_inner())
    }

    /// Returns one partition's current head.
    ///
    /// # Errors
    ///
    /// Returns the typed outcome the listener refused with, and
    /// [`StateError::Malformed`] naming `head` when a listener answered
    /// successfully but carried no head.
    ///
    /// # Cancellation safety
    ///
    /// Read-only: dropping it loses the answer and nothing else.
    pub async fn head(
        &self,
        declared: &DeclaredCall,
        request: &GetJournalHead,
    ) -> Result<JournalHead, StateError> {
        let request = pb::GetJournalHeadRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            partition: String::from(Kernel(request)),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_journal_head_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?
            .into_owned();
        Ok(Kernel::<JournalHead>::try_from(
            reply
                .head
                .into_option()
                .ok_or_else(|| missing("head", "a successful read carries its head"))?,
        )?
        .into_inner())
    }

    /// Lists one bounded page of partitions.
    ///
    /// # Errors
    ///
    /// Returns the typed outcome the listener refused with, including
    /// [`StateError::BoundsExceeded`] past the family's page bound.
    ///
    /// # Cancellation safety
    ///
    /// Read-only: dropping it loses the page and nothing else.
    pub async fn list_partitions(
        &self,
        declared: &DeclaredCall,
        request: &ListJournalPartitions,
    ) -> Result<PartitionPage, StateError> {
        let request = pb::ListJournalPartitionsRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            start_after: request
                .start_after()
                .map(|partition| partition.as_str().to_owned()),
            limit: request.limit(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .list_journal_partitions_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?
            .into_owned();
        Ok(Kernel::<PartitionPage>::try_from(
            reply
                .page
                .into_option()
                .ok_or_else(|| missing("page", "a successful listing carries its page"))?,
        )?
        .into_inner())
    }

    /// Replays one partition and reports whether its tamper-evidence holds.
    ///
    /// A partition that does not verify is a
    /// [`PartitionVerification::Violation`], not an error: the listener
    /// answered, and the answer is bad news. An error here means the listener
    /// could not answer at all, which a caller must never report as a healthy
    /// log.
    ///
    /// # Errors
    ///
    /// Returns the typed outcome the listener refused with, and
    /// [`StateError::Malformed`] naming `verdict` when a listener answered
    /// successfully but reached no verdict.
    ///
    /// # Cancellation safety
    ///
    /// Read-only: dropping it loses the verdict and nothing else.
    pub async fn verify_replay(
        &self,
        declared: &DeclaredCall,
        request: &VerifyPartitionReplay,
    ) -> Result<PartitionVerification, StateError> {
        let request = pb::VerifyPartitionReplayRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            partition: request.partition().as_str().to_owned(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .verify_partition_replay_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?
            .into_owned();
        Ok(Kernel::<PartitionVerification>::try_from(reply)?.into_inner())
    }

    /// Returns when one partition's storage last changed.
    ///
    /// The operational read a retention policy's idle axis is decided on. A
    /// partition the module holds nothing for reports
    /// [`PartitionLastModified::at_ms`] of [`None`], which a caller reads as
    /// "nothing to say" rather than as a very old time.
    ///
    /// # Errors
    ///
    /// Returns the typed outcome the listener refused with, including
    /// [`StateError::Malformed`] naming `partition` for a name the module could
    /// not address.
    ///
    /// # Cancellation safety
    ///
    /// Read-only: dropping it loses the answer and nothing else.
    pub async fn last_modified(
        &self,
        declared: &DeclaredCall,
        request: &GetPartitionLastModified,
    ) -> Result<PartitionLastModified, StateError> {
        let request = pb::GetPartitionLastModifiedRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            partition: request.partition().as_str().to_owned(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_partition_last_modified_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?
            .into_owned();
        Ok(PartitionLastModified::new(reply.at_ms))
    }

    /// Returns one partition's current signed root.
    ///
    /// # Errors
    ///
    /// Returns the typed outcome the listener refused with, and
    /// [`StateError::Malformed`] naming `attestation` when a listener answered
    /// successfully but carried no attestation.
    ///
    /// # Cancellation safety
    ///
    /// Read-only: dropping it loses the attestation and nothing else.
    pub async fn root(
        &self,
        declared: &DeclaredCall,
        request: &GetJournalRoot,
    ) -> Result<JournalAttestation, StateError> {
        let request = pb::GetJournalRootRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            partition: String::from(Kernel(request)),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_journal_root_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?
            .into_owned();
        Ok(Kernel::<JournalAttestation>::try_from(
            reply.attestation.into_option().ok_or_else(|| {
                missing("attestation", "a successful read carries its attestation")
            })?,
        )?
        .into_inner())
    }

    /// Returns one record's inclusion proof.
    ///
    /// # Errors
    ///
    /// Returns the typed outcome the listener refused with, and
    /// [`StateError::Malformed`] naming `proof` when a listener answered
    /// successfully but carried no proof.
    ///
    /// # Cancellation safety
    ///
    /// Read-only: dropping it loses the proof and nothing else.
    pub async fn proof(
        &self,
        declared: &DeclaredCall,
        request: &GetJournalProof,
    ) -> Result<JournalProof, StateError> {
        let request = pb::GetJournalProofRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            partition: request.partition().as_str().to_owned(),
            position: request.position().get(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_journal_proof_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?
            .into_owned();
        Ok(Kernel::<JournalProof>::try_from(
            reply
                .proof
                .into_option()
                .ok_or_else(|| missing("proof", "a successful read carries its proof"))?,
        )?
        .into_inner())
    }

    /// Destroys one partition.
    ///
    /// # Errors
    ///
    /// Returns the typed outcome the command earned, and
    /// [`StateError::Malformed`] naming `receipt` when a listener answered
    /// successfully but carried none.
    ///
    /// # Cancellation safety
    ///
    /// Mutating and irreversible: a dropped call may already have destroyed the
    /// partition. Retry the same command identity, which is a replay.
    pub async fn destroy(
        &self,
        declared: &DeclaredCall,
        command: &DestroyPartition,
    ) -> Result<Receipt, StateError> {
        let request = pb::DestroyJournalPartitionRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            command: buffa::MessageField::some(Kernel(command).into()),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .destroy_journal_partition_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?
            .into_owned();
        receipt_of(reply.receipt)
    }

    /// Physically destroys one exact incarnation and leaves its durable hold
    /// active for a cross-family erasure.
    ///
    /// # Errors
    ///
    /// Returns the typed outcome the command earned. A dropped or lost reply
    /// may already have staged the destruction; retry the identical command.
    pub async fn stage_destroy(
        &self,
        declared: &DeclaredCall,
        command: &DestroyPartition,
    ) -> Result<(), StateError> {
        let request = pb::StageJournalDestructionRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            command: buffa::MessageField::some(Kernel(command).into()),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        self.inner
            .stage_journal_destruction_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?;
        Ok(())
    }

    /// Records a staged destruction and releases its durable hold.
    ///
    /// # Errors
    ///
    /// Returns the typed outcome the command earned, and
    /// [`StateError::Malformed`] when the stage is absent or a successful
    /// reply carries no receipt.
    pub async fn complete_destroy(
        &self,
        declared: &DeclaredCall,
        command: &DestroyPartition,
    ) -> Result<Receipt, StateError> {
        let request = pb::CompleteJournalDestructionRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            command: buffa::MessageField::some(Kernel(command).into()),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .complete_journal_destruction_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?
            .into_owned();
        receipt_of(reply.receipt)
    }

    /// Rewrites the named records of one partition in place.
    ///
    /// # Errors
    ///
    /// Returns the typed outcome the command earned, and
    /// [`StateError::Malformed`] naming `receipt` when a listener answered
    /// successfully but carried none.
    ///
    /// # Cancellation safety
    ///
    /// Mutating and irreversible: a dropped call may already have rewritten the
    /// partition. Retry the same command identity, which is a replay.
    pub async fn excise(
        &self,
        declared: &DeclaredCall,
        command: &ExcisePartitionRecords,
    ) -> Result<Receipt, StateError> {
        let request = pb::ExciseJournalRecordsRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            command: buffa::MessageField::some(Kernel(command).into()),
            decisions: command
                .decisions()
                .iter()
                .map(|decision| pb::RecordDecision::from(Kernel(decision)))
                .collect(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .excise_journal_records_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?
            .into_owned();
        receipt_of(reply.receipt)
    }

    /// Repairs one partition, quarantining every record it cannot read.
    ///
    /// # Errors
    ///
    /// Returns the typed outcome the command earned, and
    /// [`StateError::Malformed`] naming `receipt` when a listener answered
    /// successfully but carried none.
    ///
    /// # Cancellation safety
    ///
    /// Mutating: a dropped call may already have repaired the partition. Retry
    /// the same command identity, which is a replay.
    pub async fn repair(
        &self,
        declared: &DeclaredCall,
        command: &RepairPartition,
    ) -> Result<RepairOutcome, StateError> {
        let request = pb::RepairJournalPartitionRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            command: buffa::MessageField::some(Kernel(command).into()),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .repair_journal_partition_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|e| from_connect_error(&e, &Self::fallback(attempted)))?
            .into_owned();
        let quarantined = reply
            .quarantined
            .into_iter()
            .map(|record| Kernel::<QuarantinedRecord>::from(record).into_inner())
            .collect();
        Ok(RepairOutcome::new(receipt_of(reply.receipt)?, quarantined))
    }
}

/// Reads the receipt a successful mutation carries.
fn receipt_of(receipt: impl Into<Option<pb::Receipt>>) -> Result<Receipt, StateError> {
    Ok(Kernel::<Receipt>::try_from(
        receipt
            .into()
            .ok_or_else(|| missing("receipt", "a committed command carries its receipt"))?,
    )?
    .into_inner())
}

/// Builds the outcome for a reply field the listener was required to set.
fn missing(field: &str, reason: &str) -> StateError {
    StateError::Malformed {
        field: field.to_owned(),
        reason: reason.to_owned(),
    }
}