bombay-behavior 0.13.1

Pure, statically typed actor behavior primitives
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
//! Staged fresh-actor creation capabilities.

use core::future::Future;
use core::marker::PhantomData;

use super::addressing::{Address, ChildRecipient};
use crate::next::Never;
use crate::{Behavior, Protocol};

/// Behavior-owned provenance for a staged fresh actor creation request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CreationKind<N> {
    /// An initial or ordinary later birth.
    Birth,
    /// A fresh successor incarnation requested by a replacement protocol.
    ReplacementIncarnation {
        /// The exact child incarnation this fresh actor is intended to replace.
        replaces: N,
    },
}

impl<N> CreationKind<N> {
    #[must_use]
    pub const fn replacement_of(replaces: N) -> Self {
        Self::ReplacementIncarnation { replaces }
    }
}

/// A staged request to establish a fresh child at a creator-local nonce.
///
/// The nonce is a routing and correlation key, not an actor identity or proof
/// of freshness. The kind is Behavior-owned intent; a runtime's typed creation
/// resolution is the corresponding committed fact. Replacement at an existing
/// address is deliberately absent; stable identity is derived with a proxy
/// actor.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Create<A: Address, New> {
    pub nonce: A::Nonce,
    pub child: New,
    pub kind: CreationKind<A::Nonce>,
}

impl<A: Address, New> Create<A, New> {
    #[must_use]
    pub const fn new(nonce: A::Nonce, child: New, kind: CreationKind<A::Nonce>) -> Self {
        Self { nonce, child, kind }
    }

    #[must_use]
    pub const fn birth(nonce: A::Nonce, child: New) -> Self {
        Self::new(nonce, child, CreationKind::Birth)
    }

    #[must_use]
    pub const fn replacement_incarnation(nonce: A::Nonce, replaces: A::Nonce, child: New) -> Self {
        Self::new(nonce, child, CreationKind::replacement_of(replaces))
    }
}

/// A named creator-local route for one statically declared child role.
///
/// The route carries routing intent only. Its nonce is not an actor identity,
/// proof of freshness, or evidence that creation succeeded. `Child` fixes the
/// exact behavior accepted by [`ChildRoute::birth`], while `Role` keeps two
/// declarations of the same child behavior nominally distinct.
pub struct ChildRoute<Child: Behavior, Role> {
    recipient: ChildRecipient<Child::Protocol>,
    child: PhantomData<fn() -> Child>,
    role: PhantomData<fn() -> Role>,
}

/// Static proof that `Role` names one exact direct child of `Parent`.
///
/// Behavior authoring owns this relationship. A runtime may use the proof to
/// build application topology, but the role itself allocates nothing and is
/// not evidence that the child was created or installed.
pub trait ChildRole<Parent: Behavior> {
    /// The only child behavior accepted at this role.
    type Child: Behavior;

    /// Structural position of this role in `Parent`'s closed child sum.
    type Position: ChildPosition<<Parent::Birth as BirthMode>::Child, Self::Child>;
}

impl<Child: Behavior, Role> Copy for ChildRoute<Child, Role> {}

impl<Child: Behavior, Role> Clone for ChildRoute<Child, Role> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Child: Behavior, Role> PartialEq for ChildRoute<Child, Role> {
    fn eq(&self, other: &Self) -> bool {
        self.recipient == other.recipient
    }
}

impl<Child: Behavior, Role> Eq for ChildRoute<Child, Role> {}

impl<Child: Behavior, Role> core::fmt::Debug for ChildRoute<Child, Role>
where
    <<Child::Protocol as Protocol>::Addr as Address>::Nonce: core::fmt::Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ChildRoute")
            .field("nonce", &self.nonce())
            .finish()
    }
}

impl<Child: Behavior, Role> ChildRoute<Child, Role> {
    /// Name this declared role at a creator-local route.
    #[must_use]
    pub const fn new(nonce: <<Child::Protocol as Protocol>::Addr as Address>::Nonce) -> Self {
        Self {
            recipient: ChildRecipient::new(nonce),
            child: PhantomData,
            role: PhantomData,
        }
    }

    /// Return the creator-local recipient for this declared child role.
    #[must_use]
    pub const fn recipient(self) -> ChildRecipient<Child::Protocol> {
        self.recipient
    }

    /// Return the creator-local nonce used by creation and lifecycle facts.
    #[must_use]
    pub const fn nonce(self) -> <<Child::Protocol as Protocol>::Addr as Address>::Nonce {
        self.recipient.nonce()
    }

    /// Stage one creation request with explicit Behavior-owned provenance.
    #[must_use]
    pub const fn stage(
        self,
        child: Child,
        kind: CreationKind<<<Child::Protocol as Protocol>::Addr as Address>::Nonce>,
    ) -> Create<<Child::Protocol as Protocol>::Addr, Child> {
        Create::new(self.nonce(), child, kind)
    }

    /// Stage an ordinary fresh-birth request for this declared child role.
    #[must_use]
    pub const fn birth(self, child: Child) -> Create<<Child::Protocol as Protocol>::Addr, Child> {
        self.stage(child, CreationKind::Birth)
    }

    /// Stage a replacement incarnation for this declared child role.
    #[must_use]
    pub const fn replacement_incarnation(
        self,
        replaces: <<Child::Protocol as Protocol>::Addr as Address>::Nonce,
        child: Child,
    ) -> Create<<Child::Protocol as Protocol>::Addr, Child> {
        self.stage(child, CreationKind::replacement_of(replaces))
    }
}

/// Static interpreter capability for installing one concrete child behavior.
///
/// An interpreter implements this trait separately for every concrete child
/// behavior it can install. `C::Protocol` remains the canonical hosting
/// identity at this boundary: distinct child behaviors may select the same
/// protocol and therefore share one runtime-owned protocol space while still
/// receiving distinct installation calls. Semantic child roles and routes are
/// deliberately not storage identities. Heterogeneous child sums require all
/// applicable implementations through recursive static bounds, so unsupported
/// alternatives fail to compile instead of falling through to a registry or
/// erased path. The returned future is sendable so an interpreter may remain
/// inside a thread-safe recursive driver future.
pub trait InstallBirth<A: Address, C: Behavior, Output, Error>
where
    C::Protocol: Protocol<Addr = A>,
{
    /// Install and commit exactly the supplied concrete creation.
    ///
    /// # Errors
    /// Returns the interpreter's typed allocation, initialization, or commit
    /// failure without binding the requested nonce.
    fn install_birth(
        &mut self,
        creation: Create<A, C>,
    ) -> impl Future<Output = Result<Output, Error>> + Send;
}

/// Exhaustive static dispatch of one creation-only child sum.
///
/// This is an interpreter-facing derived construction, not another actor-model
/// operation. Implementations must preserve the nonce and provenance and call
/// exactly one concrete [`InstallBirth`] implementation. [`ChildChoice`]
/// provides the closed recursive heterogeneous sum. Dispatch futures are
/// sendable; heterogeneous sums therefore require sendable alternatives,
/// creator-local nonces, and installers.
pub trait DispatchBirth<A: Address, Installer, Output, Error>: Sized {
    /// Select exactly one concrete installer while preserving creation data.
    ///
    /// # Errors
    /// Returns the selected concrete installer's typed failure unchanged.
    fn dispatch_birth(
        self,
        nonce: A::Nonce,
        kind: CreationKind<A::Nonce>,
        installer: &mut Installer,
    ) -> impl Future<Output = Result<Output, Error>> + Send;
}

/// One alternative in a closed, recursively composed child-creation sum.
///
/// `Head` is one concrete child behavior and `Tail` is the remaining closed
/// sum. This is a creation choice only: it is not a behavior, message
/// envelope, registry, or runtime dispatch mechanism.
///
/// Every alternative requires a concrete installer; incomplete interpreter
/// support is rejected statically:
///
/// ```compile_fail
/// use behavior::{
///     Actions, Behavior, BehaviorActed, ChildChoice, Create, DispatchBirth,
///     InstallBirth, MailAddr, Never, NoBirths, Protocol, User,
/// };
///
/// struct First;
/// struct Second;
///
/// macro_rules! inert {
///     ($child:ty) => {
///         impl Protocol for $child {
///             type Addr = MailAddr;
///             type Msg = Never;
///         }
///         impl Behavior for $child {
///             type Event = User<MailAddr, Never>;
///             type Sends = Vec<Never>;
///             type Ph = Never;
///             type Error = Never;
///             type Birth = NoBirths;
///
///             fn transition(
///                 &mut self,
///                 _: behavior::ActiveTurn,
///                 event: Self::Event,
///             ) -> BehaviorActed<Self> {
///                 match event.message {}
///             }
///         }
///     };
/// }
/// inert!(First);
/// inert!(Second);
///
/// struct Incomplete;
/// impl InstallBirth<MailAddr, First, (), Never> for Incomplete {
///     async fn install_birth(
///         &mut self,
///         _: Create<MailAddr, First>,
///     ) -> Result<(), Never> {
///         Ok(())
///     }
/// }
///
/// type Both = ChildChoice<First, ChildChoice<Second, Never>>;
/// fn require_complete<T: DispatchBirth<MailAddr, Incomplete, (), Never>>() {}
/// require_complete::<Both>();
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChildChoice<Head, Tail> {
    /// Select the concrete child at this position.
    Head(Head),
    /// Select one concrete child from the remaining alternatives.
    Tail(Tail),
}

/// Position selecting the head of a closed [`ChildChoice`] sum.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ChildHead;

/// Position selecting inside the tail of a closed [`ChildChoice`] sum.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ChildTail<Position>(PhantomData<fn() -> Position>);

/// Static proof that `Child` occupies `Position` in a closed child sum.
///
/// This trait provides structural evidence only. It does not construct a
/// choice, perform creation, or select a child through runtime inspection.
/// A role cannot claim a position occupied by a different child:
///
/// ```compile_fail
/// use behavior::{
///     Actions, Behavior, BehaviorActed, Births, ChildChoice, ChildHead,
///     ChildRole, MailAddr, Never, NoBirths, User,
/// };
/// struct First;
/// struct Second;
/// struct Parent;
/// macro_rules! inert {
///     ($actor:ty) => {
///         impl behavior::Protocol for $actor {
///             type Addr = MailAddr;
///             type Msg = Never;
///         }
///         impl Behavior for $actor {
///             type Protocol = Self;
///             type Event = User<MailAddr, Never>;
///             type Sends = Vec<Never>;
///             type Ph = Never;
///             type Error = Never;
///             type Birth = NoBirths;
///             fn transition(&mut self, _: behavior::ActiveTurn, event: Self::Event) -> BehaviorActed<Self> {
///                 match event.message {}
///             }
///         }
///     };
/// }
/// inert!(First);
/// inert!(Second);
/// impl behavior::Protocol for Parent {
///     type Addr = MailAddr;
///     type Msg = Never;
/// }
/// impl Behavior for Parent {
///     type Protocol = Self;
///     type Event = User<MailAddr, Never>;
///     type Sends = Vec<Never>;
///     type Ph = Never;
///     type Error = Never;
///     type Birth = Births<ChildChoice<Second, ChildChoice<First, Never>>>;
///     fn transition(&mut self, _: behavior::ActiveTurn, event: Self::Event) -> BehaviorActed<Self> {
///         match event.message {}
///     }
/// }
/// struct ForgedFirst;
/// impl ChildRole<Parent> for ForgedFirst {
///     type Child = First;
///     type Position = ChildHead;
/// }
/// ```
pub trait ChildPosition<Children, Child: Behavior>: sealed::ChildPosition {}

impl sealed::ChildPosition for ChildHead {}

impl<Head: Behavior, Tail> ChildPosition<ChildChoice<Head, Tail>, Head> for ChildHead {}

impl<Position> sealed::ChildPosition for ChildTail<Position> {}

impl<Head, Tail, Position, Child> ChildPosition<ChildChoice<Head, Tail>, Child>
    for ChildTail<Position>
where
    Child: Behavior,
    Position: ChildPosition<Tail, Child>,
{
}

mod sealed {
    pub trait ChildPosition {}
    pub trait ChildProduct {}
}

/// The empty heterogeneous creation product.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NoChildren;

impl sealed::ChildProduct for NoChildren {}

/// One creation appended to an ordered heterogeneous child product.
pub struct ChildCons<A: Address, C, Earlier> {
    creation: Create<A, C>,
    earlier: Earlier,
}

impl<A: Address, C, Earlier> sealed::ChildProduct for ChildCons<A, C, Earlier> {}

/// A pure, ordered heterogeneous product of staged direct-child creations.
///
/// This value owns no mailbox, address, runtime actor, or lifecycle. Explicit
/// creator-local nonces remain caller policy. Conversion rejects duplicates
/// within this product before producing any `Actions` value; the interpreter
/// must still reject collisions with already established children.
pub struct Children<A: Address, Product = NoChildren> {
    product: Product,
    address: PhantomData<fn() -> A>,
}

/// Rejection while converting a heterogeneous child product into creations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum ChildrenError<N> {
    /// Two declarations selected the same creator-local routing nonce.
    #[error("duplicate creator-local child nonce")]
    DuplicateNonce {
        /// The colliding nonce; no creation product was returned.
        nonce: N,
    },
}

/// Closed recursive conversion implemented only by Bombay child products.
pub trait ChildProduct<A: Address>: sealed::ChildProduct + Sized {
    /// Closed sum containing exactly the concrete child behavior types.
    type Choice;

    #[doc(hidden)]
    fn stage(
        self,
    ) -> Result<(Vec<Create<A, Self::Choice>>, Vec<A::Nonce>), ChildrenError<A::Nonce>>;
}

impl<A: Address> ChildProduct<A> for NoChildren {
    type Choice = Never;

    fn stage(
        self,
    ) -> Result<(Vec<Create<A, Self::Choice>>, Vec<A::Nonce>), ChildrenError<A::Nonce>> {
        Ok((Vec::new(), Vec::new()))
    }
}

impl<A, C, Earlier> ChildProduct<A> for ChildCons<A, C, Earlier>
where
    A: Address,
    C: Behavior,
    C::Protocol: Protocol<Addr = A>,
    Earlier: ChildProduct<A>,
{
    type Choice = ChildChoice<C, Earlier::Choice>;

    fn stage(
        self,
    ) -> Result<(Vec<Create<A, Self::Choice>>, Vec<A::Nonce>), ChildrenError<A::Nonce>> {
        let (earlier, mut nonces) = self.earlier.stage()?;
        if nonces.contains(&self.creation.nonce) {
            return Err(ChildrenError::DuplicateNonce {
                nonce: self.creation.nonce,
            });
        }
        let mut creates = earlier
            .into_iter()
            .map(|creation| {
                Create::new(
                    creation.nonce,
                    ChildChoice::Tail(creation.child),
                    creation.kind,
                )
            })
            .collect::<Vec<_>>();
        nonces.push(self.creation.nonce);
        creates.push(Create::new(
            self.creation.nonce,
            ChildChoice::Head(self.creation.child),
            self.creation.kind,
        ));
        Ok((creates, nonces))
    }
}

impl<A: Address> Children<A, NoChildren> {
    /// Start an empty heterogeneous creation product.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            product: NoChildren,
            address: PhantomData,
        }
    }
}

impl<A: Address> Default for Children<A, NoChildren> {
    fn default() -> Self {
        Self::new()
    }
}

impl<A: Address, Product> Children<A, Product> {
    /// Append one complete staged creation, preserving its provenance.
    #[must_use]
    pub fn create<C>(self, creation: Create<A, C>) -> Children<A, ChildCons<A, C, Product>>
    where
        C: Behavior,
        C::Protocol: Protocol<Addr = A>,
    {
        Children {
            product: ChildCons {
                creation,
                earlier: self.product,
            },
            address: PhantomData,
        }
    }

    /// Append one ordinary fresh-birth request.
    #[must_use]
    pub fn child<C>(self, nonce: A::Nonce, child: C) -> Children<A, ChildCons<A, C, Product>>
    where
        C: Behavior,
        C::Protocol: Protocol<Addr = A>,
    {
        self.create(Create::birth(nonce, child))
    }

    /// Append an ordinary birth through one named child-role binding.
    #[must_use]
    pub fn child_at<C, Role>(
        self,
        route: ChildRoute<C, Role>,
        child: C,
    ) -> Children<A, ChildCons<A, C, Product>>
    where
        C: Behavior,
        C::Protocol: Protocol<Addr = A>,
    {
        self.create(route.birth(child))
    }
}

impl<A, Product> Children<A, Product>
where
    A: Address,
    Product: ChildProduct<A>,
{
    /// Validate the shared nonce domain and produce ordered creation requests.
    ///
    /// # Errors
    /// Returns [`ChildrenError::DuplicateNonce`] without returning a partial
    /// creation vector when any two declarations in this product share a
    /// nonce. Existing child-namespace collisions remain interpreter-owned
    /// creation rejections.
    pub fn into_creates(self) -> Result<Vec<Create<A, Product::Choice>>, ChildrenError<A::Nonce>> {
        self.product.stage().map(|(creates, _)| creates)
    }
}

impl<A, Head, Tail, Installer, Output, Error> DispatchBirth<A, Installer, Output, Error>
    for ChildChoice<Head, Tail>
where
    A: Address,
    A::Nonce: Send,
    Head: Behavior + Send,
    Head::Protocol: Protocol<Addr = A>,
    Tail: DispatchBirth<A, Installer, Output, Error> + Send,
    Installer: InstallBirth<A, Head, Output, Error> + Send,
{
    async fn dispatch_birth(
        self,
        nonce: A::Nonce,
        kind: CreationKind<A::Nonce>,
        installer: &mut Installer,
    ) -> Result<Output, Error> {
        match self {
            Self::Head(child) => {
                installer
                    .install_birth(Create::new(nonce, child, kind))
                    .await
            }
            Self::Tail(tail) => tail.dispatch_birth(nonce, kind, installer).await,
        }
    }
}

impl<A, Installer, Output, Error> DispatchBirth<A, Installer, Output, Error> for Never
where
    A: Address,
{
    fn dispatch_birth(
        self,
        _nonce: A::Nonce,
        _kind: CreationKind<A::Nonce>,
        _installer: &mut Installer,
    ) -> impl Future<Output = Result<Output, Error>> + Send {
        async move { match self {} }
    }
}

impl<A, C, Installer, Output, Error> DispatchBirth<A, Installer, Output, Error> for C
where
    A: Address,
    C: Behavior,
    C::Protocol: Protocol<Addr = A>,
    Installer: InstallBirth<A, C, Output, Error>,
{
    fn dispatch_birth(
        self,
        nonce: A::Nonce,
        kind: CreationKind<A::Nonce>,
        installer: &mut Installer,
    ) -> impl Future<Output = Result<Output, Error>> + Send {
        installer.install_birth(Create::new(nonce, self, kind))
    }
}

/// A type-level description of a behavior's creation capability.
pub trait BirthMode {
    type Child;
}

/// Empty protocol projection of a closed behavior-birth algebra.
pub struct NoBirthProtocols;

/// One behavior protocol followed by the remaining closed birth projection.
pub struct BirthProtocol<P: Protocol, Tail> {
    protocol: PhantomData<fn() -> P>,
    tail: PhantomData<fn() -> Tail>,
}

/// Structural position selecting the current projected birth protocol.
pub struct BirthProtocolHead;

/// Structural position selecting inside the remaining protocol projection.
pub struct BirthProtocolTail<Position>(PhantomData<fn() -> Position>);

/// Static membership evidence for one occurrence in a birth-protocol product.
pub trait BirthProtocolAt<P: Protocol, Position> {}

impl<P: Protocol, Tail> BirthProtocolAt<P, BirthProtocolHead> for BirthProtocol<P, Tail> {}

impl<Head, Tail, P, Position> BirthProtocolAt<P, BirthProtocolTail<Position>>
    for BirthProtocol<Head, Tail>
where
    Head: Protocol,
    P: Protocol,
    Tail: BirthProtocolAt<P, Position>,
{
}

/// Closed product operation used by the structural birth projection.
#[doc(hidden)]
pub trait BirthProtocolProduct {
    type Append<Tail: BirthProtocolProduct>: BirthProtocolProduct;
}

impl BirthProtocolProduct for NoBirthProtocols {
    type Append<Tail: BirthProtocolProduct> = Tail;
}

impl<P, Rest> BirthProtocolProduct for BirthProtocol<P, Rest>
where
    P: Protocol,
    Rest: BirthProtocolProduct,
{
    type Append<Tail: BirthProtocolProduct> = BirthProtocol<P, Rest::Append<Tail>>;
}

/// Closed static projection of a behavior's own protocol and every protocol
/// reachable through its transitive staged-birth algebra.
///
/// This is structural information derived from [`Behavior::Birth`]. It makes
/// no hosting or allocation decision and does not inspect send destinations.
pub trait BirthProtocols: Behavior {
    type Protocols: BirthProtocolProduct;
}

impl<B> BirthProtocols for B
where
    B: Behavior,
    B::Birth: BirthModeProtocols,
{
    type Protocols = BirthProtocol<B::Protocol, <B::Birth as BirthModeProtocols>::Protocols>;
}

#[doc(hidden)]
pub trait BirthModeProtocols {
    type Protocols: BirthProtocolProduct;
}

impl<M> BirthModeProtocols for M
where
    M: BirthMode,
    M::Child: BirthNodeProtocols,
{
    type Protocols = <M::Child as BirthNodeProtocols>::Protocols;
}

#[doc(hidden)]
pub trait BirthNodeProtocols {
    type Protocols: BirthProtocolProduct;
}

impl<B> BirthNodeProtocols for B
where
    B: BirthProtocols,
{
    type Protocols = B::Protocols;
}

impl<Head, Tail> BirthNodeProtocols for ChildChoice<Head, Tail>
where
    Head: BirthNodeProtocols,
    Tail: BirthNodeProtocols,
{
    type Protocols = <Head::Protocols as BirthProtocolProduct>::Append<Tail::Protocols>;
}

impl BirthNodeProtocols for Never {
    type Protocols = NoBirthProtocols;
}

/// This behavior cannot emit child births.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NoBirths;

impl BirthMode for NoBirths {
    type Child = Never;
}

/// This behavior may emit births of `C`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Births<C>(PhantomData<fn() -> C>);

impl<C> BirthMode for Births<C> {
    type Child = C;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Actions, BehaviorActed, MailAddr, NoBirths, User};

    struct Child;

    struct SharedProtocol;

    impl behavior::Protocol for SharedProtocol {
        type Addr = MailAddr;
        type Msg = u8;
    }

    struct Primary;
    struct Fallback;

    macro_rules! shared_protocol_behavior {
        ($behavior:ty, $birth:ty) => {
            impl Behavior for $behavior {
                type Protocol = SharedProtocol;
                type Event = User<MailAddr, u8>;
                type Sends = Vec<Never>;
                type Ph = Never;
                type Error = Never;
                type Birth = $birth;

                fn transition(
                    &mut self,
                    _: crate::ActiveTurn,
                    _: Self::Event,
                ) -> BehaviorActed<Self> {
                    Ok(Actions::cont())
                }
            }
        };
    }

    shared_protocol_behavior!(Primary, Births<Child>);
    shared_protocol_behavior!(Fallback, NoBirths);

    impl behavior::Protocol for Child {
        type Addr = MailAddr;
        type Msg = u8;
    }

    impl Behavior for Child {
        type Protocol = Self;
        type Event = User<MailAddr, u8>;
        type Sends = Vec<Never>;
        type Ph = Never;
        type Error = Never;
        type Birth = NoBirths;

        fn transition(&mut self, _: crate::ActiveTurn, _: Self::Event) -> BehaviorActed<Self> {
            Ok(Actions::cont())
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum InstallError {
        Refused,
    }

    struct RecordingInstaller {
        calls: usize,
        observed: Vec<(u64, CreationKind<u64>)>,
        result: Result<u32, InstallError>,
    }

    #[derive(Debug, PartialEq, Eq)]
    enum SharedInstallation {
        Primary(u64),
        Fallback(u64),
    }

    #[derive(Default)]
    struct SharedProtocolInstaller(Vec<SharedInstallation>);

    impl InstallBirth<MailAddr, Primary, (), Never> for SharedProtocolInstaller {
        async fn install_birth(
            &mut self,
            creation: Create<MailAddr, Primary>,
        ) -> Result<(), Never> {
            self.0.push(SharedInstallation::Primary(creation.nonce));
            Ok(())
        }
    }

    impl InstallBirth<MailAddr, Fallback, (), Never> for SharedProtocolInstaller {
        async fn install_birth(
            &mut self,
            creation: Create<MailAddr, Fallback>,
        ) -> Result<(), Never> {
            self.0.push(SharedInstallation::Fallback(creation.nonce));
            Ok(())
        }
    }

    impl InstallBirth<MailAddr, Child, u32, InstallError> for RecordingInstaller {
        async fn install_birth(
            &mut self,
            creation: Create<MailAddr, Child>,
        ) -> Result<u32, InstallError> {
            self.calls += 1;
            self.observed.push((creation.nonce, creation.kind));
            self.result
        }
    }

    fn installer(result: Result<u32, InstallError>) -> RecordingInstaller {
        RecordingInstaller {
            calls: 0,
            observed: Vec::new(),
            result,
        }
    }

    fn assert_send<T: Send>(_: &T) {}

    enum WorkerRole {}

    #[test]
    fn child_route_preserves_one_nonce_across_routing_and_creation_provenance() {
        let route = ChildRoute::<Child, WorkerRole>::new(17);

        assert_eq!(route.nonce(), 17);
        assert_eq!(route.recipient().nonce(), 17);
        assert_eq!(route, ChildRoute::new(17));
        assert_ne!(route, ChildRoute::new(19));
        assert_eq!(format!("{route:?}"), "ChildRoute { nonce: 17 }");

        let birth = route.birth(Child);
        assert_eq!(birth.nonce, 17);
        assert_eq!(birth.kind, CreationKind::Birth);

        let replacement = route.replacement_incarnation(11, Child);
        assert_eq!(replacement.nonce, 17);
        assert_eq!(replacement.kind, CreationKind::replacement_of(11));
    }

    #[test]
    fn empty_child_product_stages_no_creations_or_nonces() {
        let (creations, nonces) = <NoChildren as ChildProduct<MailAddr>>::stage(NoChildren)
            .expect("an empty child product is valid");
        assert!(creations.is_empty());
        assert!(nonces.is_empty());
    }

    #[tokio::test]
    async fn concrete_child_dispatches_once_with_exact_nonce_provenance_and_output() {
        let mut installer = installer(Ok(91));
        let future = Child.dispatch_birth(
            17,
            CreationKind::ReplacementIncarnation { replaces: 8 },
            &mut installer,
        );
        assert_send(&future);
        let result = future.await;

        assert_eq!(result, Ok(91));
        assert_eq!(installer.calls, 1);
        assert_eq!(
            installer.observed,
            [(17, CreationKind::ReplacementIncarnation { replaces: 8 })]
        );
    }

    #[tokio::test]
    async fn concrete_child_returns_the_exact_installer_error_without_retry() {
        let mut installer = installer(Err(InstallError::Refused));
        let future = Child.dispatch_birth(23, CreationKind::replacement_of(19), &mut installer);
        assert_send(&future);
        let result = future.await;

        assert_eq!(result, Err(InstallError::Refused));
        assert_eq!(installer.calls, 1);
        assert_eq!(installer.observed, [(23, CreationKind::replacement_of(19))]);
    }

    #[tokio::test]
    async fn distinct_child_alternatives_preserve_one_canonical_protocol_identity() {
        type Alternatives = ChildChoice<Primary, ChildChoice<Fallback, Never>>;

        fn requires_shared_protocol<C: Behavior<Protocol = SharedProtocol>>() {}
        requires_shared_protocol::<Primary>();
        requires_shared_protocol::<Fallback>();

        let mut installer = SharedProtocolInstaller::default();
        Alternatives::Head(Primary)
            .dispatch_birth(11, CreationKind::Birth, &mut installer)
            .await
            .unwrap();
        Alternatives::Tail(ChildChoice::Head(Fallback))
            .dispatch_birth(17, CreationKind::Birth, &mut installer)
            .await
            .unwrap();

        assert_eq!(
            installer.0,
            [
                SharedInstallation::Primary(11),
                SharedInstallation::Fallback(17),
            ]
        );
    }

    #[test]
    fn birth_protocol_projection_recurses_without_inspecting_send_lanes() {
        type Protocols = <Primary as BirthProtocols>::Protocols;
        type Expected = BirthProtocol<SharedProtocol, BirthProtocol<Child, NoBirthProtocols>>;

        trait Same<T> {}
        impl<T> Same<T> for T {}
        fn exact<T: Same<Expected>>() {}
        exact::<Protocols>();
    }
}