minerva 0.2.0

Causal ordering for distributed systems
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
//! Old-epoch judgment and its declaration-frozen projection.

extern crate alloc;

use alloc::boxed::Box;
use alloc::vec::Vec;

use crate::metis::dot::{Dot, RawDot};
use crate::metis::{
    Adopted, Cut, DotSet, Dotted, Metatheses, Recension, RefoundMap, Rhapsody, VersionVector,
};

use super::{Consigned, EpochAddress, SealedEpoch};

/// Structural accounting for one open epoch shadow.
///
/// Enabled by the `instrumentation` feature. Counts cover every variable-size
/// shadow component without exposing its mutation-capable stores.
#[cfg(feature = "instrumentation")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct EpochShadowProfile {
    /// The carried old-world text plane.
    pub text: crate::metis::RhapsodyProfile,
    /// Station rows in the carried text context.
    pub text_context_stations: usize,
    /// Sparse entries in the carried text context.
    pub text_context_exceptions: usize,
    /// Surviving carried movement testimonies.
    pub testimonies: usize,
    /// Station rows in the carried movement context.
    pub movement_context_stations: usize,
    /// Sparse entries in the carried movement context.
    pub movement_context_exceptions: usize,
    /// Explicit old-to-new identities in the frozen translation map.
    pub mapped_dots: usize,
    /// Station ceilings in the frozen translation map.
    pub mapped_ceiling_stations: usize,
    /// Station live counts in the frozen translation map.
    pub mapped_live_stations: usize,
    /// The maintained old-world decision surface.
    pub recension: crate::metis::RecensionProfile,
    /// Cached projected identities, zero when the lazy projection is absent.
    pub projected_dots: usize,
    /// Allocated cached-projection slots.
    pub projected_capacity: usize,
}

/// A projection of the shadow's effective reading into the new identity
/// plane.
///
/// This is a value, not a mutable sequence store. Out-of-order movement can
/// re-decide an earlier outcome, so materializing each intermediate outcome
/// as immutable loci would violate the rule that one dot names one write.
/// Consumers read this sequence or freeze it at the seal.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EpochProjection {
    epoch: EpochAddress,
    order: Vec<Dot>,
}

impl EpochProjection {
    /// The winning declaration that names the projected epoch.
    #[must_use]
    pub const fn epoch(&self) -> EpochAddress {
        self.epoch
    }

    /// Effective visible order under the frozen identity map.
    #[must_use]
    pub fn order(&self) -> &[Dot] {
        &self.order
    }
}

/// A delta attempts to introduce a live identity from the sealed stratum
/// that the frozen map deliberately swept.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[error("epoch shadow cannot project swept identity {dot}")]
pub struct SweptIdentity {
    /// The old-epoch identity with no image in the frozen map.
    pub dot: Dot,
}

/// The next generation's opening base pair, consigned by a sealed
/// window (PRD 0024 stage four's document-plane half, ruling R-50).
///
/// The text pair carries the old epoch's complete final reading, re-spelled
/// through the declaration-frozen map. Window-born survivors are woven at
/// their judged places; window-deleted cut-live elements stay as order
/// tombstones. Its context holds the image of every event dot either plane
/// delivered, so the new generation's floors are born gap-free. The movement
/// pair starts empty under the same translated context: every window move's
/// outcome is already baked into the text spelling, and the new epoch's record
/// begins fresh, exactly as `refound` sweeps it.
///
/// The retired map rides along because the caller's half of stage four
/// still needs it: external references (cursors, held mark identities,
/// content hashes) re-translate per epoch through this map, and its
/// retention is caller policy (PRD 0024 R7).
#[derive(Debug)]
pub struct EpochConsignment {
    text: Dotted<Rhapsody>,
    moves: Dotted<Metatheses>,
    map: RefoundMap,
}

impl EpochConsignment {
    /// The next generation's opening text pair.
    #[must_use]
    pub const fn text(&self) -> &Dotted<Rhapsody> {
        &self.text
    }

    /// The next generation's opening movement pair: an empty record under
    /// the translated window context.
    #[must_use]
    pub const fn moves(&self) -> &Dotted<Metatheses> {
        &self.moves
    }

    /// The retired dot map, the caller's translation seam for external
    /// references (retention is caller policy, PRD 0024 R7).
    #[must_use]
    pub const fn map(&self) -> &RefoundMap {
        &self.map
    }

    /// Surrenders the base pair and the retired map.
    #[must_use]
    pub fn into_parts(self) -> (Dotted<Rhapsody>, Dotted<Metatheses>, RefoundMap) {
        (self.text, self.moves, self.map)
    }
}

/// The seal consignment's refusals.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum EpochConsignmentError {
    /// The seal witness names a different epoch than this shadow judges.
    #[error("seal witness names epoch {sealed:?}, not this shadow's {shadow:?}")]
    ForeignSeal {
        /// The epoch the presented seal actually closed.
        sealed: EpochAddress,
        /// The epoch this shadow was opened for.
        shadow: EpochAddress,
    },
    /// The shadow's contexts plus the seal's own protocol record do not
    /// cover the sealed join: a delta the seal proves delivered
    /// everywhere never reached this shadow. Folding anyway would drop
    /// that content silently and permanently, because the sealed lineage
    /// afterwards answers the missing dot as an already-delivered
    /// duplicate; the door refuses instead, naming the first uncovered
    /// dot as evidence.
    #[error("the shadow is missing sealed-window delivery {dot}")]
    Incomplete {
        /// The first missing slot, one past the carried coverage for its
        /// station: a synthesized coordinate ([`RawDot`]), not a held
        /// identity.
        dot: RawDot,
    },
    /// The shadow carries an identity above the sealed join: traffic the
    /// seal never proved delivered everywhere, so folding it would
    /// diverge this replica's consignment from the fleet's.
    #[error("the shadow carries post-seal identity {dot}")]
    BeyondSeal {
        /// The first carried high water above the sealed join: a
        /// per-station reading ([`RawDot`]), deliberately not a per-dot
        /// scan.
        dot: RawDot,
    },
    /// The window's final reading carries an unplaced birth or a pending
    /// movement, state a lawfully sealed window cannot contain (every mint
    /// rides its minter's own floor into the adoption join, so a complete
    /// window places every birth and supports every testimony). The fold
    /// refuses rather than guessing a place for it.
    #[error("the sealed window carries unfoldable state at {dot}")]
    Unfoldable {
        /// The first unplaced birth or pending testimony.
        dot: Dot,
    },
}

/// A candidate sealed stratum failed structural validation at the adopted
/// declaration's cut.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum EpochStratumError {
    /// The consumed pair contexts do not account for a dot the adopted cut
    /// says was delivered everywhere.
    #[error("epoch stratum is incomplete at {dot}")]
    Incomplete {
        /// The first cut identity missing from both causal-pair contexts.
        dot: Dot,
    },
    /// State carries an identity above the declaration cut. It belongs to
    /// the open window and must enter through the shadow delivery path.
    #[error("epoch stratum identity {dot} lies above the adopted cut")]
    BeyondCut {
        /// The first above-cut identity in ascending pair order.
        dot: Dot,
    },
    /// The bounded state is not a causally closed, foldable stratum.
    #[error("epoch stratum is not sealed at {dot}")]
    Unsealed {
        /// The first unreachable text dot or pending movement testimony.
        dot: Dot,
    },
}

/// State proven structurally bounded at an adopted winner's declaration cut.
///
/// Construction consumes both old causal pairs. Every carried context,
/// woven text identity, and movement testimony must be at or below the cut;
/// above-cut state belongs to the window. The fold then verifies reachability
/// and movement support and freezes the one map all replicas derive from the
/// witnessed stratum.
///
/// Construction is *fused* (the S270 boundary-latency slice): the decision
/// surface is derived once and serves three consumers that each replayed
/// the pair for themselves before, the re-foundation fold (whose
/// [`pristine`](Self::pristine) output construction now retains instead of
/// discarding), the shadow's maintained recension, and the frozen
/// projection. Every product is a pure function of the consumed pairs, so
/// the fusion owes and keeps exact agreement with the separate
/// derivations.
#[derive(Debug)]
pub struct EpochStratum {
    epoch: EpochAddress,
    text: Dotted<Rhapsody>,
    moves: Dotted<Metatheses>,
    pristine: Rhapsody,
    map: RefoundMap,
    recension: Recension,
    projection: Option<EpochProjection>,
}

impl EpochStratum {
    /// Validates and consumes the adopted declaration's exact fold input.
    ///
    /// # Errors
    ///
    /// Returns [`EpochStratumError::Incomplete`] when the pair contexts do
    /// not jointly cover the declaration cut,
    /// [`EpochStratumError::BeyondCut`] when either pair carries an identity
    /// above it, and
    /// [`EpochStratumError::Unsealed`] when the fold finds unreachable text
    /// or a pending movement.
    ///
    /// # Panics
    ///
    /// Only if an internal invariant is broken: the frozen map and the
    /// projection derive from the one recension this constructor builds,
    /// so every projected identity has a map image by construction.
    pub fn new(
        adopted: &Adopted,
        text: Dotted<Rhapsody>,
        moves: Dotted<Metatheses>,
    ) -> Result<Self, EpochStratumError> {
        let cut = adopted.cut().as_vector();
        let coverage = text.context().merge(moves.context());
        if let Some(dot) = adopted.cut().to_have_set().difference(&coverage).next() {
            return Err(EpochStratumError::Incomplete { dot });
        }
        let beyond = text
            .context()
            .dots()
            .chain(text.store().woven().dots())
            .chain(moves.context().dots())
            .chain(moves.store().iter().map(|(dot, _)| dot))
            .find(|dot| dot.counter() > cut.get(dot.station()));
        if let Some(dot) = beyond {
            return Err(EpochStratumError::BeyondCut { dot });
        }

        let recension = text.store().recension(moves.store());
        let refounded = text
            .store()
            .refound_recension(&recension)
            .map_err(|error| EpochStratumError::Unsealed { dot: error.dot })?;
        let (pristine, mut map) = refounded.into_parts();
        map.bind_cut(adopted.cut());
        let projection = EpochShadow::project(adopted.address(), &map, &recension)
            .expect("the frozen map and the projection derive from one recension");
        Ok(Self {
            epoch: adopted.address(),
            text,
            moves,
            pristine,
            map,
            recension,
            projection: Some(projection),
        })
    }

    /// The pristine re-founded core: live content only, born coalesced,
    /// the next generation's native opening plane. Retained by the fused
    /// construction so an adopter does not run the re-foundation fold a
    /// second time for the store the stratum already derived. A borrow,
    /// for reads that precede the transition (the allocator basis is this
    /// store's own per-station high water);
    /// [`into_transition`](Self::into_transition) moves the store itself
    /// out. Exactly equal to [`Rhapsody::refound`]'s store over the same
    /// pairs (the fusion's agreement law).
    #[must_use]
    pub const fn pristine(&self) -> &Rhapsody {
        &self.pristine
    }

    /// Opens the epoch transition, consuming the stratum: the one
    /// validated fold input moves both of its products out exactly once,
    /// the pristine native plane and the old window's judgment shadow
    /// (S272, the consumer-requested ownership form of the S270 fusion).
    ///
    /// Ownership transfer makes the old pairs' one-window lifetime explicit.
    /// The pair return removes the S270 recipe's remaining hazard: no door
    /// discards the pristine core. The native plane therefore always reaches
    /// the transition site, and an adopter never clones or re-runs the
    /// re-foundation fold for a store the stratum already derived. What to
    /// retain is still the caller's decision at that site, as any Rust move
    /// is; what the type rules out is needing the native plane after a door
    /// already destroyed it.
    #[must_use]
    pub fn into_transition(self) -> EpochTransition {
        EpochTransition {
            native: self.pristine,
            shadow: EpochShadow {
                epoch: self.epoch,
                text: self.text,
                moves: self.moves,
                map: self.map,
                recension: self.recension,
                projection: self.projection,
            },
        }
    }
}

/// The two products of one validated, adopted stratum, moved out exactly
/// once by [`EpochStratum::into_transition`].
///
/// The native plane is the re-founded core the caller owns from here on;
/// the shadow judges the window's old-addressed traffic. Public fields:
/// both halves arrive together at the transition site under their own
/// names, so retaining or dropping either is decided there, never by a
/// door that pre-discarded one (the S270 shape this replaces).
#[derive(Debug)]
pub struct EpochTransition {
    /// The pristine re-founded core: the next generation's native opening
    /// plane (its per-station high water is the caller's native allocator
    /// basis).
    pub native: Rhapsody,
    /// The old window's judgment context: deliver the window's
    /// old-addressed traffic here, then seal and consign.
    pub shadow: EpochShadow,
}

/// One open epoch's old-world judgment context.
///
/// The shadow owns both causal pairs so removal evidence and the movement
/// record cannot drift apart from the topology they judge. The map is frozen
/// at declaration. `Recension` is the maintained decision form; each fold is
/// checked at the input boundary before it mutates the carried pairs.
#[derive(Debug)]
pub struct EpochShadow {
    epoch: EpochAddress,
    text: Dotted<Rhapsody>,
    moves: Dotted<Metatheses>,
    map: RefoundMap,
    recension: Recension,
    projection: Option<EpochProjection>,
}

impl EpochShadow {
    /// Folds one old-addressed text delta and refreshes the exact projection.
    ///
    /// A delta may delete old content or birth content above the frozen cut.
    /// It may not introduce a novel identity below the frozen ceiling: that
    /// would contradict the declaration witness, so the fold rejects it
    /// before mutation. A covered replay of a swept insertion is lawful and
    /// absorbs under the pair's survivor law.
    ///
    /// # Errors
    ///
    /// Returns [`SweptIdentity`] when the delta introduces a novel live dot
    /// below the declaration-frozen ceiling.
    pub fn deliver_text(&mut self, delta: &Dotted<Rhapsody>) -> Result<(), SweptIdentity> {
        if let Some(dot) = Self::swept_text(&self.map, &self.text, delta) {
            return Err(SweptIdentity { dot });
        }
        self.text.merge_from(delta);
        self.refresh();
        Ok(())
    }

    /// Folds one old-addressed movement delta and refreshes the exact
    /// projection. The old topology and complete surviving testimony set
    /// decide it together, so out-of-order arrivals may lawfully re-decide
    /// earlier outcomes.
    ///
    /// # Errors
    ///
    /// Returns [`SweptIdentity`] when the delta introduces a novel testimony
    /// at or below the declaration cut.
    pub fn deliver_moves(&mut self, delta: &Dotted<Metatheses>) -> Result<(), SweptIdentity> {
        if let Some(dot) = Self::swept_moves(&self.map, &self.moves, delta) {
            return Err(SweptIdentity { dot });
        }
        self.moves.merge_from(delta);
        self.refresh();
        Ok(())
    }

    /// Folds a batch of old-addressed text deltas with one maintenance
    /// refresh at the end, instead of one per delivery.
    ///
    /// Observationally this door is [`deliver_text`](Self::deliver_text) in a
    /// loop, stopped at the first refusal: each delta is validated at its own
    /// fold point (against the context as the earlier batch entries left it),
    /// the deltas before a refused one stay folded, and the refused one and
    /// its successors do not enter. Cost is the one difference, under the
    /// shell discipline's rule. The door brings the maintained decision
    /// surface and the projection current once per batch. An adoption
    /// replaying a window's already-delivered traffic therefore pays its
    /// merges plus one collation, not one collation per delta. The S270 phase
    /// split measured that per-delivery term as the adoption half's dominant
    /// cost.
    ///
    /// # Errors
    ///
    /// Returns [`SweptIdentity`] for the first delta that introduces a
    /// novel live dot below the declaration-frozen ceiling; the surface is
    /// refreshed over everything folded before it.
    pub fn deliver_text_batch<'a, I>(&mut self, deltas: I) -> Result<(), SweptIdentity>
    where
        I: IntoIterator<Item = &'a Dotted<Rhapsody>>,
    {
        let mut folded = false;
        for delta in deltas {
            if let Some(dot) = Self::swept_text(&self.map, &self.text, delta) {
                if folded {
                    self.refresh();
                }
                return Err(SweptIdentity { dot });
            }
            self.text.merge_from(delta);
            folded = true;
        }
        if folded {
            self.refresh();
        }
        Ok(())
    }

    /// Folds a batch of old-addressed movement deltas with one maintenance
    /// refresh at the end: [`deliver_moves`](Self::deliver_moves) in a
    /// loop, stopped at the first refusal, under the same contract and
    /// cost rule as [`deliver_text_batch`](Self::deliver_text_batch).
    ///
    /// # Errors
    ///
    /// Returns [`SweptIdentity`] for the first delta that introduces a
    /// novel testimony at or below the declaration cut; the surface is
    /// refreshed over everything folded before it.
    pub fn deliver_moves_batch<'a, I>(&mut self, deltas: I) -> Result<(), SweptIdentity>
    where
        I: IntoIterator<Item = &'a Dotted<Metatheses>>,
    {
        let mut folded = false;
        for delta in deltas {
            if let Some(dot) = Self::swept_moves(&self.map, &self.moves, delta) {
                if folded {
                    self.refresh();
                }
                return Err(SweptIdentity { dot });
            }
            self.moves.merge_from(delta);
            folded = true;
        }
        if folded {
            self.refresh();
        }
        Ok(())
    }

    /// The text door's admission check: the first delta dot that is
    /// neither translatable (live at the cut, or above the frozen ceiling)
    /// nor already carried by the pair's context.
    fn swept_text(
        map: &RefoundMap,
        text: &Dotted<Rhapsody>,
        delta: &Dotted<Rhapsody>,
    ) -> Option<Dot> {
        delta
            .store()
            .woven()
            .dots()
            .find(|&dot| map.translate(dot).is_none() && !text.context().contains(dot))
    }

    /// The movement door's admission check, over the delta's testimony
    /// dots.
    fn swept_moves(
        map: &RefoundMap,
        moves: &Dotted<Metatheses>,
        delta: &Dotted<Metatheses>,
    ) -> Option<Dot> {
        delta
            .store()
            .iter()
            .map(|(dot, _)| dot)
            .find(|&dot| map.translate(dot).is_none() && !moves.context().contains(dot))
    }

    /// The exact new-identity reading, materialized lazily and cached until
    /// the next old-addressed delivery.
    ///
    /// # Panics
    ///
    /// Only if an internal invariant is broken and a post-validation visible
    /// identity has no frozen-map image.
    #[must_use]
    pub fn projection(&mut self) -> &EpochProjection {
        if self.projection.is_none() {
            self.projection = Some(
                Self::project(self.epoch, &self.map, &self.recension)
                    .expect("validated window identities remain projectable"),
            );
        }
        self.projection.as_ref().expect("projection materialized")
    }

    /// The old-world decision surface, including refused and pending moves.
    #[must_use]
    pub const fn recension(&self) -> &Recension {
        &self.recension
    }

    /// Captures every variable-size shadow component structurally.
    #[cfg(feature = "instrumentation")]
    #[must_use]
    pub fn profile(&self) -> EpochShadowProfile {
        let (mapped_dots, mapped_ceiling_stations, mapped_live_stations) =
            self.map.structural_counts();
        EpochShadowProfile {
            text: self.text.store().profile(),
            text_context_stations: self.text.context().station_count(),
            text_context_exceptions: self.text.context().exceptions_len(),
            testimonies: self.moves.store().len(),
            movement_context_stations: self.moves.context().station_count(),
            movement_context_exceptions: self.moves.context().exceptions_len(),
            mapped_dots,
            mapped_ceiling_stations,
            mapped_live_stations,
            recension: self.recension.profile(),
            projected_dots: self
                .projection
                .as_ref()
                .map_or(0, |value| value.order.len()),
            projected_capacity: self
                .projection
                .as_ref()
                .map_or(0, |value| value.order.capacity()),
        }
    }

    /// Bequeaths the next generation's opening base pair, consuming the
    /// shadow on success: the seal ends the window, and the one-window
    /// judgment state ends with it (the affine lifetime the stratum's
    /// ownership transfer began). A refusal hands the shadow back, because
    /// a mismatched witness or a missing delivery is curable and the
    /// judgment state is the only thing that can cure it.
    ///
    /// The consignment is a pure function of the shadow's final delta set and
    /// the declaration-frozen map. Every replica that seals therefore derives
    /// the identical pair. The text plane is re-spelled in the final reading's
    /// tombstone-inclusive order, with window outcomes baked in and the
    /// rank-contest falsifier's verbatim-anchor divergence unrepresentable.
    /// The movement record is reborn empty. Both pairs share one translated
    /// context that carries the image of every event dot the seal accounts
    /// for, so each plane's floors are born gap-free on its own.
    ///
    /// # The acceptance
    ///
    /// Success is not only a base pair: it is the moment the certification
    /// duty is discharged, so the door hands back a [`Consigned`] beside the
    /// consignment. That witness is the certifiable grade, and this is its
    /// only mint (its one audited escape, [`Consigned::vouch`], carries the
    /// bootstrap case). A caller assembling a checkpoint certificate binds
    /// over [`Consigned::record`] rather than over whatever
    /// [`Epochs::try_seal`](super::Epochs::try_seal) last returned, and the
    /// window between those two doors --- where a member can hold a seal
    /// record its peers reject --- stops being reachable through this
    /// crate's types. See [`Consigned`] for why this door in particular is
    /// the right gate: it is the only one that reads a second, independent
    /// source.
    ///
    /// The witness is the caller's [`SealedEpoch`]. The door checks everything
    /// that witness implies, and trusts nothing beside it. First, the seal
    /// must name this shadow's epoch. Second, the shadow's contexts plus the
    /// seal's own declaration record must cover exactly the sealed join. That
    /// record holds the winner and every retired candidate, the protocol-plane
    /// events outside the two pairs. Coverage must be no less: a covered delta
    /// that never reached this shadow would be dropped silently, then answered
    /// as a duplicate forever after. Coverage must be no more: post-seal
    /// traffic folded here would diverge this replica's consignment from the
    /// fleet's. Nothing caller-claimed enters the check.
    ///
    /// # Errors
    ///
    /// Returns the shadow back, boxed so the refusal stays small, beside
    /// one of four errors:
    ///
    /// * [`EpochConsignmentError::ForeignSeal`]: the seal names another
    ///   epoch.
    /// * [`EpochConsignmentError::Incomplete`]: a sealed-join dot is
    ///   missing from every carried context. Deliver the missing delta and
    ///   retry.
    /// * [`EpochConsignmentError::BeyondSeal`]: a carried dot lies above
    ///   the sealed join.
    /// * [`EpochConsignmentError::Unfoldable`]: the final reading carries
    ///   an unplaced birth or pending testimony, a state a lawful seal
    ///   makes unreachable.
    ///
    /// # Panics
    ///
    /// Only if an internal invariant is broken and a spelled identity has
    /// no context image under the same frozen map that spelled it.
    pub fn consign(
        self,
        sealed: &SealedEpoch,
    ) -> Result<(EpochConsignment, Consigned), (Box<Self>, EpochConsignmentError)> {
        if sealed.declaration() != self.epoch {
            let refusal = EpochConsignmentError::ForeignSeal {
                sealed: sealed.declaration(),
                shadow: self.epoch,
            };
            return Err((Box::new(self), refusal));
        }
        let join = sealed.sealed_join();
        let mut protocol = DotSet::new();
        for dot in sealed.declaration_dots() {
            let _ = protocol.insert(dot);
        }
        let coverage = self
            .text
            .context()
            .merge(self.moves.context())
            .merge(&protocol)
            .floor();
        for (station, counter) in join {
            if coverage.get(station) < counter {
                let dot = RawDot::new(station, coverage.get(station) + 1);
                return Err((Box::new(self), EpochConsignmentError::Incomplete { dot }));
            }
        }
        // Only the shadow's own contexts can exceed the join: the seal's
        // protocol record is canonicalized against it at construction
        // (`Epochs::try_seal` is the sole `SealedEpoch` source), so a
        // beyond-scan over protocol dots would be dead defense. The scan
        // reads per-station high waters, never the dot enumeration: a
        // compaction boundary must not pay per historical event to check
        // its own ceiling, and the highest held dot is the evidence.
        let beyond = self
            .text
            .context()
            .high_water()
            .merge(&self.moves.context().high_water())
            .into_iter()
            .find(|&(station, high)| high > join.get(station));
        if let Some(dot) = beyond {
            return Err((
                Box::new(self),
                EpochConsignmentError::BeyondSeal { dot: dot.into() },
            ));
        }
        let store = match self.recension.consign_store(&self.map) {
            Ok(store) => store,
            Err(unfoldable) => {
                let dot = unfoldable.dot;
                return Err((Box::new(self), EpochConsignmentError::Unfoldable { dot }));
            }
        };
        let context = Self::translate_context(
            &self
                .text
                .context()
                .merge(self.moves.context())
                .merge(&protocol),
            &self.map,
        );
        let text = Dotted::try_new(store, context.clone())
            .expect("every spelled identity rides the same frozen map as its context image");
        Ok((
            EpochConsignment {
                text,
                moves: Dotted::from_context(context),
                map: self.map,
            },
            Consigned::accepted(sealed.clone()),
        ))
    }

    /// The context image, computed structurally: a compaction boundary
    /// must not pay per swept historical dot to describe what survived
    /// it. Per station, the live images are exactly the compacted prefix
    /// `1..=live` (whichever old dots they came from), the gap-free
    /// window portion of the context extends that prefix contiguously
    /// under the affine shift, and only the sparse out-of-order
    /// exceptions are translated individually. Dots dead at the cut have
    /// no image and never enter; the result is floor-perfect whenever the
    /// window's mints are counter-contiguous above the cut (the
    /// one-allocator dot discipline the fleet recipe records).
    ///
    /// The caller passes the union context of both planes plus the seal's
    /// protocol record, whose floor covers every station ceiling (the
    /// stratum proved cut coverage at adoption and the completeness check
    /// re-proved join coverage at this seal), so the per-station window
    /// extent is `floor - ceiling`.
    fn translate_context(context: &DotSet, map: &RefoundMap) -> DotSet {
        let mut prefix = VersionVector::new();
        let floor = context.floor();
        for (station, contextual) in &floor {
            let window = contextual.saturating_sub(map.ceiling_of(station));
            let total = map.live_of(station) + window;
            if total > 0 {
                prefix.observe(station, total);
            }
        }
        let mut translated = DotSet::from_witnessed(&Cut::from_witnessed(prefix));
        for dot in context.exceptions() {
            if let Some(image) = map.translate(dot) {
                let _ = translated.insert(image);
            }
        }
        translated
    }

    fn refresh(&mut self) {
        self.recension
            .collate(self.text.store(), self.moves.store());
        self.projection = None;
    }

    fn project(
        epoch: EpochAddress,
        map: &RefoundMap,
        recension: &Recension,
    ) -> Result<EpochProjection, SweptIdentity> {
        let order = recension
            .order()
            .into_iter()
            .map(|dot| map.translate(dot).ok_or(SweptIdentity { dot }))
            .collect::<Result<_, _>>()?;
        Ok(EpochProjection { epoch, order })
    }
}