Skip to main content

tatara_process/
tagged_union.rs

1//! `tagged_union::resolve` — the typescape's "exactly-one-Option" pattern,
2//! lifted to one source of truth.
3//!
4//! Several CRD-facing types in this crate ([`crate::intent::Intent`],
5//! [`crate::lifetime::Lifetime`], [`crate::export::ArtifactSource`],
6//! [`crate::export::VectorChannel`], [`crate::encapsulates::EncapsulationKind`])
7//! carry `N` `Option<T>` fields where exactly one is expected to be
8//! populated on the wire. Each previously hand-rolled the same
9//! `count() + if-let-chain + unreachable!()` body — four parallel tables
10//! (the struct fields, an `is_some()` count array, an `if-let-else`
11//! resolution chain, and any sibling projection like `IntentVariant::kind`)
12//! kept coherent only by code review. The `unreachable!()` arm at the
13//! bottom of every chain was a sentinel that fires at runtime if the
14//! parallel tables ever drift.
15//!
16//! This module collapses the resolver to ONE typed sweep over an
17//! `IntoIterator<Item = Option<V>>` of candidate variant projections.
18//! Adding a new tagged-union variant is now ONE additional line at the
19//! callsite — no `unreachable!()` arm to update, no parallel `is_some()`
20//! count array to extend.
21
22/// Outcome of [`resolve`] when the candidate list isn't exactly-one.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum ResolveError {
25    /// No candidate was populated.
26    None,
27    /// More than one candidate was populated.
28    Many,
29}
30
31/// Resolve at most one populated variant from a candidate list.
32///
33/// Each item in `candidates` is the projected borrowed-variant view for
34/// the corresponding `Option<T>` field — `None` when the field is unset,
35/// `Some(V::Variant(...))` when set.
36///
37/// Returns the single populated variant, [`ResolveError::None`] when
38/// none are populated, or [`ResolveError::Many`] when more than one are.
39///
40/// The body is one short-circuiting sweep — `Many` is returned as soon
41/// as the second populated entry is seen, without scanning the rest.
42pub fn resolve<V>(candidates: impl IntoIterator<Item = Option<V>>) -> Result<V, ResolveError> {
43    let mut found: Option<V> = None;
44    for candidate in candidates {
45        if candidate.is_some() {
46            if found.is_some() {
47                return Err(ResolveError::Many);
48            }
49            found = candidate;
50        }
51    }
52    found.ok_or(ResolveError::None)
53}
54
55/// Sibling error carriers on tagged-union `.variant()` sites all
56/// project the two [`ResolveError`] arms onto the SAME closed-set
57/// diagnostic shape — `Empty(&'static str)` for "no variant set"
58/// (carrying the closed-set kind list so the operator diagnostic
59/// names every candidate) and a payload-free `Ambiguous` for
60/// "multiple variants set". This trait names that shared shape as
61/// ONE typed contract; [`resolve_or_err`] then composes [`resolve`]
62/// with the trait so each per-carrier `.map_err(|e| match e { ... })`
63/// site collapses to a one-line typed dispatch.
64///
65/// Impls live at each error carrier's own module so the (diagnostic
66/// message, closed-set list) pair stays owned by the carrier that
67/// publishes it — the trait is the projection, not the message.
68pub trait TaggedUnionError: Sized {
69    /// Construct the "no variant set" arm with the closed-set kind
70    /// list slash-joined into the diagnostic payload.
71    fn empty(kinds: &'static str) -> Self;
72    /// Construct the "multiple variants set" arm.
73    fn ambiguous() -> Self;
74}
75
76/// Resolve at most one populated variant, mapping the two
77/// [`ResolveError`] arms onto the caller's typed carrier via
78/// [`TaggedUnionError`]. The compound-lift primitive: sweep +
79/// short-circuit + typed-error dispatch as ONE call.
80///
81/// Substrate primitive for the four sibling `Xxx::variant()` sites
82/// on `ProcessSpec` (`Intent::variant`,
83/// `EncapsulationKind::variant`, `ArtifactSource::variant`,
84/// `VectorChannel::variant`) that previously restated the SAME
85/// `.map_err(|e| match e { None => Empty(LIST), Many => Ambiguous })`
86/// two-arm dispatch at each call site — every one of them a
87/// byte-identical restatement of the (empty→list, many→ambiguous)
88/// projection whose payload identity is strictly the carrier's own
89/// diagnostic. A fifth sibling error carrier picks up the projection
90/// through ONE `impl TaggedUnionError` block + ONE `resolve_or_err`
91/// call site.
92///
93/// The [`Lifetime::variant`](crate::lifetime::Lifetime::variant)
94/// site is DELIBERATELY not routed through this primitive — its
95/// `ResolveError::None` arm resolves to a `Permanent` default
96/// variant, not to an `Empty` typed error, so the projection shape
97/// diverges at the None arm.
98pub fn resolve_or_err<V, E: TaggedUnionError>(
99    candidates: impl IntoIterator<Item = Option<V>>,
100    kinds: &'static str,
101) -> Result<V, E> {
102    resolve(candidates).map_err(|e| match e {
103        ResolveError::None => E::empty(kinds),
104        ResolveError::Many => E::ambiguous(),
105    })
106}
107
108/// Declare a sibling error carrier for a tagged-union `.variant()`
109/// site — the enum + [`TaggedUnionError`] impl in ONE authoring
110/// surface.
111///
112/// Every one of the four production `.variant()` sites on
113/// `ProcessSpec` ([`crate::intent::Intent`],
114/// [`crate::encapsulates::EncapsulationKind`],
115/// [`crate::export::ArtifactSource`],
116/// [`crate::export::VectorChannel`]) pre-lift restated the same
117/// four-piece authoring shape by hand:
118///
119/// 1. `#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq,
120///    Eq)]` on the carrier — byte-identical across all four.
121/// 2. A two-variant enum body (`Empty(&'static str)`, `Ambiguous`)
122///    — structurally identical.
123/// 3. Two `#[error(...)]` messages whose only per-carrier knob is a
124///    noun-prefix (`"intent"`, `"encapsulation kind"`, ...) — every
125///    other byte of the (`"has no variant set (one of {0}
126///    required)"`, `"has multiple variants set; exactly one
127///    required"`) tails was verbatim.
128/// 4. A six-line `impl TaggedUnionError` whose two constructor
129///    bodies re-projected `Self::Empty(kinds)` / `Self::Ambiguous`
130///    onto each carrier's own typed variants.
131///
132/// The macro collapses (1) + (2) + (4) onto ONE call and takes the
133/// two per-carrier operator-facing diagnostic literals as named
134/// arguments so (3) stays visible at the callsite without re-authoring
135/// the shared derive set or trait impl. A fifth sibling carrier
136/// lands as ONE `declare_tagged_union_error!` invocation — no
137/// re-authored `#[derive(...)]`, no re-authored two-variant enum
138/// body, no re-authored `impl TaggedUnionError` block.
139///
140/// Emitted derives include `Copy` — the `Empty` arm carries only
141/// a `&'static str` and the `Ambiguous` arm is payload-free, so
142/// the carrier is always `Copy` regardless of caller.
143///
144/// # Example
145///
146/// ```ignore
147/// declare_tagged_union_error! {
148///     pub IntentError,
149///     empty = "intent has no variant set (one of {0} required)",
150///     ambiguous = "intent has multiple variants set; exactly one required",
151/// }
152/// ```
153///
154/// Expands to the enum + [`TaggedUnionError`] impl for
155/// `IntentError`; the `Empty` arm carries the caller's closed-set
156/// kind-list literal.
157#[macro_export]
158macro_rules! declare_tagged_union_error {
159    (
160        $(#[$attr:meta])*
161        $vis:vis $name:ident,
162        empty = $empty:literal,
163        ambiguous = $ambiguous:literal $(,)?
164    ) => {
165        $(#[$attr])*
166        #[derive(
167            ::std::clone::Clone,
168            ::std::marker::Copy,
169            ::std::fmt::Debug,
170            ::thiserror::Error,
171            ::std::cmp::PartialEq,
172            ::std::cmp::Eq,
173        )]
174        $vis enum $name {
175            #[error($empty)]
176            Empty(&'static str),
177            #[error($ambiguous)]
178            Ambiguous,
179        }
180
181        impl $crate::tagged_union::TaggedUnionError for $name {
182            fn empty(kinds: &'static str) -> Self {
183                Self::Empty(kinds)
184            }
185            fn ambiguous() -> Self {
186                Self::Ambiguous
187            }
188        }
189    };
190}
191
192/// Declare the three-block impl stanza a tagged-union parent type
193/// publishes to the substrate — inherent `.variant()` forwarder +
194/// [`VariantSelector<Parent>`] impl on the sibling `Kind` +
195/// [`TaggedUnion`] impl on the parent — in ONE authoring surface.
196///
197/// Every one of the four production `.variant()` sites on
198/// `ProcessSpec` ([`crate::intent::Intent`],
199/// [`crate::encapsulates::EncapsulationKind`],
200/// [`crate::export::ArtifactSource`],
201/// [`crate::export::VectorChannel`]) pre-lift restated the same three
202/// impl blocks by hand:
203///
204/// 1. `impl $parent { pub fn variant(&self) -> Result<$variant<'_>, $err> { ... } }`
205///    — a one-line delegation to the [`TaggedUnion::variant`] default
206///    body, plus 5 lines of rustdoc cross-referencing the other three
207///    sibling `.variant()` sites verbatim.
208/// 2. `impl VariantSelector<$parent> for $kind { type Variant<'a> = $variant<'a>; fn select(...) { <$kind>::select(self, parent) } }`
209///    — 6 lines whose only per-site knobs are (`$parent`, `$kind`,
210///    `$variant`); the trait method body a straight delegation to the
211///    inherent `<$kind>::select`.
212/// 3. `impl TaggedUnion for $parent { type Kind = $kind; type Error = $err; const KIND_LIST = $kind_list; }`
213///    — 3 associated-item assignments whose only per-site knobs are
214///    the (`$kind`, `$err`, `$kind_list`) tuple.
215///
216/// The macro takes the (`$parent`, `$kind`, `$variant`, `$err`,
217/// `$kind_list`) five-tuple as named arguments and emits all three
218/// blocks. A fifth sibling tagged-union parent picks up all three
219/// impls through ONE macro call — no re-authored inherent
220/// `.variant()` forwarder, no re-authored `impl VariantSelector`
221/// block, no re-authored `impl TaggedUnion` block.
222///
223/// The emitted inherent `.variant()`'s rustdoc is canonical (names
224/// the substrate primitive, not the exact set of sibling sites) so
225/// a fifth sibling doesn't drift the cross-ref count against reality
226/// merely by existing.
227///
228/// # Example
229///
230/// ```ignore
231/// declare_tagged_union_impls! {
232///     parent = Intent,
233///     kind = IntentKind,
234///     variant = IntentVariant,
235///     error = IntentError,
236///     kind_list = INTENT_KIND_LIST,
237/// }
238/// ```
239///
240/// Expands to the inherent `Intent::variant`, the
241/// `VariantSelector<Intent>` impl on `IntentKind`, and the
242/// `TaggedUnion` impl on `Intent`.
243#[macro_export]
244macro_rules! declare_tagged_union_impls {
245    (
246        parent = $parent:ty,
247        kind = $kind:ty,
248        variant = $variant:ident,
249        error = $err:ty,
250        kind_list = $kind_list:expr $(,)?
251    ) => {
252        impl $parent {
253            /// Resolve to exactly one variant. Errors on zero or many.
254            ///
255            /// One-line inherent forwarder that delegates the sweep
256            /// body to the substrate primitive
257            /// [`crate::tagged_union::TaggedUnion::variant`] — every
258            /// production `.variant()` site on `ProcessSpec` dispatches
259            /// through this ONE default body so the resolve-sweep
260            /// pattern lives at ONE substrate site. The inherent surface
261            /// stays load-bearing so consumer callsites don't need
262            /// `use TaggedUnion`.
263            pub fn variant(&self) -> ::std::result::Result<$variant<'_>, $err> {
264                <Self as $crate::tagged_union::TaggedUnion>::variant(self)
265            }
266
267            /// Presence probe — does this tagged union carry a
268            /// populated slot addressed by the given closed-set
269            /// discriminator?
270            ///
271            /// One-line inherent forwarder that delegates to the
272            /// substrate primitive
273            /// [`crate::tagged_union::TaggedUnion::has`] — every
274            /// closed-set-driven presence check on `ProcessSpec`
275            /// dispatches through this ONE default body so the
276            /// per-slot `spec.<field>.is_some()` pattern lives at
277            /// ONE substrate site. The inherent surface stays
278            /// load-bearing so consumer callsites don't need
279            /// `use TaggedUnion`.
280            pub fn has(&self, kind: $kind) -> bool {
281                <Self as $crate::tagged_union::TaggedUnion>::has(self, kind)
282            }
283
284            /// Closed-set-complement peer of [`Self::has`] — `true` iff
285            /// the given `kind` is MISSING (its slot on this tagged
286            /// union is empty).
287            ///
288            /// One-line inherent forwarder that delegates to the
289            /// substrate primitive
290            /// [`crate::tagged_union::TaggedUnion::lacks`], whose
291            /// default body is `!self.has(kind)`. Every consumer whose
292            /// semantic reading is "the missing set contains this
293            /// kind" — a "still missing: <kind>" diagnostic, a
294            /// `lacks-<kind>` require-tag classifier arm, a
295            /// dependency-satisfaction check — reads
296            /// `parent.lacks(kind)` through the inherent surface
297            /// rather than negating `parent.has(kind)` at the call
298            /// site. The definitional complement law
299            /// `parent.lacks(kind) == !parent.has(kind)` and the
300            /// kind-scoped implication
301            /// `parent.lacks_only(kind) → parent.lacks(kind)` are
302            /// pinned as first-class typed invariants by the trait's
303            /// own default body and swept substrate-wide by
304            /// [`crate::tagged_union::assert_lacks_matches_has_complement`].
305            pub fn lacks(&self, kind: $kind) -> bool {
306                <Self as $crate::tagged_union::TaggedUnion>::lacks(self, kind)
307            }
308
309            /// Widened peer of [`Self::has`] — returns the borrowed
310            /// variant view addressed by `kind`, or `None` when the
311            /// matching slot is empty.
312            ///
313            /// One-line inherent forwarder that delegates to the
314            /// substrate primitive
315            /// [`crate::tagged_union::TaggedUnion::find`], whose
316            /// default body is `kind.select(self)`. Every
317            /// closed-set-driven `kind.select(&parent)` callsite that
318            /// pre-lift required `use VariantSelector` at the caller
319            /// now reads `parent.find(kind)` through the inherent
320            /// surface, byte-for-byte symmetrical with
321            /// `parent.has(kind)`. The composition law
322            /// `parent.has(kind) == parent.find(kind).is_some()` is
323            /// pinned as a first-class typed invariant by the trait's
324            /// own `has` default body
325            /// (`self.find(kind).is_some()`), swept substrate-wide by
326            /// [`crate::tagged_union::assert_find_agrees_with_has`].
327            pub fn find(&self, kind: $kind) -> ::std::option::Option<$variant<'_>> {
328                <Self as $crate::tagged_union::TaggedUnion>::find(self, kind)
329            }
330
331            /// Closed-set-inversion peer of [`Self::has`] / [`Self::find`]
332            /// — returns the canonical-ordered `Vec` of populated
333            /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
334            /// discriminators.
335            ///
336            /// One-line inherent forwarder that delegates to the
337            /// substrate primitive
338            /// [`crate::tagged_union::TaggedUnion::populated_kinds`],
339            /// whose default body is
340            /// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k|
341            /// self.has(*k)).collect()`. Every consumer that needs
342            /// to enumerate which slots on a tagged-union parent are
343            /// populated (an operator-facing "Ambiguous named
344            /// [Nix, Container]" diagnostic composed on the malformed
345            /// arm; a closed-set audit dispatcher; a
346            /// `populated-kind-count-<n>` require-tag classifier
347            /// prefix) reads `parent.populated_kinds()` through the
348            /// inherent surface, byte-for-byte symmetrical with
349            /// `parent.has(kind)` / `parent.find(kind)`. The
350            /// composition law
351            /// `parent.populated_kinds().contains(&k) == parent.has(k)`
352            /// is pinned as a first-class typed invariant by the
353            /// trait's own default body and swept substrate-wide by
354            /// [`crate::tagged_union::assert_populated_kinds_matches_has`].
355            pub fn populated_kinds(&self) -> ::std::vec::Vec<$kind> {
356                <Self as $crate::tagged_union::TaggedUnion>::populated_kinds(self)
357            }
358
359            /// Scalar cardinality peer of [`Self::populated_kinds`] —
360            /// the number of populated slots on this tagged union.
361            ///
362            /// One-line inherent forwarder that delegates to the
363            /// substrate primitive
364            /// [`crate::tagged_union::TaggedUnion::populated_kind_count`],
365            /// whose default body is
366            /// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k|
367            /// self.has(*k)).count()`. Every consumer that needs the
368            /// cardinality of the populated-slot set as a scalar
369            /// (a `populated-kind-count-<n>` require-tag classifier
370            /// prefix; a fast-path branch on the Ambiguous-arm side
371            /// that discriminates "well-formed" from "malformed with
372            /// N slots"; a coherence check that verifies "every
373            /// well-formed parent has exactly one populated slot")
374            /// reads `parent.populated_kind_count()` through the
375            /// inherent surface, byte-for-byte symmetrical with
376            /// `parent.has(kind)` / `parent.find(kind)` /
377            /// `parent.populated_kinds()`. The composition law
378            /// `parent.populated_kind_count() == parent.populated_kinds().len()`
379            /// is pinned as a first-class typed invariant by the
380            /// trait's own default body and swept substrate-wide by
381            /// [`crate::tagged_union::assert_populated_kind_count_matches_populated_kinds`].
382            pub fn populated_kind_count(&self) -> usize {
383                <Self as $crate::tagged_union::TaggedUnion>::populated_kind_count(self)
384            }
385
386            /// Closed-set-COMPLEMENT peer of [`Self::populated_kinds`]
387            /// — returns the canonical-ordered `Vec` of EMPTY
388            /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
389            /// discriminators.
390            ///
391            /// One-line inherent forwarder that delegates to the
392            /// substrate primitive
393            /// [`crate::tagged_union::TaggedUnion::missing_kinds`],
394            /// whose default body is
395            /// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k|
396            /// !self.has(*k)).collect()`. Every consumer that needs to
397            /// enumerate which slots on a tagged-union parent are
398            /// ABSENT (an operator-facing "still missing [Nix, Container]"
399            /// diagnostic on the partially-populated arm; a coherence
400            /// check verifying "every process boundary carries every
401            /// intent slot"; a `missing-<kind>` require-tag classifier
402            /// arm) reads `parent.missing_kinds()` through the
403            /// inherent surface, byte-for-byte symmetrical with
404            /// `parent.populated_kinds()`. The partition law
405            /// `parent.populated_kinds() ∪ parent.missing_kinds() ==
406            /// ClosedSet::ALL` (with the two sets disjoint) is pinned
407            /// as a first-class typed invariant by the trait's own
408            /// default body and swept substrate-wide by
409            /// [`crate::tagged_union::assert_missing_kinds_matches_has`].
410            pub fn missing_kinds(&self) -> ::std::vec::Vec<$kind> {
411                <Self as $crate::tagged_union::TaggedUnion>::missing_kinds(self)
412            }
413
414            /// Scalar cardinality peer of [`Self::missing_kinds`] —
415            /// the number of EMPTY slots on this tagged union.
416            ///
417            /// One-line inherent forwarder that delegates to the
418            /// substrate primitive
419            /// [`crate::tagged_union::TaggedUnion::missing_kind_count`],
420            /// whose default body is
421            /// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k|
422            /// !self.has(*k)).count()`. Every consumer that needs the
423            /// cardinality of the missing-slot set as a scalar (a
424            /// `missing-kind-count-<n>` require-tag classifier prefix;
425            /// a fast-path branch that discriminates "well-formed"
426            /// from "N missing slots"; a coherence check that verifies
427            /// "every well-formed parent has exactly ALL.len() - 1
428            /// missing slots") reads `parent.missing_kind_count()`
429            /// through the inherent surface, byte-for-byte symmetrical
430            /// with `parent.populated_kind_count()`. The scalar
431            /// partition law `parent.populated_kind_count() +
432            /// parent.missing_kind_count() == <Kind as ClosedSet>::ALL.len()`
433            /// is pinned by the trait's own default body and swept
434            /// substrate-wide by
435            /// [`crate::tagged_union::assert_missing_kind_count_matches_missing_kinds`].
436            pub fn missing_kind_count(&self) -> usize {
437                <Self as $crate::tagged_union::TaggedUnion>::missing_kind_count(self)
438            }
439
440            /// Short-circuiting `Option<$kind>` peer of
441            /// [`Self::populated_kinds`] — the FIRST populated kind on
442            /// this tagged union in canonical
443            /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
444            /// order, or `None` when no slot is populated.
445            ///
446            /// One-line inherent forwarder that delegates to the
447            /// substrate primitive
448            /// [`crate::tagged_union::TaggedUnion::first_populated_kind`],
449            /// whose default body is
450            /// `<Kind as ClosedSet>::ALL.iter().copied().find(|k|
451            /// self.has(*k))`. Every consumer that needs the earliest
452            /// populated slot on a tagged-union parent as an
453            /// `Option<Kind>` (an operator-facing "Ambiguous, starting
454            /// at Nix" diagnostic on the malformed arm; a
455            /// `first-populated-<kind>` require-tag classifier arm; a
456            /// fast-path branch that discriminates "empty" from "any
457            /// populated") reads `parent.first_populated_kind()` through
458            /// the inherent surface, byte-for-byte symmetrical with
459            /// `parent.populated_kinds()` / `parent.has(kind)`. The
460            /// composition law `parent.first_populated_kind() ==
461            /// parent.populated_kinds().first().copied()` is pinned as
462            /// a first-class typed invariant by the trait's own default
463            /// body and swept substrate-wide by
464            /// [`crate::tagged_union::assert_first_populated_kind_matches_populated_kinds`].
465            pub fn first_populated_kind(&self) -> ::std::option::Option<$kind> {
466                <Self as $crate::tagged_union::TaggedUnion>::first_populated_kind(self)
467            }
468
469            /// Short-circuiting `Option<$kind>` peer of
470            /// [`Self::missing_kinds`] — the FIRST missing kind on this
471            /// tagged union in canonical
472            /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
473            /// order, or `None` when EVERY slot is populated.
474            ///
475            /// One-line inherent forwarder that delegates to the
476            /// substrate primitive
477            /// [`crate::tagged_union::TaggedUnion::first_missing_kind`],
478            /// whose default body is
479            /// `<Kind as ClosedSet>::ALL.iter().copied().find(|k|
480            /// !self.has(*k))`. Byte-for-byte symmetrical with
481            /// `parent.first_populated_kind()` under a negated
482            /// predicate; the two primitives PARTITION
483            /// `ClosedSet::ALL`'s earliest-element projection on the
484            /// (populated, missing) split. The composition law
485            /// `parent.first_missing_kind() ==
486            /// parent.missing_kinds().first().copied()` is pinned as a
487            /// first-class typed invariant by the trait's own default
488            /// body and swept substrate-wide by
489            /// [`crate::tagged_union::assert_first_missing_kind_matches_missing_kinds`].
490            pub fn first_missing_kind(&self) -> ::std::option::Option<$kind> {
491                <Self as $crate::tagged_union::TaggedUnion>::first_missing_kind(self)
492            }
493
494            /// Short-circuiting `Option<$kind>` peer of
495            /// [`Self::populated_kinds`] — the LAST populated kind on
496            /// this tagged union in canonical
497            /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
498            /// order, or `None` when no slot is populated.
499            ///
500            /// One-line inherent forwarder that delegates to the
501            /// substrate primitive
502            /// [`crate::tagged_union::TaggedUnion::last_populated_kind`],
503            /// whose default body is
504            /// `<Kind as ClosedSet>::ALL.iter().rev().copied().find(|k|
505            /// self.has(*k))` — a REVERSED closed-set walk composed
506            /// against `self.has` per variant that SHORT-CIRCUITS at
507            /// the latest match. Byte-for-byte time-reversed peer of
508            /// [`Self::first_populated_kind`]. Empty parent returns
509            /// `None`; well-formed parent returns `Some(k)` (the sole
510            /// populated slot); malformed (Ambiguous) parent returns
511            /// `Some(k)` where `k` is the LATEST populated slot in
512            /// canonical `ALL` order — the operator-diagnostic "and
513            /// last at Z" peer of the "Ambiguous, starting at Nix"
514            /// upgrade the first-projection enables. The composition
515            /// law `parent.last_populated_kind() ==
516            /// parent.populated_kinds().last().copied()` is pinned as
517            /// a first-class typed invariant by the trait's own default
518            /// body and swept substrate-wide by
519            /// [`crate::tagged_union::assert_last_populated_kind_matches_populated_kinds`].
520            pub fn last_populated_kind(&self) -> ::std::option::Option<$kind> {
521                <Self as $crate::tagged_union::TaggedUnion>::last_populated_kind(self)
522            }
523
524            /// Short-circuiting `Option<$kind>` peer of
525            /// [`Self::missing_kinds`] — the LAST missing kind on this
526            /// tagged union in canonical
527            /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
528            /// order, or `None` when EVERY slot is populated.
529            ///
530            /// One-line inherent forwarder that delegates to the
531            /// substrate primitive
532            /// [`crate::tagged_union::TaggedUnion::last_missing_kind`],
533            /// whose default body is
534            /// `<Kind as ClosedSet>::ALL.iter().rev().copied().find(|k|
535            /// !self.has(*k))`. Byte-for-byte time-reversed peer of
536            /// [`Self::first_missing_kind`] under an identical negated
537            /// predicate. The two primitives PARTITION
538            /// `ClosedSet::ALL`'s endpoint projection on the (populated,
539            /// missing) × (earliest, latest) product together with the
540            /// `first_*` peers — every endpoint-addressable coherence
541            /// check reads ONE of the four at ONE call site without
542            /// allocating a `Vec<$kind>`. The composition law
543            /// `parent.last_missing_kind() ==
544            /// parent.missing_kinds().last().copied()` is pinned as a
545            /// first-class typed invariant by the trait's own default
546            /// body and swept substrate-wide by
547            /// [`crate::tagged_union::assert_last_missing_kind_matches_missing_kinds`].
548            pub fn last_missing_kind(&self) -> ::std::option::Option<$kind> {
549                <Self as $crate::tagged_union::TaggedUnion>::last_missing_kind(self)
550            }
551
552            /// Exactly-one-populated `Option<$kind>` peer of
553            /// [`Self::populated_kinds`] — `Some(k)` iff `k` is the
554            /// SOLE populated kind on this tagged union, else `None`.
555            ///
556            /// One-line inherent forwarder that delegates to the
557            /// substrate primitive
558            /// [`crate::tagged_union::TaggedUnion::unique_populated_kind`],
559            /// whose default body is a two-step-short-circuit walk
560            /// over `<Kind as ClosedSet>::ALL` returning `Some(k)`
561            /// only when EXACTLY ONE `has(k)` is `true`. Every
562            /// consumer that needs the resolved kind identity on the
563            /// well-formed arm (without paying for the borrowed
564            /// variant view [`Self::variant`] returns, and without
565            /// materializing the [`Self::Error`] carrier on the
566            /// empty / malformed arms) reads
567            /// `parent.unique_populated_kind()` through the inherent
568            /// surface — `Some(k)` names well-formed exactly-one,
569            /// `None` collapses BOTH the empty AND the malformed
570            /// (ambiguous) arms.
571            ///
572            /// The composition laws
573            /// `parent.unique_populated_kind().is_some() ==
574            /// (parent.populated_kind_count() == 1)` and (on the
575            /// `Some` arm) `parent.unique_populated_kind() ==
576            /// parent.first_populated_kind() ==
577            /// parent.last_populated_kind()` are pinned as first-
578            /// class typed invariants by the trait's own default body
579            /// and swept substrate-wide by
580            /// [`crate::tagged_union::assert_unique_populated_kind_matches_populated_kinds`].
581            pub fn unique_populated_kind(&self) -> ::std::option::Option<$kind> {
582                <Self as $crate::tagged_union::TaggedUnion>::unique_populated_kind(self)
583            }
584
585            /// Exactly-one-missing `Option<$kind>` peer of
586            /// [`Self::missing_kinds`] — `Some(k)` iff `k` is the
587            /// SOLE missing kind on this tagged union, else `None`.
588            ///
589            /// One-line inherent forwarder that delegates to the
590            /// substrate primitive
591            /// [`crate::tagged_union::TaggedUnion::unique_missing_kind`],
592            /// whose default body is a two-step-short-circuit walk
593            /// over `<Kind as ClosedSet>::ALL` under a NEGATED `has`
594            /// predicate returning `Some(k)` only when EXACTLY ONE
595            /// `!has(k)` is `true`. Byte-for-byte symmetrical with
596            /// `parent.unique_populated_kind()` under complement; on
597            /// tagged unions with `<Kind as ClosedSet>::ALL.len() >
598            /// 2` the primitive returns `Some` only on the near-
599            /// saturation arm (`ALL.len() - 1` populated).
600            ///
601            /// The composition laws
602            /// `parent.unique_missing_kind().is_some() ==
603            /// (parent.missing_kind_count() == 1)` and (on the
604            /// `Some` arm) `parent.unique_missing_kind() ==
605            /// parent.first_missing_kind() ==
606            /// parent.last_missing_kind()` are pinned as first-class
607            /// typed invariants by the trait's own default body and
608            /// swept substrate-wide by
609            /// [`crate::tagged_union::assert_unique_missing_kind_matches_missing_kinds`].
610            pub fn unique_missing_kind(&self) -> ::std::option::Option<$kind> {
611                <Self as $crate::tagged_union::TaggedUnion>::unique_missing_kind(self)
612            }
613
614            /// Boolean cardinality-endpoint peer of [`Self::populated_kinds`]
615            /// — `true` iff NO slot on this tagged union is populated.
616            ///
617            /// One-line inherent forwarder that delegates to the
618            /// substrate primitive
619            /// [`crate::tagged_union::TaggedUnion::is_empty`], whose
620            /// default body is `!<Kind as ClosedSet>::ALL.iter().any(|k|
621            /// self.has(k))` — a short-circuiting closed-set walk that
622            /// returns `true` iff every point-probe returns `false`,
623            /// WITHOUT materializing the `Vec` `populated_kinds` would
624            /// build. Every consumer that needs the zero-arm Boolean
625            /// projection of the populated cardinality (a fast-path
626            /// guard on "any content at all"; an operator-facing
627            /// "carrier missing content" diagnostic on the `Empty` arm;
628            /// an `is-empty` require-tag classifier arm) reads
629            /// `parent.is_empty()` through the inherent surface, byte-
630            /// for-byte symmetrical with `parent.is_saturated()` under
631            /// the (populated, missing) complement axis. The
632            /// composition law
633            /// `parent.is_empty() == (parent.populated_kind_count() == 0)`
634            /// is pinned as a first-class typed invariant by the
635            /// trait's own default body and swept substrate-wide by
636            /// [`crate::tagged_union::assert_is_empty_matches_populated_kind_count`].
637            pub fn is_empty(&self) -> bool {
638                <Self as $crate::tagged_union::TaggedUnion>::is_empty(self)
639            }
640
641            /// Boolean cardinality-endpoint peer of [`Self::missing_kinds`]
642            /// — `true` iff EVERY slot on this tagged union is populated
643            /// (i.e. the missing set is empty).
644            ///
645            /// One-line inherent forwarder that delegates to the
646            /// substrate primitive
647            /// [`crate::tagged_union::TaggedUnion::is_saturated`], whose
648            /// default body is `<Kind as ClosedSet>::ALL.iter().all(|k|
649            /// self.has(k))` — a short-circuiting closed-set walk that
650            /// returns `true` iff every point-probe returns `true`,
651            /// WITHOUT materializing the `Vec` `missing_kinds` would
652            /// build. Every consumer that needs the zero-arm Boolean
653            /// projection of the missing cardinality (a fast-path guard
654            /// discriminating "over-populated" from "well-formed or
655            /// partial"; an operator-facing "over-populated carrier"
656            /// diagnostic; an `is-saturated` require-tag classifier
657            /// arm) reads `parent.is_saturated()` through the inherent
658            /// surface, byte-for-byte symmetrical with
659            /// `parent.is_empty()` under the (populated, missing)
660            /// complement axis. The composition law
661            /// `parent.is_saturated() == (parent.missing_kind_count() == 0)`
662            /// is pinned as a first-class typed invariant by the
663            /// trait's own default body and swept substrate-wide by
664            /// [`crate::tagged_union::assert_is_saturated_matches_missing_kind_count`].
665            pub fn is_saturated(&self) -> bool {
666                <Self as $crate::tagged_union::TaggedUnion>::is_saturated(self)
667            }
668
669            /// Boolean cardinality "at-least-one" peer of
670            /// [`Self::populated_kinds`] — `true` iff AT LEAST ONE slot
671            /// on this tagged union is populated (the populated set is
672            /// NON-empty).
673            ///
674            /// One-line inherent forwarder that delegates to the
675            /// substrate primitive
676            /// [`crate::tagged_union::TaggedUnion::has_any_populated_kind`],
677            /// whose default body is `<Kind as ClosedSet>::ALL.iter().any(|k|
678            /// self.has(k))` — a short-circuiting closed-set walk that
679            /// returns `true` at the FIRST populated slot, WITHOUT
680            /// materializing the `Vec` `populated_kinds` would build.
681            /// Every consumer that needs the ≥ 1 halfspace on the
682            /// populated cardinality (a boundary-progress "any content
683            /// at all" diagnostic; an `is-non-empty` require-tag
684            /// classifier arm; a fast-path branch discriminating "some
685            /// populated" from "all missing") reads
686            /// `parent.has_any_populated_kind()` through the inherent
687            /// surface — byte-for-byte definitional complement of
688            /// `parent.is_empty()`, no readerly inversion at the
689            /// callsite, and byte-for-byte symmetrical with
690            /// `parent.has_any_missing_kind()` under the (populated,
691            /// missing) complement axis. The composition law
692            /// `parent.has_any_populated_kind() == !parent.is_empty()`
693            /// is pinned as a first-class typed invariant by the
694            /// trait's own default body and swept substrate-wide by
695            /// [`crate::tagged_union::assert_has_any_populated_kind_matches_populated_kind_count`].
696            pub fn has_any_populated_kind(&self) -> bool {
697                <Self as $crate::tagged_union::TaggedUnion>::has_any_populated_kind(self)
698            }
699
700            /// Boolean cardinality "at-least-one" peer of
701            /// [`Self::missing_kinds`] — `true` iff AT LEAST ONE slot on
702            /// this tagged union is missing (the missing set is
703            /// NON-empty).
704            ///
705            /// One-line inherent forwarder that delegates to the
706            /// substrate primitive
707            /// [`crate::tagged_union::TaggedUnion::has_any_missing_kind`],
708            /// whose default body is `<Kind as ClosedSet>::ALL.iter().any(|k|
709            /// !self.has(k))` — a short-circuiting closed-set walk under
710            /// a negated `has` predicate that returns `true` at the
711            /// FIRST missing slot, WITHOUT materializing the `Vec`
712            /// `missing_kinds` would build. Every consumer that needs
713            /// the ≥ 1 halfspace on the missing cardinality (an
714            /// operator-facing "not fully populated" diagnostic; a
715            /// `has-any-missing-kind` require-tag classifier arm; a
716            /// fast-path branch discriminating "any slot still absent"
717            /// from "over-populated / saturated") reads
718            /// `parent.has_any_missing_kind()` through the inherent
719            /// surface — byte-for-byte definitional complement of
720            /// `parent.is_saturated()`, no readerly inversion at the
721            /// callsite, and byte-for-byte symmetrical with
722            /// `parent.has_any_populated_kind()` under the (populated,
723            /// missing) complement axis. The composition law
724            /// `parent.has_any_missing_kind() == !parent.is_saturated()`
725            /// is pinned as a first-class typed invariant by the
726            /// trait's own default body and swept substrate-wide by
727            /// [`crate::tagged_union::assert_has_any_missing_kind_matches_missing_kind_count`].
728            pub fn has_any_missing_kind(&self) -> bool {
729                <Self as $crate::tagged_union::TaggedUnion>::has_any_missing_kind(self)
730            }
731
732            /// Boolean cardinality-mid-endpoint peer of
733            /// [`Self::unique_populated_kind`] — `true` iff EXACTLY ONE
734            /// slot on this tagged union is populated.
735            ///
736            /// One-line inherent forwarder that delegates to the
737            /// substrate primitive
738            /// [`crate::tagged_union::TaggedUnion::has_unique_populated_kind`],
739            /// whose default body is `self.unique_populated_kind().is_some()`
740            /// — the Boolean projection of the two-step-short-circuit
741            /// closed-set walk `unique_populated_kind` already performs,
742            /// without paying for a `Vec<$kind>` allocation on any arm.
743            /// Every consumer that needs the exactly-one-populated arm
744            /// as a `bool` (a fast-path branch on the well-formed arm
745            /// that skips the borrowed-view / error-carrier
746            /// materialization [`Self::variant`] would pay for; an
747            /// operator-facing "well-formed" diagnostic on the resolver's
748            /// Ok arm; a `has-unique-populated-kind` require-tag
749            /// classifier arm; a coherence check verifying "every
750            /// production parent from a `single_slot_X` factory is
751            /// well-formed") reads `parent.has_unique_populated_kind()`
752            /// through the inherent surface, byte-for-byte symmetrical
753            /// with `parent.is_empty()` / `parent.is_saturated()` under
754            /// the (zero-, one-arm) × (populated, missing) cardinality
755            /// grid. The composition law
756            /// `parent.has_unique_populated_kind() == (parent.populated_kind_count() == 1)`
757            /// is pinned as a first-class typed invariant by the trait's
758            /// own default body and swept substrate-wide by
759            /// [`crate::tagged_union::assert_has_unique_populated_kind_matches_populated_kind_count`].
760            pub fn has_unique_populated_kind(&self) -> bool {
761                <Self as $crate::tagged_union::TaggedUnion>::has_unique_populated_kind(self)
762            }
763
764            /// Boolean cardinality-mid-endpoint peer of
765            /// [`Self::unique_missing_kind`] — `true` iff EXACTLY ONE
766            /// slot on this tagged union is missing.
767            ///
768            /// One-line inherent forwarder that delegates to the
769            /// substrate primitive
770            /// [`crate::tagged_union::TaggedUnion::has_unique_missing_kind`],
771            /// whose default body is `self.unique_missing_kind().is_some()`
772            /// — the Boolean projection of the two-step-short-circuit
773            /// closed-set walk `unique_missing_kind` already performs.
774            /// Every consumer that needs the exactly-one-missing arm as
775            /// a `bool` (a fast-path branch on the near-saturation arm;
776            /// an operator-facing "one slot away from saturated"
777            /// diagnostic; a `has-unique-missing-kind` require-tag
778            /// classifier arm) reads `parent.has_unique_missing_kind()`
779            /// through the inherent surface, byte-for-byte symmetrical
780            /// with `parent.has_unique_populated_kind()` under the
781            /// (populated, missing) complement axis. The composition law
782            /// `parent.has_unique_missing_kind() == (parent.missing_kind_count() == 1)`
783            /// is pinned as a first-class typed invariant by the trait's
784            /// own default body and swept substrate-wide by
785            /// [`crate::tagged_union::assert_has_unique_missing_kind_matches_missing_kind_count`].
786            pub fn has_unique_missing_kind(&self) -> bool {
787                <Self as $crate::tagged_union::TaggedUnion>::has_unique_missing_kind(self)
788            }
789
790            /// Boolean cardinality many-arm peer of
791            /// [`Self::has_unique_populated_kind`] — `true` iff TWO
792            /// OR MORE slots on this tagged union are populated (i.e.
793            /// the "ambiguous" arm of the resolver contract).
794            ///
795            /// One-line inherent forwarder that delegates to the
796            /// substrate primitive
797            /// [`crate::tagged_union::TaggedUnion::has_multiple_populated_kinds`],
798            /// whose default body is a two-step-short-circuit closed-
799            /// set walk under [`Self::has`] that returns `true` iff
800            /// the filtered iterator yields at least two hits, WITHOUT
801            /// materializing the `Vec` `populated_kinds` would build.
802            /// The short-circuit fires on the SECOND populated slot
803            /// — strictly cheaper than the widened primitive on every
804            /// arm past the second populated slot.
805            ///
806            /// # Sibling to the Boolean cardinality trichotomy
807            ///
808            /// Third arm of the {0, 1, ≥2} cardinality trichotomy on
809            /// the populated axis. Together with [`Self::is_empty`]
810            /// (zero-arm) and [`Self::has_unique_populated_kind`]
811            /// (one-arm), these three Boolean primitives partition
812            /// every tagged-union state coherently — EXACTLY ONE of
813            /// the three returns `true` on any given parent. Maps
814            /// directly onto the three arms of the resolver contract
815            /// [`Self::variant`] returns:
816            /// `is_empty()` ↔ `Err(Error::empty)`,
817            /// `has_unique_populated_kind()` ↔ `Ok(Variant)`,
818            /// `has_multiple_populated_kinds()` ↔ `Err(Error::ambiguous)`.
819            ///
820            /// The composition law
821            /// `parent.has_multiple_populated_kinds() == (parent.populated_kind_count() >= 2)`
822            /// is pinned as a first-class typed invariant by the
823            /// trait's own default body and swept substrate-wide by
824            /// [`crate::tagged_union::assert_has_multiple_populated_kinds_matches_populated_kind_count`].
825            pub fn has_multiple_populated_kinds(&self) -> bool {
826                <Self as $crate::tagged_union::TaggedUnion>::has_multiple_populated_kinds(self)
827            }
828
829            /// Boolean cardinality many-arm peer of
830            /// [`Self::has_unique_missing_kind`] — `true` iff TWO OR
831            /// MORE slots on this tagged union are missing.
832            ///
833            /// One-line inherent forwarder that delegates to the
834            /// substrate primitive
835            /// [`crate::tagged_union::TaggedUnion::has_multiple_missing_kinds`],
836            /// whose default body is a two-step-short-circuit closed-
837            /// set walk under a NEGATED [`Self::has`] predicate that
838            /// returns `true` iff the filtered iterator yields at
839            /// least two hits, WITHOUT materializing the `Vec`
840            /// `missing_kinds` would build. Byte-for-byte symmetrical
841            /// with `parent.has_multiple_populated_kinds()` under the
842            /// (populated, missing) complement axis.
843            ///
844            /// Third arm of the {0, 1, ≥2} cardinality trichotomy on
845            /// the missing axis. Together with [`Self::is_saturated`]
846            /// (zero-arm) and [`Self::has_unique_missing_kind`]
847            /// (one-arm), these three Boolean primitives partition
848            /// every tagged-union state coherently on the complement
849            /// axis. The composition law
850            /// `parent.has_multiple_missing_kinds() == (parent.missing_kind_count() >= 2)`
851            /// is pinned as a first-class typed invariant by the
852            /// trait's own default body and swept substrate-wide by
853            /// [`crate::tagged_union::assert_has_multiple_missing_kinds_matches_missing_kind_count`].
854            pub fn has_multiple_missing_kinds(&self) -> bool {
855                <Self as $crate::tagged_union::TaggedUnion>::has_multiple_missing_kinds(self)
856            }
857
858            /// Boolean cardinality "≤ 1" peer of
859            /// [`Self::has_multiple_populated_kinds`] — `true` iff AT
860            /// MOST ONE slot on this tagged union is populated (i.e.
861            /// zero or one populated slot).
862            ///
863            /// One-line inherent forwarder that delegates to the
864            /// substrate primitive
865            /// [`crate::tagged_union::TaggedUnion::has_at_most_one_populated_kind`],
866            /// whose default body is the definitional Boolean negation
867            /// of [`Self::has_multiple_populated_kinds`] — reuses the
868            /// SAME two-step-short-circuit closed-set walk without
869            /// re-authoring the fused loop; the short-circuit fires on
870            /// the SECOND populated slot, and the negation flips the
871            /// return in-place without a second walk over the closed
872            /// set. Strictly cheaper than the widened union composition
873            /// `self.is_empty() || self.has_unique_populated_kind()`
874            /// (which walks the closed set twice) on every arm.
875            ///
876            /// # Sibling to the Boolean cardinality "≥ 2" primitive
877            ///
878            /// Boolean-negation peer under `!(≥ 2) == (≤ 1)` — where
879            /// [`Self::has_multiple_populated_kinds`] names the
880            /// AMBIGUOUS arm of the resolver contract (the arm
881            /// [`Self::variant`] returns `Err(Error::ambiguous)` on),
882            /// `has_at_most_one_populated_kind` names its complement —
883            /// the RESOLVEABLE-OR-EMPTY arm (the two arms of the
884            /// resolver contract that DON'T return `Err(Error::ambiguous)`).
885            /// The typed predicate for "this parent is not ambiguous"
886            /// without inverting a `!parent.has_multiple_populated_kinds()`
887            /// at every callsite.
888            ///
889            /// # Composition laws
890            ///
891            /// - `has_at_most_one_populated_kind() == !has_multiple_populated_kinds()`
892            ///   — the definitional Boolean negation, at the trait
893            ///   default body's SAME fused short-circuit walk.
894            /// - `has_at_most_one_populated_kind() == (populated_kind_count() <= 1)`
895            ///   — the scalar cardinality composition.
896            /// - `has_at_most_one_populated_kind() == is_empty() || has_unique_populated_kind()`
897            ///   — the union of the zero-arm and the one-arm of the
898            ///   {0, 1, ≥ 2} cardinality trichotomy.
899            ///
900            /// All three composition laws are pinned as first-class
901            /// typed invariants by the trait's own default body and
902            /// swept substrate-wide by
903            /// [`crate::tagged_union::assert_has_at_most_one_populated_kind_matches_populated_kind_count`].
904            pub fn has_at_most_one_populated_kind(&self) -> bool {
905                <Self as $crate::tagged_union::TaggedUnion>::has_at_most_one_populated_kind(self)
906            }
907
908            /// Boolean cardinality "≤ 1" peer of
909            /// [`Self::has_multiple_missing_kinds`] — `true` iff AT
910            /// MOST ONE slot on this tagged union is missing (i.e.
911            /// zero or one missing slot).
912            ///
913            /// One-line inherent forwarder that delegates to the
914            /// substrate primitive
915            /// [`crate::tagged_union::TaggedUnion::has_at_most_one_missing_kind`],
916            /// whose default body is the definitional Boolean negation
917            /// of [`Self::has_multiple_missing_kinds`] — reuses the
918            /// SAME two-step-short-circuit closed-set walk under a
919            /// negated [`Self::has`] predicate without re-authoring the
920            /// fused loop. Strictly cheaper than the widened union
921            /// composition
922            /// `self.is_saturated() || self.has_unique_missing_kind()`
923            /// (two closed-set walks) on every arm.
924            ///
925            /// # Sibling to the Boolean cardinality "≥ 2" primitive
926            ///
927            /// Boolean-negation peer under `!(≥ 2) == (≤ 1)` —
928            /// byte-for-byte symmetrical with
929            /// `parent.has_at_most_one_populated_kind()` under the
930            /// (populated, missing) complement axis. Names the arm
931            /// where the parent is SATURATED-OR-NEAR-SATURATED (zero
932            /// or exactly one missing slot).
933            ///
934            /// # Composition laws
935            ///
936            /// - `has_at_most_one_missing_kind() == !has_multiple_missing_kinds()`
937            ///   — the definitional Boolean negation.
938            /// - `has_at_most_one_missing_kind() == (missing_kind_count() <= 1)`
939            ///   — the scalar complement-cardinality composition.
940            /// - `has_at_most_one_missing_kind() == is_saturated() || has_unique_missing_kind()`
941            ///   — the union of the zero-missing-arm and the
942            ///   one-missing-arm of the {0, 1, ≥ 2} cardinality
943            ///   trichotomy on the missing axis.
944            ///
945            /// All three composition laws are pinned as first-class
946            /// typed invariants by the trait's own default body and
947            /// swept substrate-wide by
948            /// [`crate::tagged_union::assert_has_at_most_one_missing_kind_matches_missing_kind_count`].
949            pub fn has_at_most_one_missing_kind(&self) -> bool {
950                <Self as $crate::tagged_union::TaggedUnion>::has_at_most_one_missing_kind(self)
951            }
952
953            /// Boolean parent-state middle-arm projection — `true` iff
954            /// this tagged union has AT LEAST ONE populated slot AND AT
955            /// LEAST ONE missing slot, i.e. it is neither
956            /// [`Self::is_empty`] nor [`Self::is_saturated`].
957            ///
958            /// One-line inherent forwarder that delegates to the
959            /// substrate primitive
960            /// [`crate::tagged_union::TaggedUnion::is_partially_populated`],
961            /// whose default body is a FUSED short-circuit closed-set
962            /// walk that returns `true` at the EARLIEST slot where both
963            /// a populated AND a missing kind have been observed —
964            /// byte-for-byte cheaper than the widened composition
965            /// `!self.is_empty() && !self.is_saturated()` (two closed-
966            /// set walks) on every partially-populated arm.
967            ///
968            /// # Sibling to the parent-state trichotomy
969            ///
970            /// Middle arm of the natural `{Empty | Partial | Saturated}`
971            /// parent-state trichotomy — orthogonal to the {0, 1, ≥2}
972            /// cardinality trichotomies on the populated / missing
973            /// axes. Together with [`Self::is_empty`] (all-missing arm)
974            /// and [`Self::is_saturated`] (all-populated arm), these
975            /// three Boolean primitives partition every tagged-union
976            /// state coherently on the parent-state axis — EXACTLY ONE
977            /// of the three returns `true` on any given parent. The
978            /// trichotomy partition law
979            /// `usize::from(is_empty()) + usize::from(is_partially_populated())
980            /// + usize::from(is_saturated()) == 1` is pinned as a first-
981            /// class typed invariant by the trait's own default body
982            /// and swept substrate-wide by
983            /// [`crate::tagged_union::assert_is_partially_populated_matches_cardinality`].
984            pub fn is_partially_populated(&self) -> bool {
985                <Self as $crate::tagged_union::TaggedUnion>::is_partially_populated(self)
986            }
987
988            /// Kind-scoped strict refinement of [`Self::has`] — `true`
989            /// iff the given `kind` is populated AND no OTHER slot on
990            /// this tagged union is populated. The "exactly this one
991            /// variant" predicate.
992            ///
993            /// One-line inherent forwarder that delegates to the
994            /// substrate primitive
995            /// [`crate::tagged_union::TaggedUnion::has_only`], whose
996            /// default body is a FUSED short-circuit closed-set walk
997            /// that returns `false` at the EARLIEST populated slot
998            /// whose kind is NOT `kind`, and returns `true` iff the
999            /// sweep completes with `kind` seen as the sole populated
1000            /// slot. Byte-for-byte cheaper than either widened
1001            /// composition `self.unique_populated_kind() ==
1002            /// Some(kind)` (which walks until the SECOND populated
1003            /// slot) or `self.has(kind) &&
1004            /// self.has_unique_populated_kind()` (which walks the
1005            /// closed set twice) on every arm where the parent
1006            /// carries a populated slot that isn't `kind`.
1007            ///
1008            /// # Sibling to [`Self::has`]
1009            ///
1010            /// Kind-scoped strict-refinement peer: `has(kind)` is the
1011            /// SUBSET predicate; `has_only(kind)` is the EQUAL
1012            /// predicate. The implication
1013            /// `has_only(kind) → has(kind)` binds the pair on the
1014            /// strict-refinement axis. The composition law
1015            /// `parent.has_only(kind) ==
1016            /// (parent.unique_populated_kind() == Some(kind))` is
1017            /// pinned as a first-class typed invariant by the trait's
1018            /// own default body and swept substrate-wide by
1019            /// [`crate::tagged_union::assert_has_only_matches_unique_populated_kind`].
1020            pub fn has_only(&self, kind: $kind) -> bool {
1021                <Self as $crate::tagged_union::TaggedUnion>::has_only(self, kind)
1022            }
1023
1024            /// Closed-set-complement peer of [`Self::has_only`] —
1025            /// `true` iff the given `kind` is MISSING AND no OTHER slot
1026            /// on this tagged union is missing.
1027            ///
1028            /// One-line inherent forwarder that delegates the fused
1029            /// short-circuit walk to the substrate primitive
1030            /// [`crate::tagged_union::TaggedUnion::lacks_only`], whose
1031            /// default body walks
1032            /// `<Self::Kind as ClosedSet>::ALL` under a negated
1033            /// [`crate::tagged_union::TaggedUnion::has`] and returns
1034            /// `false` at the EARLIEST missing slot whose kind is not
1035            /// `kind`. Byte-for-byte cheaper than either widened
1036            /// composition
1037            /// `self.unique_missing_kind() == Some(kind)` (which walks
1038            /// until the SECOND missing slot before comparing) or
1039            /// `!self.has(kind) && self.has_unique_missing_kind()`
1040            /// (two closed-set walks) on every arm where the parent
1041            /// carries a missing slot that isn't `kind`.
1042            ///
1043            /// # Sibling to [`Self::has_only`]
1044            ///
1045            /// Closed-set-complement peer: `has_only(kind)` names
1046            /// parents whose SOLE populated slot is `kind`;
1047            /// `lacks_only(kind)` names parents whose SOLE missing slot
1048            /// is `kind`. The composition law
1049            /// `parent.lacks_only(kind) ==
1050            /// (parent.unique_missing_kind() == Some(kind))` and the
1051            /// cardinality-refinement law
1052            /// `parent.lacks_only(kind) == (!parent.has(kind) &&
1053            /// parent.has_unique_missing_kind())` are pinned as first-
1054            /// class typed invariants by the trait's own default body
1055            /// and swept substrate-wide by
1056            /// [`crate::tagged_union::assert_lacks_only_matches_unique_missing_kind`].
1057            pub fn lacks_only(&self, kind: $kind) -> bool {
1058                <Self as $crate::tagged_union::TaggedUnion>::lacks_only(self, kind)
1059            }
1060        }
1061
1062        impl $crate::tagged_union::VariantSelector<$parent> for $kind {
1063            type Variant<'a> = $variant<'a>;
1064            fn select<'a>(self, parent: &'a $parent) -> ::std::option::Option<$variant<'a>>
1065            where
1066                Self: 'a,
1067            {
1068                <$kind>::select(self, parent)
1069            }
1070        }
1071
1072        impl $crate::tagged_union::TaggedUnion for $parent {
1073            type Kind = $kind;
1074            type Error = $err;
1075            const KIND_LIST: &'static str = $kind_list;
1076        }
1077    };
1078}
1079
1080/// Project the borrowed-view of a tagged-union variant addressed by
1081/// this closed-set discriminator.
1082///
1083/// Companion trait to [`TaggedUnion`] — binds a `Kind` closed-set to
1084/// the parent `P` it discriminates AND to the borrowed-view
1085/// [`Self::Variant<'a>`] the resolver hands out. Every one of the
1086/// four production `.variant()` sites on `ProcessSpec`
1087/// ([`crate::intent::Intent`], [`crate::encapsulates::EncapsulationKind`],
1088/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
1089/// pre-lift restated the same
1090/// `Self::Kind::ALL.into_iter().map(|k| k.select(self))` sweep body
1091/// verbatim at its inherent `.variant()`. Post-lift the trait binds
1092/// `(k.select(self), Variant<'a>)` onto ONE typed contract per Kind
1093/// so [`TaggedUnion::variant`]'s default body can dispatch the sweep
1094/// generically — the four sibling inherent bodies collapse to
1095/// one-line delegations and a fifth sibling picks up the sweep for
1096/// free through ONE `impl VariantSelector` block.
1097///
1098/// The GAT `Variant<'a>` carries the parent's lifetime so a borrowed
1099/// view projected from `&'a P` composes typed with the resolver's
1100/// short-circuit — every projection stays a compile-time refinement,
1101/// no `Box<dyn ...>` erasure. The GAT is additionally bound to
1102/// [`VariantKind<Self>`] so every implementor's borrowed view knows
1103/// its addressing Kind — the reverse projection of [`Self::select`]
1104/// closed at compile-time so a fifth sibling that adds `impl
1105/// VariantSelector` without opening the peer `impl VariantKind` fails
1106/// at the trait bound, not later at a per-consumer round-trip test.
1107pub trait VariantSelector<P: ?Sized>: Copy + 'static {
1108    /// The borrowed-view enum returned by the parent's inherent
1109    /// `.variant()` method — one arm per closed-set variant, each
1110    /// arm carrying a `&'a` reference into the parent's populated
1111    /// slot. Bound generically here so [`TaggedUnion::variant`]'s
1112    /// default body can name the return type without restating it
1113    /// per parent. Additionally bound to [`VariantKind<Self>`] so
1114    /// the reverse projection `Variant<'a> → Self` is closed at the
1115    /// trait boundary — every implementor's borrowed view knows its
1116    /// addressing Kind through ONE typed contract, and the substrate
1117    /// testkit [`assert_variant_round_trip`] composes `select`
1118    /// (forward) with `variant_kind` (reverse) generically.
1119    type Variant<'a>: VariantKind<Self>
1120    where
1121        P: 'a,
1122        Self: 'a;
1123
1124    /// Project a `&'a P` borrow into the optional typed variant view
1125    /// for `self` (the addressed discriminator). Returns `None` iff
1126    /// the matching slot on `P` is `None`. Composes the closed-set
1127    /// sweep [`TaggedUnion::variant`] loops over.
1128    fn select<'a>(self, parent: &'a P) -> Option<Self::Variant<'a>>
1129    where
1130        Self: 'a;
1131}
1132
1133/// Reverse projection — every borrowed-variant view enum knows its
1134/// closed-set `K` discriminator.
1135///
1136/// Dual of [`VariantSelector<P>::select`] on the addressed Kind:
1137/// where the selector projects a parent borrow forward into an
1138/// optional Variant, this trait projects a populated Variant back
1139/// into the Kind that addresses it. Together they compose the
1140/// round-trip contract every tagged-union `.variant()` site pins
1141/// via the substrate testkit [`assert_variant_round_trip`]:
1142/// `k.select(&parent).map(|v| v.variant_kind()) == Some(k)` on the
1143/// populated side, and `parent.variant().unwrap().variant_kind() == k`
1144/// through the [`TaggedUnion::variant`] resolver's default body.
1145///
1146/// Every borrowed-view enum on `ProcessSpec`'s tagged-union axis
1147/// ([`crate::intent::IntentVariant<'_>`],
1148/// [`crate::lifetime::LifetimeVariant<'_>`],
1149/// [`crate::encapsulates::EncapsulationKindVariant<'_>`],
1150/// [`crate::export::ArtifactVariant<'_>`],
1151/// [`crate::export::ChannelVariant<'_>`]) pre-lift restated the same
1152/// `match self { Self::A(_) => K::A, Self::B(_) => K::B, ... }`
1153/// per-arm mapping at its own inherent method (named `.kind()` on
1154/// four of five sites; `.target()` on
1155/// [`crate::encapsulates::EncapsulationKindVariant`] where the
1156/// discriminator's semantic role is a target of encapsulation, not
1157/// a kind of parent). The reverse-projection body must stay
1158/// per-implementor — it names the ground-truth arm-to-Kind mapping
1159/// only the site knows — but the CONTRACT lives at ONE typed
1160/// surface so:
1161///
1162/// * Every downstream generic consumer binds through
1163///   `<T::Variant<'_> as VariantKind<T::Kind>>::variant_kind(&v)`
1164///   instead of a per-parent inherent-method restatement.
1165/// * [`VariantSelector<P>::Variant<'a>`] bounds this trait — a
1166///   fifth sibling that adds `impl VariantSelector<P> for XKind`
1167///   without the peer `impl VariantKind<XKind> for XVariant<'_>`
1168///   fails at the associated-type bound, so the reverse projection
1169///   is closed at compile-time across every implementor.
1170/// * The generic testkit [`assert_variant_round_trip`] composes
1171///   `select` (forward) with `variant_kind` (reverse) at ONE
1172///   substrate site — the four sibling
1173///   `_kind_round_trips_through_variant_kind` /
1174///   `_target_round_trips_through_variant_target` test bodies
1175///   collapse to one-line invocations.
1176///
1177/// The trait method is named [`Self::variant_kind`] rather than
1178/// `kind` to avoid shadowing the inherent `.kind()` (or
1179/// `.target()`) methods each borrowed-view enum already publishes.
1180/// Every impl body is a one-line delegation to the site's inherent
1181/// method — the substrate stays the projection, not the mapping.
1182pub trait VariantKind<K: Copy + 'static> {
1183    /// Project a borrowed-variant view back into its addressing
1184    /// closed-set `K` discriminator. Round-trips the closed set on
1185    /// the populated side against [`VariantSelector::select`] — a
1186    /// value returned by `k.select(&parent).unwrap()` must satisfy
1187    /// `variant_kind() == k`, and a value returned by
1188    /// `parent.variant().unwrap()` must satisfy `variant_kind() ==
1189    /// k` for the populated slot's `k`.
1190    fn variant_kind(&self) -> K;
1191}
1192
1193/// Generic round-trip testkit — pins that
1194/// [`VariantSelector::select`] (forward projection) and
1195/// [`VariantKind::variant_kind`] (reverse projection) compose the
1196/// closed set in both directions on the populated side.
1197///
1198/// Substrate primitive for the four sibling
1199/// `_kind_round_trips_through_variant_kind` /
1200/// `_target_round_trips_through_variant_target` tests on
1201/// `ProcessSpec` ([`crate::intent::Intent`],
1202/// [`crate::encapsulates::EncapsulationKind`],
1203/// [`crate::export::ArtifactSource`],
1204/// [`crate::export::VectorChannel`]) that pre-lift each restated the
1205/// same two-arm round-trip probe at their own test bodies:
1206///
1207/// 1. For each `k in K::ALL`, construct a parent with only slot `k`
1208///    populated (via a site-local `single_slot_X(k) -> Parent`
1209///    helper).
1210/// 2. Assert that `k.select(&parent).unwrap().variant_kind() == k`
1211///    (the forward-then-reverse round-trip).
1212/// 3. Assert that `parent.variant().unwrap().variant_kind() == k`
1213///    (the resolver-then-reverse round-trip).
1214///
1215/// Post-lift each site's round-trip test collapses to ONE
1216/// `assert_variant_round_trip::<T, _>(single_slot_X)` invocation
1217/// whose body is the substrate primitive's own dispatch. A fifth
1218/// sibling picks up the round-trip check through ONE call site.
1219///
1220/// The `make_parent` closure stays per-site — every one of the four
1221/// production sites already owns a
1222/// `single_slot_intent(k) / single_slot_source(k) /
1223/// single_slot_channel(k) / single_slot_kind(t)` helper that
1224/// constructs a minimally-valid parent with the addressed slot's
1225/// inner spec populated; the closure IS the round-trip's ground
1226/// truth for "populate slot k", and lifting it into the primitive
1227/// would collapse the per-site construction knowledge that stays
1228/// deliberately local.
1229///
1230/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
1231/// — `Lifetime` doesn't impl [`TaggedUnion`] (its `variant()` returns
1232/// `Ok(Permanent)` on empty, not an `Empty` typed error), so the
1233/// `<T: TaggedUnion>` bound doesn't reach it. Its per-site
1234/// round-trip test binds through [`VariantKind`] directly on
1235/// [`crate::lifetime::LifetimeVariant`] instead.
1236#[track_caller]
1237pub fn assert_variant_round_trip<T, F>(make_parent: F)
1238where
1239    T: TaggedUnion,
1240    T::Kind: PartialEq + std::fmt::Debug,
1241    F: Fn(T::Kind) -> T,
1242{
1243    for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
1244        .iter()
1245        .copied()
1246    {
1247        let parent = make_parent(k);
1248        let selected = k.select(&parent).unwrap_or_else(|| {
1249            panic!("VariantSelector::select must return Some for populated slot {k:?}")
1250        });
1251        assert_eq!(
1252            <<T::Kind as VariantSelector<T>>::Variant<'_> as VariantKind<T::Kind>>::variant_kind(
1253                &selected,
1254            ),
1255            k,
1256            "select→variant_kind round-trip failed for {k:?}",
1257        );
1258        let resolved = parent.variant().ok().unwrap_or_else(|| {
1259            panic!("TaggedUnion::variant must resolve exactly-one populated for {k:?}")
1260        });
1261        assert_eq!(
1262            <<T::Kind as VariantSelector<T>>::Variant<'_> as VariantKind<T::Kind>>::variant_kind(
1263                &resolved,
1264            ),
1265            k,
1266            "variant()→variant_kind resolver disagreed on {k:?}",
1267        );
1268    }
1269}
1270
1271/// Declarative surface that names the (Kind, Error, KIND_LIST) triple
1272/// a tagged-union `.variant()` site publishes to the substrate — and
1273/// provides the sweep body as ONE default method every implementor
1274/// picks up for free.
1275///
1276/// Every one of the four production `.variant()` sites on `ProcessSpec`
1277/// ([`crate::intent::Intent`], [`crate::encapsulates::EncapsulationKind`],
1278/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
1279/// exposes the SAME three-piece surface: a closed-set discriminator
1280/// [`Self::Kind`], a typed [`Self::Error`] carrier that projects onto
1281/// the shared [`TaggedUnionError`] contract, and a slash-joined
1282/// operator diagnostic literal [`Self::KIND_LIST`]. Pre-lift the
1283/// triple lived on each parent type as independent inherent items —
1284/// the (Kind, Error) types cross-referenced only by module-doc prose,
1285/// the `KIND_LIST` `&'static str` maintained separately at each site
1286/// alongside the inherent `.variant()` body. Post-lift the trait
1287/// binds the three onto ONE typed contract per parent so downstream
1288/// generic code binds to `<T: TaggedUnion>` instead of restating the
1289/// per-parent quadruple of associated names.
1290///
1291/// The [`Self::variant`] default method is the substrate primitive
1292/// every inherent `.variant()` on the four production sites delegates
1293/// to — one-line inherent forwarders preserve the load-bearing
1294/// calling convention (so no downstream callsite needs
1295/// `use crate::tagged_union::TaggedUnion` to reach `.variant()`) while
1296/// the resolve-sweep body lives at ONE substrate site. Adding a fifth
1297/// sibling means ONE `impl TaggedUnion` block + ONE
1298/// `impl VariantSelector<Self>` block on the sibling `Kind` + ONE
1299/// one-line inherent forwarder — no re-authored 5-line
1300/// `resolve_or_err(K::ALL.into_iter().map(|k| k.select(self)),
1301/// KIND_LIST)` sweep body.
1302///
1303/// The `Kind` type is bound to [`tatara_closed_set::ClosedSet`] so
1304/// generic testkit primitives (starting with
1305/// [`assert_kind_list_matches_closed_set`]) can compose
1306/// `<Self::Kind as ClosedSet>::labels_joined("/")` against
1307/// [`Self::KIND_LIST`] byte-identically across every implementor —
1308/// the diagnostic-stability invariant every sibling pre-lift pinned
1309/// through a hand-rolled per-site test body. It is additionally
1310/// bound to [`VariantSelector<Self>`] so [`Self::variant`]'s default
1311/// body reaches `k.select(self)` generically.
1312///
1313/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY not routed
1314/// through this trait — its `variant()` returns `Ok(Permanent)` on
1315/// empty rather than an `Empty` typed error, so its projection shape
1316/// diverges from the four Empty-projecting siblings. Same reasoning
1317/// as [`resolve_or_err`]'s explicit exclusion of `Lifetime`.
1318pub trait TaggedUnion: Sized {
1319    /// The closed-set discriminator over this tagged-union's variants.
1320    /// Bound to [`tatara_closed_set::ClosedSet`] so the generic
1321    /// diagnostic-stability testkit ([`assert_kind_list_matches_closed_set`])
1322    /// can project `<Self::Kind as ClosedSet>::labels_joined("/")`
1323    /// against [`Self::KIND_LIST`] byte-identically. Additionally
1324    /// bound to [`VariantSelector<Self>`] so [`Self::variant`]'s
1325    /// default body can dispatch `k.select(self)` at each
1326    /// [`ClosedSet::ALL`] entry generically.
1327    type Kind: tatara_closed_set::ClosedSet + VariantSelector<Self>;
1328
1329    /// The typed error carrier returned by the parent's inherent
1330    /// `.variant()` method — projects onto the shared
1331    /// [`TaggedUnionError`] contract so [`resolve_or_err`]'s two-arm
1332    /// dispatch reaches every implementor uniformly.
1333    type Error: TaggedUnionError;
1334
1335    /// Slash-joined operator diagnostic literal — the payload of
1336    /// [`TaggedUnionError::empty`] when no slot is populated on this
1337    /// tagged union. Pinned against
1338    /// `<Self::Kind as tatara_closed_set::ClosedSet>::labels_joined("/")`
1339    /// by [`assert_kind_list_matches_closed_set`] so a variant added
1340    /// to `Self::Kind` without updating this constant (or a renamed
1341    /// variant) fails-loudly at the testkit boundary.
1342    const KIND_LIST: &'static str;
1343
1344    /// Sweep over every [`Self::Kind`] discriminator in
1345    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order,
1346    /// projecting each into the parent's borrowed variant view via
1347    /// [`VariantSelector::select`], and resolve to exactly one populated
1348    /// variant through [`resolve_or_err`]. Errors on zero (with
1349    /// [`Self::KIND_LIST`] carried on the [`TaggedUnionError::empty`]
1350    /// arm) or many.
1351    ///
1352    /// The substrate primitive every one of the four production
1353    /// `.variant()` sites on `ProcessSpec` dispatches through — the
1354    /// per-parent inherent `.variant()` is a one-line delegation to
1355    /// this default so the calling convention (`intent.variant()`,
1356    /// `channel.variant()`, ...) stays load-bearing at the callsite
1357    /// without every consumer picking up `use TaggedUnion`.
1358    ///
1359    /// Adding a fifth sibling picks up this body for free — no
1360    /// re-authored `resolve_or_err(...)` sweep at the impl block.
1361    fn variant(&self) -> Result<<Self::Kind as VariantSelector<Self>>::Variant<'_>, Self::Error> {
1362        resolve_or_err(
1363            <Self::Kind as tatara_closed_set::ClosedSet>::ALL
1364                .iter()
1365                .copied()
1366                .map(|k| k.select(self)),
1367            Self::KIND_LIST,
1368        )
1369    }
1370
1371    /// Widened peer of [`Self::has`] — projects a `&'a Self` borrow
1372    /// into the optional borrowed-variant view addressed by `kind`,
1373    /// or `None` when the matching slot on `Self` is empty.
1374    ///
1375    /// One-liner that delegates to [`VariantSelector::select`] on the
1376    /// closed-set discriminator; the substrate primitive both
1377    /// [`Self::has`] (via the default `self.find(kind).is_some()`
1378    /// body) and future diagnostic consumers (an operator-facing
1379    /// require-tag classifier that reads the populated slot's inner
1380    /// payload for a `param.key=value` message, a coherence check
1381    /// that projects the borrowed variant into its
1382    /// [`VariantKind::variant_kind`] Kind for round-trip validation
1383    /// without going through the resolver's Empty/Ambiguous carriers)
1384    /// compose against.
1385    ///
1386    /// # Sibling to [`Self::has`]
1387    ///
1388    /// One refinement wider: `has` collapses the return to a `bool`;
1389    /// `find` returns the matching borrowed [`VariantSelector::Variant`]
1390    /// so callers can read the populated slot's inner spec without
1391    /// re-projecting through `kind.select(self)` at the callsite (and
1392    /// without pulling `use VariantSelector` into scope). The default
1393    /// body of `has` is `self.find(kind).is_some()` — the two methods
1394    /// share ONE walk semantics by construction, so a regression that
1395    /// drifted the presence probe from the widened probe becomes
1396    /// structurally impossible past the trait boundary.
1397    ///
1398    /// # Peer to [`crate::boundary::ConditionSliceExt::find_kind`]
1399    ///
1400    /// Same shape, same axis, second instance in the workspace-wide
1401    /// `(K) -> Option<&V>` widened presence-probe algebra:
1402    /// [`ConditionSliceExt::find_kind`] returns `Option<&Condition>`
1403    /// on the slice-level ONE-shape probe; `find` here returns
1404    /// `Option<Variant<'_>>` on the tagged-union parent-level
1405    /// N-slot probe. Both refine their `has_kind` / `has` bool peer
1406    /// through the same `find(...).is_some()` composition law.
1407    ///
1408    /// # Semantics
1409    ///
1410    /// Returns `Some(v)` where `v` is the borrowed-view projection of
1411    /// the populated slot addressed by `kind`, or `None` iff that
1412    /// slot is `None`. Byte-for-byte equivalent to
1413    /// `kind.select(self)`; existing `k.select(&parent)` callsites
1414    /// route through this inherent surface after the macro-emitted
1415    /// forwarder lands.
1416    fn find(&self, kind: Self::Kind) -> Option<<Self::Kind as VariantSelector<Self>>::Variant<'_>> {
1417        kind.select(self)
1418    }
1419
1420    /// Presence probe — does this tagged union carry a populated
1421    /// slot addressed by the given closed-set discriminator?
1422    ///
1423    /// Default body: `self.find(kind).is_some()`. The presence half
1424    /// of the resolve contract, without allocating an [`Self::Error`]
1425    /// carrier when the caller only needs the yes/no answer.
1426    /// Substrate primitive for closed-set-driven dispatch tables
1427    /// (e.g. tatara-check's `intent-<kind>` requires-tag sweep) where
1428    /// a hand-authored per-slot `spec.<field>.is_some()` chain
1429    /// otherwise drifts from the
1430    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
1431    /// enumeration as new variants land.
1432    ///
1433    /// Every one of the four production `.variant()` sites on
1434    /// `ProcessSpec` picks this up for free through the trait default
1435    /// — the [`declare_tagged_union_impls!`] macro emits a one-line
1436    /// inherent forwarder so `intent.has(kind)` reads at consumer
1437    /// callsites without `use TaggedUnion`. Adding a fifth sibling
1438    /// picks up the presence probe with zero re-authored body.
1439    fn has(&self, kind: Self::Kind) -> bool {
1440        self.find(kind).is_some()
1441    }
1442
1443    /// Closed-set-complement peer of [`Self::has`] — `true` iff the
1444    /// given `kind` is MISSING (its slot on this tagged union is
1445    /// empty). The definitional dual of the presence probe on the
1446    /// MISSING axis.
1447    ///
1448    /// Default body: `!self.has(kind)`. One bit-flip; the primitive
1449    /// value here is naming — every consumer that reads "the missing
1450    /// set contains `kind`" or "the parent lacks this dependency"
1451    /// gets a first-class typed predicate whose call-site text reads
1452    /// correctly on the missing axis, without inverting the reader's
1453    /// parse of `!parent.has(...)` at every site.
1454    ///
1455    /// # Sibling to [`Self::has`]
1456    ///
1457    /// Closed-set-complement peer on the (populated, missing)
1458    /// duality: `has(kind)` names parents whose POPULATED set
1459    /// contains `kind`; `lacks(kind)` names parents whose MISSING
1460    /// set contains `kind`. The definitional complement law
1461    /// `lacks(kind) == !has(kind)` holds on every arm and every kind
1462    /// — pinned as a first-class typed invariant by the trait's own
1463    /// default body and swept substrate-wide by
1464    /// [`assert_lacks_matches_has_complement`].
1465    ///
1466    /// # Sibling to [`Self::lacks_only`]
1467    ///
1468    /// Kind-scoped strict-refinement peer on the MISSING axis:
1469    /// `lacks(kind)` is the SUBSET predicate (`kind` missing, maybe
1470    /// others too); `lacks_only(kind)` is the EQUAL predicate
1471    /// (`kind` missing AND ONLY `kind`). The implication
1472    /// `lacks_only(kind) → lacks(kind)` binds the pair on the
1473    /// strict-refinement axis — byte-for-byte missing-axis peer of
1474    /// the populated-axis `has_only(kind) → has(kind)` implication.
1475    /// Together with `has(kind)`, `has_only(kind)`, and
1476    /// `lacks_only(kind)` the four predicates close the 2×2
1477    /// (populated, missing) × (subset, equal) grid on the
1478    /// kind-scoped tagged-union axis.
1479    ///
1480    /// # Truth table on the exactly-one-slot tagged-union contract
1481    ///
1482    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
1483    /// cardinality `N ≥ 2` and a fixed argument `kind`:
1484    ///
1485    /// - Empty parent (0 populated, N missing): `true` — every kind
1486    ///   is missing, so any `kind` satisfies the predicate.
1487    /// - Well-formed parent with `kind` populated (1 populated ==
1488    ///   kind): `false` — the populated slot addresses `kind`, so
1489    ///   `kind` is not missing.
1490    /// - Well-formed parent with OTHER kind populated (1 populated
1491    ///   != kind): `true` — the sole populated slot is not `kind`,
1492    ///   so `kind` is missing.
1493    /// - Saturated parent (N populated, 0 missing): `false` — every
1494    ///   kind is populated, so `kind` is not missing.
1495    ///
1496    /// # Kind-domain cardinality
1497    ///
1498    /// `<Self::Kind as ClosedSet>::ALL.iter().filter(|k| parent.lacks(*k)).count()
1499    /// == parent.missing_kind_count()` — the count of kinds
1500    /// satisfying `lacks` on any arm is exactly the parent's
1501    /// missing-slot count. Closed-set-complement peer of the
1502    /// populated-axis law `count k where has(k) ==
1503    /// populated_kind_count()`. Binds the kind-scoped SUBSET
1504    /// primitive on the missing axis to the arg-less cardinality
1505    /// scalar at ONE substrate site.
1506    ///
1507    /// # Compounding future consumers
1508    ///
1509    /// - Any consumer whose semantic reading is "the missing set
1510    ///   contains this kind" — a "still missing: <kind>" diagnostic,
1511    ///   a `lacks-<kind>` require-tag classifier arm, a
1512    ///   dependency-satisfaction check — reads `parent.lacks(kind)`
1513    ///   through the inherent surface rather than negating
1514    ///   `parent.has(kind)` at the call site. The primitive costs
1515    ///   one bit-flip past [`Self::has`]; the reader-facing win is
1516    ///   that `!parent.has(k)` no longer needs to be re-parsed as
1517    ///   "the missing set contains k" at every missing-axis call
1518    ///   site.
1519    /// - The kind-scoped implication
1520    ///   `lacks_only(kind) → lacks(kind)` becomes a first-class
1521    ///   typed law binding [`Self::lacks_only`] to `lacks` on the
1522    ///   strict-refinement axis — byte-for-byte missing-axis peer
1523    ///   of `has_only(kind) → has(kind)`.
1524    ///
1525    /// A new [`Self::Kind`] variant added to
1526    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
1527    /// this primitive mechanically through the delegated
1528    /// [`Self::has`] — the closed-set walk extended by
1529    /// [`Self::has`]'s default body composition picks up the new
1530    /// slot at every downstream callsite without further per-caller
1531    /// edit.
1532    ///
1533    /// # Theory grounding
1534    ///
1535    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
1536    ///   The closed-set-complement projection lives at ONE substrate
1537    ///   site as a definitional negation of [`Self::has`]. The
1538    ///   complement law `lacks(kind) == !has(kind)` and the
1539    ///   kind-scoped implication `lacks_only(kind) → lacks(kind)`
1540    ///   are pinned across every production tagged union at compile
1541    ///   time via the trait's default body composition, not
1542    ///   per-parent.
1543    /// - THEORY.md §VI.1 — generation over composition. A new
1544    ///   [`Self::Kind`] variant added to `ALL` reaches this
1545    ///   primitive mechanically through the delegated [`Self::has`]
1546    ///   — every downstream consumer sees the widened kind set
1547    ///   without further per-caller edit.
1548    fn lacks(&self, kind: Self::Kind) -> bool {
1549        !self.has(kind)
1550    }
1551
1552    /// Closed-set-inversion refinement — enumerate the set of
1553    /// [`Self::Kind`] discriminators whose corresponding slot on
1554    /// `self` is populated, in canonical
1555    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order.
1556    ///
1557    /// Default body:
1558    /// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k| self.has(*k)).collect()`.
1559    /// A tagged-union parent that satisfies the exactly-one-slot
1560    /// contract returns a `Vec` of length 0 (empty parent — matches
1561    /// [`Self::variant`]'s `Empty` arm) or 1 (well-formed — matches
1562    /// the `Ok` arm); a malformed parent with multiple populated
1563    /// slots returns a `Vec` of length ≥ 2 in canonical `ALL` order
1564    /// (matches the `Ambiguous` arm and NAMES which slots are
1565    /// populated, unlike the payload-free `Ambiguous` carrier).
1566    ///
1567    /// # Sibling to [`Self::has`] / [`Self::find`]
1568    ///
1569    /// One refinement wider on the ORTHOGONAL axis: `has(k) / find(k)`
1570    /// fix a `Self::Kind` and vary the return type (`bool` /
1571    /// `Option<Variant>`); this refinement INVERTS the axis by fixing
1572    /// the parent and varying over `Kind::ALL`, returning the SET of
1573    /// populated kinds. The composition law
1574    /// `populated_kinds().contains(&k) == has(k)` for every
1575    /// `k ∈ Kind::ALL` binds the two axes structurally through the
1576    /// default body — a regression that overrode `populated_kinds`
1577    /// to skip a kind, return duplicates, or drift the walk order
1578    /// surfaces at the substrate testkit
1579    /// [`assert_populated_kinds_matches_has`].
1580    ///
1581    /// # Peer to [`crate::boundary::ConditionSliceExt::distinct_kinds`]
1582    ///
1583    /// Same shape, same axis, second instance in the workspace-wide
1584    /// closed-set-inversion refinement algebra:
1585    /// [`ConditionSliceExt::distinct_kinds`] returns
1586    /// `Vec<ConditionKind>` on the slice-level presence-probe axis
1587    /// (fixes the slice, varies over `ConditionKind::ALL`);
1588    /// `populated_kinds` here returns `Vec<Self::Kind>` on the
1589    /// tagged-union parent-level presence-probe axis (fixes the
1590    /// parent, varies over `<Self::Kind as ClosedSet>::ALL`). Both
1591    /// refine their `has(k) / has_kind(k)` bool peer through the
1592    /// same `ALL.filter(has).collect()` composition law.
1593    ///
1594    /// # Compounding future consumers
1595    ///
1596    /// - An operator-facing `Ambiguous(Vec<Kind>)` diagnostic that
1597    ///   NAMES which slots collide (upgrading the payload-free
1598    ///   [`TaggedUnionError::ambiguous`] carrier without touching the
1599    ///   resolver's short-circuit) reads `parent.populated_kinds()`
1600    ///   directly on the malformed arm.
1601    /// - A closed-set audit dispatcher that enumerates every
1602    ///   populated slot for a fleet-wide "which parents carry
1603    ///   {Container, Nix, Aplicacao}" query reaches ONE substrate
1604    ///   primitive rather than paying for a per-kind `has(k)` sweep
1605    ///   at every callsite.
1606    /// - A hypothetical `populated-kind-count-<n>` require-tag
1607    ///   classifier prefix family that publishes the populated-set
1608    ///   cardinality as a scalar reads `parent.populated_kinds().len()`.
1609    ///
1610    /// A new [`Self::Kind`] variant added to
1611    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
1612    /// this primitive mechanically (the closed-set walk picks up the
1613    /// new entry) and every downstream consumer sees the wider set
1614    /// without further per-caller edit.
1615    ///
1616    /// # Theory grounding
1617    ///
1618    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
1619    ///   The closed-set-inversion refinement lives at ONE substrate
1620    ///   site as a typed projection of [`Self::has`] over the closed
1621    ///   set `<Self::Kind as ClosedSet>::ALL`. Every downstream
1622    ///   aggregate consumer binds through the SAME shape rather
1623    ///   than restating the `ALL`-filter closure body.
1624    /// - THEORY.md §VI.1 — generation over composition. A new
1625    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
1626    ///   mechanically and every downstream consumer sees the wider
1627    ///   set with no per-caller edit.
1628    fn populated_kinds(&self) -> ::std::vec::Vec<Self::Kind> {
1629        <Self::Kind as tatara_closed_set::ClosedSet>::ALL
1630            .iter()
1631            .copied()
1632            .filter(|k| self.has(*k))
1633            .collect()
1634    }
1635
1636    /// Scalar cardinality refinement on the closed-set-inversion axis —
1637    /// the number of [`Self::Kind`] discriminators whose corresponding
1638    /// slot on `self` is populated.
1639    ///
1640    /// Default body:
1641    /// `<Self::Kind as ClosedSet>::ALL.iter().copied().filter(|k| self.has(*k)).count()`
1642    /// — a closed-set walk that composes against [`Self::has`] per
1643    /// variant WITHOUT materializing an intermediate `Vec`. A tagged-
1644    /// union parent that satisfies the exactly-one-slot contract
1645    /// returns `0` (empty — matches [`Self::variant`]'s `Empty` arm),
1646    /// `1` (well-formed — matches the `Ok` arm), or `≥ 2` (malformed
1647    /// — matches the `Ambiguous` arm) exactly aligned with
1648    /// [`Self::populated_kinds`]`().len()` but without paying for the
1649    /// heap allocation and dealloc a caller only needing the scalar
1650    /// cardinality otherwise pays.
1651    ///
1652    /// # Sibling to [`Self::populated_kinds`]
1653    ///
1654    /// Scalar projection of the closed-set-inversion widened primitive
1655    /// — where `populated_kinds` returns the SET (a `Vec<Self::Kind>`
1656    /// in canonical `ClosedSet::ALL` order), `populated_kind_count`
1657    /// collapses that set to its cardinality. The composition law
1658    /// `populated_kind_count() == populated_kinds().len()` binds the
1659    /// scalar projection to the widened primitive at the trait's
1660    /// default body — a regression that overrode
1661    /// `populated_kind_count` to skip a kind, double-count a slot, or
1662    /// drift the walk from `ClosedSet::ALL` surfaces at the substrate
1663    /// testkit
1664    /// [`assert_populated_kind_count_matches_populated_kinds`].
1665    ///
1666    /// # Peer to [`crate::boundary::ConditionSliceExt::count_kind`]
1667    ///
1668    /// Not a direct peer — `count_kind(k)` on the slice-level axis
1669    /// fixes a `ConditionKind` and returns the per-kind cardinality
1670    /// (how many `Condition`s in the slice carry `k`);
1671    /// `populated_kind_count` on the tagged-union parent-level axis
1672    /// INVERTS by fixing the parent and returning the cardinality of
1673    /// the populated-kind SET (how many distinct slots on the parent
1674    /// are populated). The distinct peer to `count_kind` on the
1675    /// tagged-union axis would be a hypothetical `populated_slots(k)
1676    /// -> usize` — but since every tagged-union slot is `Option<T>`
1677    /// (populated or not, cardinality ∈ {0, 1}), that peer reduces
1678    /// to `has(k) as usize` and doesn't earn its own name. The
1679    /// canonical scalar peer on the tagged-union axis is this
1680    /// closed-set-inversion cardinality.
1681    ///
1682    /// # Sibling of [`Self::has`] / [`Self::find`] / [`Self::populated_kinds`]
1683    ///
1684    /// Fourth refinement on the tagged-union presence-probe algebra,
1685    /// scalar-valued on the closed-set-inversion axis: `has` collapses
1686    /// per-kind presence to a `bool`, `find` widens per-kind to
1687    /// `Option<Variant>`, `populated_kinds` inverts to the SET of
1688    /// populated kinds, and `populated_kind_count` scalar-projects
1689    /// that set to its cardinality. Every downstream consumer picks
1690    /// the coarsest refinement that answers its question — a
1691    /// `populated-kind-count-<n>` require-tag classifier prefix
1692    /// (called out in [`Self::populated_kinds`]'s doc-comment as a
1693    /// hypothetical compounding-future consumer) now reaches
1694    /// `parent.populated_kind_count()` at ONE substrate site rather
1695    /// than paying for `parent.populated_kinds().len()` (with its
1696    /// intermediate heap allocation) or the per-kind
1697    /// `<Kind::ALL>.iter().filter(|k| parent.has(*k)).count()` closure
1698    /// body at the callsite.
1699    ///
1700    /// # Compounding future consumers
1701    ///
1702    /// - A `populated-kind-count-<n>` require-tag classifier prefix
1703    ///   family that publishes the populated-set cardinality as a
1704    ///   scalar (the exact use case named in
1705    ///   [`Self::populated_kinds`]'s doc-comment) reaches this ONE
1706    ///   primitive without allocating.
1707    /// - A fast-path branch on `Ambiguous`-arm callers that need to
1708    ///   distinguish "well-formed" from "malformed with N slots" reads
1709    ///   `parent.populated_kind_count() > 1` at ONE call site rather
1710    ///   than reaching for the Vec-materializing widened primitive.
1711    /// - Any coherence check that verifies "every well-formed process
1712    ///   parent has exactly one populated slot" now reads
1713    ///   `parent.populated_kind_count() == 1` at ONE site rather than
1714    ///   restating `parent.populated_kinds().len() == 1` with its
1715    ///   allocation cost, or the semantically-equivalent (but
1716    ///   parent-arm-projected) `parent.variant().is_ok()`.
1717    ///
1718    /// # Theory grounding
1719    ///
1720    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
1721    ///   The scalar cardinality lives at ONE substrate site as a
1722    ///   typed projection of [`Self::populated_kinds`] onto its
1723    ///   `.len()`, and the default body composes against
1724    ///   [`Self::has`] over the closed set `<Self::Kind as
1725    ///   ClosedSet>::ALL` byte-identically to `populated_kinds`
1726    ///   without the intermediate `Vec`. Every downstream aggregate
1727    ///   consumer binds through the SAME shape rather than paying
1728    ///   for the allocation to reach the cardinality.
1729    /// - THEORY.md §VI.1 — generation over composition. A new
1730    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
1731    ///   mechanically (the closed-set walk picks up the new entry)
1732    ///   and every downstream consumer sees the wider cardinality
1733    ///   without further per-caller edit.
1734    fn populated_kind_count(&self) -> usize {
1735        <Self::Kind as tatara_closed_set::ClosedSet>::ALL
1736            .iter()
1737            .copied()
1738            .filter(|k| self.has(*k))
1739            .count()
1740    }
1741
1742    /// Closed-set-COMPLEMENT refinement — enumerate the set of
1743    /// [`Self::Kind`] discriminators whose corresponding slot on
1744    /// `self` is EMPTY, in canonical
1745    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order.
1746    ///
1747    /// Default body:
1748    /// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k| !self.has(*k)).collect()`.
1749    /// A tagged-union parent that satisfies the exactly-one-slot
1750    /// contract returns a `Vec` of length `ALL.len()` (empty parent —
1751    /// every slot is missing, aligns with [`Self::variant`]'s `Empty`
1752    /// arm) or `ALL.len() - 1` (well-formed — every slot BUT the
1753    /// populated one is missing, aligns with the `Ok` arm); a
1754    /// malformed parent with N populated slots returns a `Vec` of
1755    /// length `ALL.len() - N` in canonical `ALL` order (aligns with
1756    /// the `Ambiguous` arm and NAMES which slots are absent,
1757    /// complementing [`Self::populated_kinds`] which NAMES which are
1758    /// populated).
1759    ///
1760    /// # Sibling to [`Self::populated_kinds`]
1761    ///
1762    /// Closed-set-complement peer of the closed-set-inversion widened
1763    /// primitive — where `populated_kinds` returns the SET of
1764    /// populated kinds, `missing_kinds` returns its COMPLEMENT within
1765    /// `ClosedSet::ALL`. The two primitives PARTITION the closed set:
1766    /// `populated_kinds() ∪ missing_kinds() == ClosedSet::ALL` and the
1767    /// two sets are disjoint. The composition law
1768    /// `missing_kinds().contains(&k) == !has(k)` for every
1769    /// `k ∈ Kind::ALL` binds the two axes structurally through the
1770    /// default body — a regression that overrode `missing_kinds` to
1771    /// skip a kind, return duplicates, or drift the walk order
1772    /// surfaces at the substrate testkit
1773    /// [`assert_missing_kinds_matches_has`].
1774    ///
1775    /// # Peer to [`crate::boundary::ConditionSliceExt::missing_kinds`]
1776    ///
1777    /// Same shape, same axis, second instance in the workspace-wide
1778    /// closed-set-complement refinement algebra:
1779    /// [`ConditionSliceExt::missing_kinds`] returns
1780    /// `Vec<ConditionKind>` on the slice-level presence-probe axis
1781    /// (fixes the slice, varies over `ConditionKind::ALL` under a
1782    /// negated predicate); `missing_kinds` here returns
1783    /// `Vec<Self::Kind>` on the tagged-union parent-level presence-
1784    /// probe axis (fixes the parent, varies over `<Self::Kind as
1785    /// ClosedSet>::ALL` under a negated predicate). Both refine their
1786    /// `has(k) / has_kind(k)` bool peer through the same
1787    /// `ALL.filter(!has).collect()` composition law — the parent-axis
1788    /// complement of the widened `populated_kinds` primitive.
1789    ///
1790    /// # Compounding future consumers
1791    ///
1792    /// - An operator-facing "which slots are still absent" diagnostic
1793    ///   on the malformed / partially-populated arm reads
1794    ///   `parent.missing_kinds()` at ONE substrate site rather than
1795    ///   paying for a negated `<Kind::ALL>.iter().filter(|k|
1796    ///   !parent.has(*k)).collect()` closure body at the callsite —
1797    ///   or the strictly-worse
1798    ///   `<Kind::ALL>.iter().filter(|k| !parent.populated_kinds().contains(k)).collect()`
1799    ///   double-loop.
1800    /// - A future require-tag classifier arm that publishes the
1801    ///   missing-set membership at fleet audit time (`missing-<kind>`
1802    ///   as the negated peer of a hypothetical `populated-<kind>`) reads
1803    ///   `parent.missing_kinds().contains(&k)` at ONE call site.
1804    /// - A hypothetical `missing-kind-count-<n>` require-tag
1805    ///   classifier prefix family that publishes the missing-set
1806    ///   cardinality as a scalar reads [`Self::missing_kind_count`]
1807    ///   (the scalar-cardinality peer of this widened primitive)
1808    ///   without allocating.
1809    ///
1810    /// A new [`Self::Kind`] variant added to
1811    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
1812    /// this primitive mechanically (the closed-set walk picks up the
1813    /// new entry on the missing side WITHOUT further per-caller edit
1814    /// — any parent that doesn't yet populate the new slot sees it
1815    /// listed as missing at every downstream callsite).
1816    ///
1817    /// # Theory grounding
1818    ///
1819    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
1820    ///   The closed-set complement lives at ONE substrate site as a
1821    ///   typed projection of [`Self::has`] over the closed set
1822    ///   `<Self::Kind as ClosedSet>::ALL` under negation. Every
1823    ///   downstream gap-analysis consumer binds through the SAME shape
1824    ///   rather than restating the negated `ALL`-filter closure body.
1825    /// - THEORY.md §VI.1 — generation over composition. A new
1826    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
1827    ///   mechanically and every downstream consumer sees the wider
1828    ///   complement without further per-caller edit.
1829    fn missing_kinds(&self) -> ::std::vec::Vec<Self::Kind> {
1830        <Self::Kind as tatara_closed_set::ClosedSet>::ALL
1831            .iter()
1832            .copied()
1833            .filter(|k| !self.has(*k))
1834            .collect()
1835    }
1836
1837    /// Scalar cardinality refinement on the closed-set-complement axis —
1838    /// the number of [`Self::Kind`] discriminators whose corresponding
1839    /// slot on `self` is EMPTY.
1840    ///
1841    /// Default body:
1842    /// `<Self::Kind as ClosedSet>::ALL.iter().copied().filter(|k| !self.has(*k)).count()`
1843    /// — a closed-set walk that composes against [`Self::has`] per
1844    /// variant under a NEGATED point-probe, WITHOUT materializing an
1845    /// intermediate `Vec`. A tagged-union parent that satisfies the
1846    /// exactly-one-slot contract returns `ALL.len()` (empty — every
1847    /// slot missing, matches [`Self::variant`]'s `Empty` arm),
1848    /// `ALL.len() - 1` (well-formed — matches the `Ok` arm), or
1849    /// `ALL.len() - N` for N-populated (malformed — matches the
1850    /// `Ambiguous` arm), exactly aligned with [`Self::missing_kinds`]
1851    /// `().len()` but without paying for the heap allocation a caller
1852    /// only needing the scalar cardinality otherwise pays.
1853    ///
1854    /// # Sibling to [`Self::missing_kinds`] / [`Self::populated_kind_count`]
1855    ///
1856    /// Scalar projection of the closed-set-complement widened primitive
1857    /// — where `missing_kinds` returns the SET (a `Vec<Self::Kind>` in
1858    /// canonical `ClosedSet::ALL` order), `missing_kind_count`
1859    /// collapses that set to its cardinality. The composition law
1860    /// `missing_kind_count() == missing_kinds().len()` binds the
1861    /// scalar projection to the widened primitive at the trait's
1862    /// default body — a regression that overrode `missing_kind_count`
1863    /// to skip a kind, double-count a slot, or drift the walk from
1864    /// `ClosedSet::ALL` surfaces at the substrate testkit
1865    /// [`assert_missing_kind_count_matches_missing_kinds`].
1866    ///
1867    /// Byte-for-byte peer of [`Self::populated_kind_count`] one axis
1868    /// over (under a negated `has` predicate): where
1869    /// `populated_kind_count` scalar-projects the closed-set-INVERSION
1870    /// widened primitive `populated_kinds`, this method scalar-projects
1871    /// the closed-set-COMPLEMENT widened primitive `missing_kinds`.
1872    /// The two scalar projections PARTITION the closed-set cardinality:
1873    /// `populated_kind_count() + missing_kind_count() ==
1874    /// <Self::Kind as ClosedSet>::ALL.len()` — the scalar consequence
1875    /// of the `(populated_kinds, missing_kinds)` partition law that
1876    /// [`assert_missing_kinds_matches_has`] pins at the widened-
1877    /// primitive layer.
1878    ///
1879    /// # Peer to [`crate::boundary::ConditionSliceExt::missing_kind_count`]
1880    ///
1881    /// Same shape at the peer axis one struct layer down: fixing the
1882    /// slice-side carrier and inverting the presence probe over the
1883    /// closed set under a negated predicate. The two primitives close
1884    /// the "closed-set-complement scalar cardinality" refinement at
1885    /// two adjacent typescape sites — one per closed-set-addressed
1886    /// slice-level refinement, one per closed-set-addressed
1887    /// tagged-union parent-level refinement (this primitive).
1888    ///
1889    /// # Compounding future consumers
1890    ///
1891    /// - A `missing-kind-count-<n>` require-tag classifier prefix
1892    ///   family that publishes the missing-set cardinality as a scalar
1893    ///   (the exact use case named in [`Self::missing_kinds`]'s
1894    ///   doc-comment as a hypothetical compounding-future consumer)
1895    ///   reaches this ONE primitive without allocating.
1896    /// - A fast-path branch on `Ambiguous`-arm callers that need to
1897    ///   distinguish "one missing slot" (well-formed exactly-one) from
1898    ///   "N missing slots" (malformed with populated_kind_count > 1)
1899    ///   reads `parent.missing_kind_count() == ALL.len() - 1` at ONE
1900    ///   call site rather than reaching for the Vec-materializing
1901    ///   widened primitive.
1902    /// - Any coherence check that verifies "every well-formed process
1903    ///   parent has exactly `ALL.len() - 1` missing slots" now reads
1904    ///   `parent.missing_kind_count() == <Kind as ClosedSet>::ALL.len() - 1`
1905    ///   at ONE site rather than restating
1906    ///   `parent.missing_kinds().len() == ALL.len() - 1` with its
1907    ///   allocation cost, or the semantically-equivalent (but
1908    ///   parent-arm-projected) `parent.variant().is_ok()`.
1909    ///
1910    /// # Theory grounding
1911    ///
1912    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
1913    ///   The scalar cardinality lives at ONE substrate site as a typed
1914    ///   projection of [`Self::missing_kinds`] onto its `.len()`, and
1915    ///   the default body composes against [`Self::has`] over the
1916    ///   closed set `<Self::Kind as ClosedSet>::ALL` under negation
1917    ///   byte-identically to `missing_kinds` without the intermediate
1918    ///   `Vec`. Every downstream aggregate consumer binds through the
1919    ///   SAME shape rather than paying for the allocation to reach the
1920    ///   cardinality.
1921    /// - THEORY.md §VI.1 — generation over composition. A new
1922    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
1923    ///   mechanically (the closed-set walk picks up the new entry on
1924    ///   the missing side WITHOUT further per-caller edit — any parent
1925    ///   that doesn't yet populate the new slot sees the cardinality
1926    ///   rise by one at every downstream callsite).
1927    fn missing_kind_count(&self) -> usize {
1928        <Self::Kind as tatara_closed_set::ClosedSet>::ALL
1929            .iter()
1930            .copied()
1931            .filter(|k| !self.has(*k))
1932            .count()
1933    }
1934
1935    /// Short-circuiting `Option<Self::Kind>` peer of
1936    /// [`Self::populated_kinds`] — the FIRST populated kind on this
1937    /// tagged union in canonical
1938    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order, or
1939    /// `None` when no slot is populated.
1940    ///
1941    /// Default body:
1942    /// `<Kind as ClosedSet>::ALL.iter().copied().find(|k| self.has(*k))`
1943    /// — a closed-set walk that composes against [`Self::has`] per
1944    /// variant and SHORT-CIRCUITS at the earliest match. An empty parent
1945    /// returns `None` (matches [`Self::variant`]'s `Empty` arm); a
1946    /// well-formed parent returns `Some(k)` where `k` is the sole
1947    /// populated slot (matches the `Ok` arm's variant kind through
1948    /// [`VariantKind`]); a malformed parent with multiple populated
1949    /// slots returns `Some(k)` where `k` is the EARLIEST populated
1950    /// slot in canonical `ALL` order — a strictly more informative
1951    /// projection than the payload-free [`TaggedUnionError::ambiguous`]
1952    /// carrier, without materializing the intermediate
1953    /// `Vec<Self::Kind>` [`Self::populated_kinds`] otherwise pays for.
1954    ///
1955    /// # Sibling to [`Self::populated_kinds`] / [`Self::populated_kind_count`]
1956    ///
1957    /// Third refinement on the closed-set-inversion axis, `Option<Kind>`-
1958    /// valued: `populated_kinds` returns the SET, `populated_kind_count`
1959    /// scalar-projects that set's cardinality, and `first_populated_kind`
1960    /// scalar-projects the SET onto its earliest element. The
1961    /// composition law `first_populated_kind() ==
1962    /// populated_kinds().first().copied()` binds the earliest-element
1963    /// projection to the widened primitive at the trait's default body —
1964    /// pinned substrate-wide by
1965    /// [`assert_first_populated_kind_matches_populated_kinds`]. Both
1966    /// coarser projections agree on emptiness:
1967    /// `first_populated_kind().is_none() == (populated_kind_count() == 0)`.
1968    ///
1969    /// # Peer to [`Self::variant`] on the malformed arm
1970    ///
1971    /// On well-formed parents the two projections agree
1972    /// (`self.variant().ok().map(|v| v.variant_kind()) ==
1973    /// first_populated_kind()`). On malformed (Ambiguous) parents they
1974    /// diverge: `variant()` returns `Err(Ambiguous)` payload-free,
1975    /// while `first_populated_kind()` names the earliest populated
1976    /// slot. Operator diagnostics that want "started at X first" text
1977    /// on the Ambiguous arm reach this ONE primitive with O(1) storage
1978    /// and short-circuit walk cost, without paying for the widened
1979    /// `populated_kinds().first().copied()` allocation the
1980    /// composition law equates it to.
1981    ///
1982    /// # Compounding future consumers
1983    ///
1984    /// - An operator-facing "Ambiguous, starting at Nix" upgrade of the
1985    ///   payload-free [`TaggedUnionError::ambiguous`] carrier reads
1986    ///   `parent.first_populated_kind()` at ONE substrate site.
1987    /// - A `first-populated-<kind>` require-tag classifier arm reads
1988    ///   this primitive with no allocation, byte-for-byte symmetrical
1989    ///   with `parent.has(kind)`.
1990    /// - A fast-path branch that discriminates "empty" from "any
1991    ///   populated" reads `parent.first_populated_kind().is_some()` at
1992    ///   ONE call site rather than allocating a `Vec` through
1993    ///   `!populated_kinds().is_empty()`.
1994    ///
1995    /// # Theory grounding
1996    ///
1997    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
1998    ///   The earliest-element projection lives at ONE substrate site as
1999    ///   a typed projection of [`Self::has`] over the closed set
2000    ///   `<Self::Kind as ClosedSet>::ALL` under short-circuit walk
2001    ///   semantics. Every downstream consumer binds through the SAME
2002    ///   shape rather than reaching for
2003    ///   `populated_kinds().first().copied()` with its allocation cost.
2004    /// - THEORY.md §VI.1 — generation over composition. A new
2005    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
2006    ///   mechanically (the closed-set walk picks up the new entry) —
2007    ///   any parent that populates only the new variant returns
2008    ///   `Some(new_variant)` at every downstream callsite without
2009    ///   further per-caller edit.
2010    fn first_populated_kind(&self) -> Option<Self::Kind> {
2011        <Self::Kind as tatara_closed_set::ClosedSet>::ALL
2012            .iter()
2013            .copied()
2014            .find(|k| self.has(*k))
2015    }
2016
2017    /// Short-circuiting `Option<Self::Kind>` peer of
2018    /// [`Self::missing_kinds`] — the FIRST missing kind on this tagged
2019    /// union in canonical
2020    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order, or
2021    /// `None` when EVERY slot is populated.
2022    ///
2023    /// Default body:
2024    /// `<Kind as ClosedSet>::ALL.iter().copied().find(|k| !self.has(*k))`
2025    /// — a closed-set walk composed against [`Self::has`] per variant
2026    /// under NEGATION with SHORT-CIRCUIT at the earliest empty slot. An
2027    /// empty parent returns `Some(ALL[0])` (every slot missing, first
2028    /// hit is index 0); a well-formed parent populating slot `k`
2029    /// returns `Some(ALL[0])` if `k != ALL[0]`, else `Some(ALL[1])`
2030    /// (the earliest non-`k` entry); a saturated parent with every
2031    /// slot populated (structurally impossible on the exactly-one
2032    /// contract but semantically well-defined) returns `None`.
2033    ///
2034    /// # Sibling to [`Self::missing_kinds`] / [`Self::missing_kind_count`]
2035    ///
2036    /// Third refinement on the closed-set-complement axis,
2037    /// `Option<Kind>`-valued: `missing_kinds` returns the COMPLEMENT SET,
2038    /// `missing_kind_count` scalar-projects its cardinality, and
2039    /// `first_missing_kind` scalar-projects the SET onto its earliest
2040    /// element. The composition law `first_missing_kind() ==
2041    /// missing_kinds().first().copied()` binds the earliest-element
2042    /// projection to the widened primitive at the trait's default
2043    /// body — pinned substrate-wide by
2044    /// [`assert_first_missing_kind_matches_missing_kinds`]. Both
2045    /// coarser projections agree on saturation:
2046    /// `first_missing_kind().is_none() == (missing_kind_count() == 0)`.
2047    ///
2048    /// # Peer to [`Self::first_populated_kind`]
2049    ///
2050    /// Closed-set-complement peer of the closed-set-inversion earliest-
2051    /// element primitive under a negated `has` predicate. The two
2052    /// primitives PARTITION `ClosedSet::ALL`'s earliest-element
2053    /// projection: at least one of `first_populated_kind()` and
2054    /// `first_missing_kind()` is `Some` on any non-degenerate closed
2055    /// set (they are both `Some` iff `1 ≤ populated_kind_count() <
2056    /// ALL.len()`).
2057    ///
2058    /// # Compounding future consumers
2059    ///
2060    /// - An operator-facing "first still-unfilled dependency" diagnostic
2061    ///   on the partially-populated arm of an aggregate boundary check
2062    ///   reads `parent.first_missing_kind()` at ONE substrate site.
2063    /// - A `first-missing-<kind>` require-tag classifier arm reads this
2064    ///   primitive with no allocation, byte-for-byte symmetrical with
2065    ///   `parent.first_populated_kind()`.
2066    /// - A fast-path branch that discriminates "saturated" from "at
2067    ///   least one missing" reads `parent.first_missing_kind().is_some()`
2068    ///   at ONE call site rather than allocating through
2069    ///   `!missing_kinds().is_empty()` or paying for the full
2070    ///   `missing_kind_count() > 0` walk.
2071    ///
2072    /// # Theory grounding
2073    ///
2074    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2075    ///   The complement-earliest-element projection lives at ONE
2076    ///   substrate site as a typed projection of [`Self::has`] over the
2077    ///   closed set `<Self::Kind as ClosedSet>::ALL` under negation
2078    ///   with short-circuit walk semantics.
2079    /// - THEORY.md §VI.1 — generation over composition. A new
2080    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
2081    ///   mechanically (the closed-set walk picks up the new entry on
2082    ///   the missing side) — every downstream consumer sees the wider
2083    ///   complement's earliest hit without further per-caller edit.
2084    fn first_missing_kind(&self) -> Option<Self::Kind> {
2085        <Self::Kind as tatara_closed_set::ClosedSet>::ALL
2086            .iter()
2087            .copied()
2088            .find(|k| !self.has(*k))
2089    }
2090
2091    /// Short-circuiting `Option<Self::Kind>` peer of
2092    /// [`Self::populated_kinds`] — the LAST populated kind on this
2093    /// tagged union in canonical
2094    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order, or
2095    /// `None` when no slot is populated.
2096    ///
2097    /// Default body:
2098    /// `<Kind as ClosedSet>::ALL.iter().rev().copied().find(|k|
2099    /// self.has(*k))` — a REVERSED closed-set walk that composes
2100    /// against [`Self::has`] per variant and SHORT-CIRCUITS at the
2101    /// latest match. Byte-for-byte time-reversed peer of
2102    /// [`Self::first_populated_kind`] under identical predicate
2103    /// composition. An empty parent returns `None`; a well-formed
2104    /// parent returns `Some(k)` where `k` is the sole populated slot
2105    /// (matches the `Ok` arm's variant kind through [`VariantKind`]);
2106    /// a malformed parent with multiple populated slots returns
2107    /// `Some(k)` where `k` is the LATEST populated slot in canonical
2108    /// `ALL` order — the operator-diagnostic peer of
2109    /// [`Self::first_populated_kind`] on the malformed arm.
2110    ///
2111    /// # Sibling to [`Self::first_populated_kind`]
2112    ///
2113    /// FOURTH refinement on the closed-set-inversion axis under a
2114    /// REVERSED walk, `Option<Kind>`-valued: together with
2115    /// [`Self::first_populated_kind`] the two primitives project
2116    /// [`Self::populated_kinds`] onto its endpoint pair (earliest,
2117    /// latest). On the well-formed (exactly-one) arm they agree
2118    /// (`first_populated_kind() == last_populated_kind()` = `Some(k)`);
2119    /// on the empty arm they agree (`None`); on the malformed
2120    /// (Ambiguous) arm they disagree exactly when the populated set
2121    /// has cardinality `> 1` (the operator-diagnostic contract
2122    /// `"Ambiguous, from X to Y"` reads both projections at ONE call
2123    /// site through this trait's default bodies).
2124    ///
2125    /// The composition law `last_populated_kind() ==
2126    /// populated_kinds().last().copied()` binds the latest-element
2127    /// projection to the widened primitive at the trait's default
2128    /// body — pinned substrate-wide by
2129    /// [`assert_last_populated_kind_matches_populated_kinds`]. Both
2130    /// coarser projections agree on emptiness:
2131    /// `last_populated_kind().is_none() == (populated_kind_count() == 0)`.
2132    ///
2133    /// # Compounding future consumers
2134    ///
2135    /// - The `"Ambiguous, from X to Y"` upgrade of the payload-free
2136    ///   [`TaggedUnionError::ambiguous`] carrier reads
2137    ///   `parent.first_populated_kind()` AND
2138    ///   `parent.last_populated_kind()` at TWO substrate primitives
2139    ///   with O(1) storage on each side.
2140    /// - A `last-populated-<kind>` require-tag classifier arm reads
2141    ///   this primitive with no allocation, byte-for-byte symmetrical
2142    ///   with `parent.first_populated_kind()`.
2143    /// - A fast-path branch that discriminates "empty" from "any
2144    ///   populated" gains a REVERSED short-circuit option
2145    ///   (`parent.last_populated_kind().is_some()`) that commits to
2146    ///   the latest-populated slot's identity rather than the
2147    ///   earliest.
2148    ///
2149    /// # Theory grounding
2150    ///
2151    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2152    ///   The latest-element projection lives at ONE substrate site as
2153    ///   a typed projection of [`Self::has`] over the closed set
2154    ///   `<Self::Kind as ClosedSet>::ALL` under REVERSED short-circuit
2155    ///   walk semantics — byte-for-byte time-reversed peer of the
2156    ///   earliest-element projection.
2157    /// - THEORY.md §VI.1 — generation over composition. A new
2158    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
2159    ///   mechanically (the reversed closed-set walk picks up the new
2160    ///   entry at its canonical `ALL` position) — every downstream
2161    ///   consumer sees the wider latest-hit projection with no
2162    ///   per-caller edit.
2163    fn last_populated_kind(&self) -> Option<Self::Kind> {
2164        <Self::Kind as tatara_closed_set::ClosedSet>::ALL
2165            .iter()
2166            .rev()
2167            .copied()
2168            .find(|k| self.has(*k))
2169    }
2170
2171    /// Short-circuiting `Option<Self::Kind>` peer of
2172    /// [`Self::missing_kinds`] — the LAST missing kind on this tagged
2173    /// union in canonical
2174    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order, or
2175    /// `None` when EVERY slot is populated.
2176    ///
2177    /// Default body:
2178    /// `<Kind as ClosedSet>::ALL.iter().rev().copied().find(|k|
2179    /// !self.has(*k))` — a REVERSED closed-set walk composed against
2180    /// [`Self::has`] per variant under NEGATION with SHORT-CIRCUIT at
2181    /// the latest empty slot. Byte-for-byte time-reversed peer of
2182    /// [`Self::first_missing_kind`] under identical predicate
2183    /// composition. An empty parent returns `Some(ALL[ALL.len()-1])`
2184    /// (every slot missing, latest hit is the last index); a well-
2185    /// formed parent populating slot `k` returns
2186    /// `Some(ALL[ALL.len()-1])` when `k != ALL[ALL.len()-1]`, else
2187    /// `Some(ALL[ALL.len()-2])` (the latest non-`k` entry); a
2188    /// saturated parent returns `None`.
2189    ///
2190    /// # Sibling to [`Self::first_missing_kind`]
2191    ///
2192    /// FOURTH refinement on the closed-set-complement axis under a
2193    /// REVERSED walk, `Option<Kind>`-valued: together with
2194    /// [`Self::first_missing_kind`] the two primitives project
2195    /// [`Self::missing_kinds`] onto its endpoint pair (earliest,
2196    /// latest). The composition law `last_missing_kind() ==
2197    /// missing_kinds().last().copied()` binds the latest-element
2198    /// projection to the widened primitive at the trait's default
2199    /// body — pinned substrate-wide by
2200    /// [`assert_last_missing_kind_matches_missing_kinds`]. Both
2201    /// coarser projections agree on saturation:
2202    /// `last_missing_kind().is_none() == (missing_kind_count() == 0)`.
2203    ///
2204    /// # Endpoint partition
2205    ///
2206    /// Together with [`Self::first_populated_kind`],
2207    /// [`Self::first_missing_kind`], and [`Self::last_populated_kind`],
2208    /// this primitive closes the FOUR-corner endpoint projection of
2209    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) on the
2210    /// (populated, missing) × (earliest, latest) product — every
2211    /// endpoint-addressable coherence check reads ONE of the four at
2212    /// ONE call site without allocating a `Vec<Self::Kind>` through
2213    /// `populated_kinds()` / `missing_kinds()`.
2214    ///
2215    /// # Compounding future consumers
2216    ///
2217    /// - An operator-facing "last still-unfilled dependency"
2218    ///   diagnostic on the partially-populated arm of an aggregate
2219    ///   boundary check reads `parent.last_missing_kind()` at ONE
2220    ///   substrate site.
2221    /// - A `last-missing-<kind>` require-tag classifier arm reads this
2222    ///   primitive with no allocation, byte-for-byte symmetrical with
2223    ///   `parent.last_populated_kind()`.
2224    /// - A fast-path branch that discriminates "saturated" from "at
2225    ///   least one missing" now has two symmetric short-circuit walk
2226    ///   options (`parent.first_missing_kind().is_some()` from the
2227    ///   FORWARD walk, `parent.last_missing_kind().is_some()` from
2228    ///   the REVERSED walk) both returning the same Boolean
2229    ///   projection but committing to different endpoint disclosures.
2230    ///
2231    /// # Theory grounding
2232    ///
2233    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2234    ///   The complement-latest-element projection lives at ONE
2235    ///   substrate site as a typed projection of [`Self::has`] over
2236    ///   the closed set `<Self::Kind as ClosedSet>::ALL` under
2237    ///   REVERSED negation-and-short-circuit walk semantics.
2238    /// - THEORY.md §VI.1 — generation over composition. A new
2239    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
2240    ///   mechanically (the reversed closed-set walk picks up the new
2241    ///   entry at its canonical `ALL` position on the missing side).
2242    fn last_missing_kind(&self) -> Option<Self::Kind> {
2243        <Self::Kind as tatara_closed_set::ClosedSet>::ALL
2244            .iter()
2245            .rev()
2246            .copied()
2247            .find(|k| !self.has(*k))
2248    }
2249
2250    /// Exactly-one-populated `Option<Self::Kind>` peer of
2251    /// [`Self::populated_kinds`] — `Some(k)` iff `k` is the SOLE
2252    /// populated kind on this tagged union, else `None`.
2253    ///
2254    /// Default body walks `<Self::Kind as ClosedSet>::ALL` under
2255    /// [`Self::has`] and returns `Some(k)` iff EXACTLY ONE hit is seen,
2256    /// short-circuiting at the SECOND hit — a two-step iterator peer
2257    /// of the earliest / latest short-circuit walks whose truth-table
2258    /// projection is disjoint from `first_populated_kind` /
2259    /// `last_populated_kind` on the malformed arm (both endpoints name
2260    /// SOME populated slot on a two-populated parent, `unique` names
2261    /// `None`).
2262    ///
2263    /// # Sibling to [`Self::first_populated_kind`] / [`Self::last_populated_kind`]
2264    ///
2265    /// FIFTH refinement on the closed-set-inversion axis under
2266    /// exactly-one-hit semantics, `Option<Kind>`-valued: together with
2267    /// [`Self::first_populated_kind`] and [`Self::last_populated_kind`]
2268    /// the three primitives project [`Self::populated_kinds`] onto its
2269    /// cardinality-conditioned scalar identity. On the well-formed
2270    /// (exactly-one) arm all three agree (`unique == first == last =
2271    /// Some(k)`); on the empty arm all three agree (`None`); on the
2272    /// malformed (Ambiguous, cardinality ≥ 2) arm the three DIVERGE:
2273    /// `first`/`last` name the endpoint populated slots (Some), while
2274    /// `unique` returns `None` — the ONLY endpoint-projection primitive
2275    /// in the algebra that distinguishes well-formed from malformed at
2276    /// its return type without paying for a [`Self::variant`] error-
2277    /// carrier allocation.
2278    ///
2279    /// The composition laws
2280    /// `unique_populated_kind().is_some() == (populated_kind_count() == 1)`
2281    /// and (on the `Some` arm) `unique_populated_kind() ==
2282    /// first_populated_kind() == last_populated_kind()` bind the
2283    /// exactly-one scalar identity to the widened primitives at the
2284    /// trait's default body — pinned substrate-wide by
2285    /// [`assert_unique_populated_kind_matches_populated_kinds`].
2286    ///
2287    /// # Peer to [`Self::variant`] as a kind-only projection
2288    ///
2289    /// Byte-for-byte equivalent to
2290    /// `self.variant().ok().map(|v| v.variant_kind())` on the trait's
2291    /// exactly-one contract, but WITHOUT paying for the [`Self::Error`]
2292    /// carrier's allocation on the failing arms, and WITHOUT reaching
2293    /// [`VariantSelector::Variant`] / [`VariantKind::variant_kind`]. A
2294    /// `use TaggedUnion` scope at the consumer is enough; the borrowed
2295    /// variant view is not needed. On well-formed parents the two
2296    /// projections agree; on empty AND malformed parents they agree by
2297    /// returning `None` (unlike `first_populated_kind`, which returns
2298    /// `Some` on malformed).
2299    ///
2300    /// # Compounding future consumers
2301    ///
2302    /// - A closed-set-driven "resolved kind identity" dispatch that
2303    ///   only needs the Kind (not the borrowed variant) reads
2304    ///   `parent.unique_populated_kind()` at ONE substrate site — one
2305    ///   short-circuit walk, no error-carrier allocation, no
2306    ///   VariantKind projection.
2307    /// - A coherence check that verifies "every well-formed process
2308    ///   parent has a unique populated kind" now reads
2309    ///   `parent.unique_populated_kind().is_some()` at ONE site rather
2310    ///   than restating `parent.populated_kind_count() == 1` (which
2311    ///   discards the resolved kind identity) or
2312    ///   `parent.variant().is_ok()` (which pays for the error carrier).
2313    /// - A future require-tag classifier arm that publishes the
2314    ///   exactly-one resolved kind (`unique-populated-<kind>`) at fleet
2315    ///   audit time reads this primitive with no allocation, byte-for-
2316    ///   byte symmetrical with the `first-populated-<kind>` and
2317    ///   `last-populated-<kind>` sibling classifier families.
2318    /// - A fast-path branch on the (empty, well-formed, ambiguous)
2319    ///   trichotomy that needs to distinguish "well-formed with kind X"
2320    ///   from BOTH "empty" AND "ambiguous" reaches this primitive at
2321    ///   ONE call site: `Some(k)` names the well-formed arm's kind,
2322    ///   `None` collapses the two failing arms together.
2323    ///
2324    /// # Theory grounding
2325    ///
2326    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2327    ///   The exactly-one-hit projection lives at ONE substrate site as
2328    ///   a typed two-step-short-circuit walk over
2329    ///   `<Self::Kind as ClosedSet>::ALL` under [`Self::has`]. The
2330    ///   composition laws above compose the SAME shape as the endpoint
2331    ///   projections, differing only in the truth-table arm on the
2332    ///   malformed side.
2333    /// - THEORY.md §VI.1 — generation over composition. A new
2334    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
2335    ///   mechanically — any parent populating only the new variant
2336    ///   returns `Some(new_variant)` at every downstream callsite
2337    ///   without further per-caller edit.
2338    fn unique_populated_kind(&self) -> Option<Self::Kind> {
2339        let mut iter = <Self::Kind as tatara_closed_set::ClosedSet>::ALL
2340            .iter()
2341            .copied()
2342            .filter(|k| self.has(*k));
2343        let first = iter.next()?;
2344        match iter.next() {
2345            None => Some(first),
2346            Some(_) => None,
2347        }
2348    }
2349
2350    /// Exactly-one-missing `Option<Self::Kind>` peer of
2351    /// [`Self::missing_kinds`] — `Some(k)` iff `k` is the SOLE missing
2352    /// kind on this tagged union, else `None`.
2353    ///
2354    /// Default body walks `<Self::Kind as ClosedSet>::ALL` under a
2355    /// NEGATED [`Self::has`] predicate and returns `Some(k)` iff
2356    /// EXACTLY ONE empty slot is seen, short-circuiting at the SECOND
2357    /// empty slot. Byte-for-byte peer of
2358    /// [`Self::unique_populated_kind`] under the complement axis.
2359    ///
2360    /// # Sibling to [`Self::first_missing_kind`] / [`Self::last_missing_kind`]
2361    ///
2362    /// FIFTH refinement on the closed-set-complement axis under
2363    /// exactly-one-hit semantics, `Option<Kind>`-valued: together with
2364    /// [`Self::first_missing_kind`] and [`Self::last_missing_kind`] the
2365    /// three primitives project [`Self::missing_kinds`] onto its
2366    /// cardinality-conditioned scalar identity on the empty side. The
2367    /// composition laws
2368    /// `unique_missing_kind().is_some() == (missing_kind_count() == 1)`
2369    /// and (on the `Some` arm) `unique_missing_kind() ==
2370    /// first_missing_kind() == last_missing_kind()` bind the exactly-
2371    /// one scalar identity to the widened primitives at the trait's
2372    /// default body — pinned substrate-wide by
2373    /// [`assert_unique_missing_kind_matches_missing_kinds`].
2374    ///
2375    /// # Truth table on the exactly-one-slot tagged-union contract
2376    ///
2377    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
2378    /// cardinality `N`:
2379    ///
2380    /// - Empty parent (0 populated, N missing): `None` (N ≥ 2 missing
2381    ///   on any non-degenerate closed set, so not unique).
2382    /// - Well-formed parent (1 populated, N-1 missing): `None` when
2383    ///   `N > 2` (N-1 ≥ 2 missing, not unique), `Some(the-one-missing)`
2384    ///   when `N == 2` (exactly one missing — the peer of the
2385    ///   populated slot).
2386    /// - N-1-populated parent (structurally the missing-side peer of
2387    ///   the well-formed arm): `Some(the-lone-empty)` — the ONLY arm
2388    ///   where `unique_missing_kind` returns `Some` on a `N > 2`
2389    ///   closed set.
2390    /// - Saturated parent (N populated, 0 missing): `None`.
2391    ///
2392    /// # Peer to [`Self::unique_populated_kind`]
2393    ///
2394    /// Closed-set-complement peer of the closed-set-inversion exactly-
2395    /// one-hit primitive under a negated `has` predicate. The two
2396    /// primitives are useful in DIFFERENT structural regimes: the
2397    /// populated peer names well-formed parents (1 populated of N),
2398    /// the missing peer names the missing-side complement (1 missing
2399    /// of N). On tagged unions with `N == 2` (rare — most `ALL`s are
2400    /// ≥ 3) the two coincide (a well-formed 1-of-2 parent has 1
2401    /// missing too).
2402    ///
2403    /// # Compounding future consumers
2404    ///
2405    /// - An operator-facing "one dependency still unfulfilled: X"
2406    ///   diagnostic on an aggregate boundary check reads
2407    ///   `parent.unique_missing_kind()` at ONE substrate site — one
2408    ///   short-circuit walk, no allocation.
2409    /// - A `unique-missing-<kind>` require-tag classifier arm reads
2410    ///   this primitive with no allocation, byte-for-byte symmetrical
2411    ///   with `parent.unique_populated_kind()`.
2412    /// - A fast-path branch on the near-saturation arm that
2413    ///   discriminates "exactly one slot still empty" from "0 or ≥ 2
2414    ///   still empty" reads `parent.unique_missing_kind().is_some()`
2415    ///   at ONE call site.
2416    ///
2417    /// # Theory grounding
2418    ///
2419    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2420    ///   The complement-exactly-one-hit projection lives at ONE
2421    ///   substrate site as a typed two-step-short-circuit walk over
2422    ///   `<Self::Kind as ClosedSet>::ALL` under a negated
2423    ///   [`Self::has`] predicate — byte-for-byte peer of the
2424    ///   populated-side primitive under complement.
2425    /// - THEORY.md §VI.1 — generation over composition. A new
2426    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
2427    ///   mechanically on the missing side.
2428    fn unique_missing_kind(&self) -> Option<Self::Kind> {
2429        let mut iter = <Self::Kind as tatara_closed_set::ClosedSet>::ALL
2430            .iter()
2431            .copied()
2432            .filter(|k| !self.has(*k));
2433        let first = iter.next()?;
2434        match iter.next() {
2435            None => Some(first),
2436            Some(_) => None,
2437        }
2438    }
2439
2440    /// Boolean cardinality-endpoint peer of [`Self::populated_kinds`] —
2441    /// `true` iff NO slot on this tagged union is populated.
2442    ///
2443    /// Default body:
2444    /// `!<Self::Kind as ClosedSet>::ALL.iter().copied().any(|k| self.has(k))`
2445    /// — a short-circuiting closed-set walk under [`Self::has`] that
2446    /// returns `true` iff every point-probe returns `false`, WITHOUT
2447    /// materializing the [`Vec`] `populated_kinds` would build and
2448    /// WITHOUT paying for the `usize` `populated_kind_count` would
2449    /// count. The `!any` composition short-circuits at the FIRST
2450    /// populated slot on the non-empty arms — strictly cheaper than
2451    /// either widened primitive on every arm where the parent has ≥ 1
2452    /// populated slot.
2453    ///
2454    /// # Sibling to [`Self::populated_kind_count`]
2455    ///
2456    /// Boolean cardinality-endpoint peer of the scalar cardinality
2457    /// primitive — where `populated_kind_count` returns the FULL scalar
2458    /// (any `usize` in `0..=ALL.len()`), `is_empty` collapses that
2459    /// scalar to its zero-arm Boolean projection. The composition law
2460    /// `is_empty() == (populated_kind_count() == 0)` binds the Boolean
2461    /// projection to the scalar primitive at the trait's default body —
2462    /// swept substrate-wide by
2463    /// [`assert_is_empty_matches_populated_kind_count`]. Byte-for-byte
2464    /// symmetrical with [`Self::is_saturated`] under the (populated,
2465    /// missing) complement axis: where `is_empty` names the zero-arm
2466    /// of the populated cardinality, `is_saturated` names the zero-arm
2467    /// of the missing cardinality (equivalently, the top-arm of the
2468    /// populated cardinality — `populated_kind_count() == ALL.len()`).
2469    ///
2470    /// # Truth table on the exactly-one-slot tagged-union contract
2471    ///
2472    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
2473    /// cardinality `N ≥ 1`:
2474    ///
2475    /// - Empty parent (0 populated, N missing): `true` — the SOLE
2476    ///   arm where `is_empty` returns `true`. Aligns with
2477    ///   [`Self::variant`]'s `Empty` arm (which returns
2478    ///   [`TaggedUnionError::empty`] carrying `KIND_LIST` verbatim).
2479    ///   The [`Self::empty`](TaggedUnionError::empty) factory produces
2480    ///   parents on this arm — pins one direction of the "empty ↔
2481    ///   is_empty()" symmetry.
2482    /// - Well-formed parent (1 populated, N-1 missing): `false`.
2483    /// - K-populated parent for `1 ≤ K ≤ N`: `false`.
2484    /// - Saturated parent (N populated, 0 missing): `false`.
2485    ///
2486    /// # Compounding future consumers
2487    ///
2488    /// - A fast-path branch that discriminates "any content at all"
2489    ///   from "empty carrier" — the most common tagged-union top-level
2490    ///   guard — reads `parent.is_empty()` at ONE substrate site with
2491    ///   ONE short-circuit walk (returns at the first populated slot),
2492    ///   rather than reaching for either `populated_kind_count() == 0`
2493    ///   (which walks every slot) or `!variant().is_ok()` (which pays
2494    ///   for the borrowed-view projection and the error-carrier
2495    ///   materialization on failing arms).
2496    /// - An operator-facing "carrier missing content" diagnostic on
2497    ///   the `Empty` arm of [`Self::variant`] reads `parent.is_empty()`
2498    ///   at ONE substrate site — one short-circuit walk, no allocation,
2499    ///   no error-carrier materialization.
2500    /// - An `is-empty` require-tag classifier arm reaches this
2501    ///   primitive at ONE call site, byte-for-byte symmetrical with
2502    ///   the sibling `is-saturated` arm.
2503    /// - A coherence check verifying "every well-formed parent has at
2504    ///   least one populated slot" reads `!parent.is_empty()` at ONE
2505    ///   site rather than the widened-primitive composition
2506    ///   `!parent.populated_kinds().is_empty()` (which pays for the
2507    ///   Vec) or `parent.populated_kind_count() > 0` (which walks every
2508    ///   slot).
2509    ///
2510    /// A new [`Self::Kind`] variant added to
2511    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
2512    /// this primitive mechanically (the closed-set walk picks up the
2513    /// new entry as an additional short-circuit slot — a parent that
2514    /// populates ONLY the new variant returns `false` at every
2515    /// downstream callsite without further per-caller edit; an all-
2516    /// empty parent continues to return `true` past every entry
2517    /// including the new one).
2518    ///
2519    /// # Theory grounding
2520    ///
2521    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2522    ///   The Boolean cardinality-endpoint projection lives at ONE
2523    ///   substrate site as a typed short-circuiting closed-set walk
2524    ///   `!<Self::Kind as ClosedSet>::ALL.iter().any(has)` — byte-
2525    ///   for-byte peer of `populated_kind_count()` composed against
2526    ///   `== 0`, but without the counter allocation on every arm and
2527    ///   with a first-populated-slot short-circuit that neither
2528    ///   widened primitive offers.
2529    /// - THEORY.md §VI.1 — generation over composition. A new
2530    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
2531    ///   mechanically through the `any` short-circuit.
2532    fn is_empty(&self) -> bool {
2533        !<Self::Kind as tatara_closed_set::ClosedSet>::ALL
2534            .iter()
2535            .copied()
2536            .any(|k| self.has(k))
2537    }
2538
2539    /// Boolean cardinality-endpoint peer of [`Self::missing_kinds`] —
2540    /// `true` iff EVERY slot on this tagged union is populated (i.e.
2541    /// the missing set is empty).
2542    ///
2543    /// Default body:
2544    /// `<Self::Kind as ClosedSet>::ALL.iter().copied().all(|k| self.has(k))`
2545    /// — a short-circuiting closed-set walk under [`Self::has`] that
2546    /// returns `true` iff every point-probe returns `true`, WITHOUT
2547    /// materializing the [`Vec`] `missing_kinds` would build and
2548    /// WITHOUT paying for the `usize` `missing_kind_count` would
2549    /// count. The `all` composition short-circuits at the FIRST
2550    /// missing slot on the non-saturated arms — strictly cheaper than
2551    /// either widened primitive on every arm where the parent has ≥ 1
2552    /// missing slot.
2553    ///
2554    /// # Sibling to [`Self::missing_kind_count`]
2555    ///
2556    /// Boolean cardinality-endpoint peer of the scalar cardinality
2557    /// primitive — where `missing_kind_count` returns the FULL scalar
2558    /// (any `usize` in `0..=ALL.len()`), `is_saturated` collapses that
2559    /// scalar to its zero-arm Boolean projection. The composition law
2560    /// `is_saturated() == (missing_kind_count() == 0)` binds the
2561    /// Boolean projection to the scalar primitive at the trait's
2562    /// default body — swept substrate-wide by
2563    /// [`assert_is_saturated_matches_missing_kind_count`]. Byte-for-
2564    /// byte symmetrical with [`Self::is_empty`] under the (populated,
2565    /// missing) complement axis: where `is_empty` names the zero-arm
2566    /// of the populated cardinality, `is_saturated` names the zero-arm
2567    /// of the missing cardinality.
2568    ///
2569    /// # Truth table on the exactly-one-slot tagged-union contract
2570    ///
2571    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
2572    /// cardinality `N ≥ 1`:
2573    ///
2574    /// - Empty parent (0 populated, N missing): `false`.
2575    /// - Well-formed parent (1 populated, N-1 missing): `false` (on
2576    ///   any `N ≥ 2` closed set). On the degenerate `N == 1` closed
2577    ///   set the well-formed and saturated arms coincide — both
2578    ///   primitives return `false` on the empty arm and `true` on the
2579    ///   single-populated arm — but real-world tagged unions in this
2580    ///   workspace all have `N ≥ 2`.
2581    /// - K-populated parent for `0 ≤ K < N`: `false`.
2582    /// - Saturated parent (N populated, 0 missing): `true` — the SOLE
2583    ///   arm where `is_saturated` returns `true`.
2584    ///
2585    /// # Compounding future consumers
2586    ///
2587    /// - A fast-path branch that discriminates "over-populated"
2588    ///   (saturated, structurally malformed on any `N ≥ 2` tagged
2589    ///   union) from "well-formed or partial" reads
2590    ///   `parent.is_saturated()` at ONE substrate site with ONE short-
2591    ///   circuit walk (returns at the first missing slot), rather than
2592    ///   reaching for either `missing_kind_count() == 0` (which walks
2593    ///   every slot) or `populated_kind_count() == ALL.len()` (same
2594    ///   cost, different axis).
2595    /// - An operator-facing "over-populated carrier" diagnostic that
2596    ///   surfaces the pathological case where every slot on a `N ≥ 2`
2597    ///   tagged union is populated reads `parent.is_saturated()` at
2598    ///   ONE substrate site — one short-circuit walk, no allocation.
2599    /// - An `is-saturated` require-tag classifier arm reaches this
2600    ///   primitive at ONE call site, byte-for-byte symmetrical with
2601    ///   the sibling `is-empty` arm.
2602    /// - A coherence check verifying "no production tagged union has
2603    ///   ever been observed saturated" reads `!parent.is_saturated()`
2604    ///   at ONE site — the substrate's structural pin on the top-arm
2605    ///   of the cardinality lattice.
2606    ///
2607    /// A new [`Self::Kind`] variant added to
2608    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
2609    /// this primitive mechanically (the closed-set walk picks up the
2610    /// new entry as an additional short-circuit slot — a parent that
2611    /// was previously saturated is no longer saturated at every
2612    /// downstream callsite unless it also populates the new slot; a
2613    /// parent that populates every slot including the new one
2614    /// continues to return `true`).
2615    ///
2616    /// # Theory grounding
2617    ///
2618    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2619    ///   The Boolean cardinality-top-endpoint projection lives at ONE
2620    ///   substrate site as a typed short-circuiting closed-set walk
2621    ///   `<Self::Kind as ClosedSet>::ALL.iter().all(has)` — byte-for-
2622    ///   byte peer of `missing_kind_count()` composed against `== 0`,
2623    ///   but without the counter allocation on every arm and with a
2624    ///   first-missing-slot short-circuit that neither widened
2625    ///   primitive offers.
2626    /// - THEORY.md §VI.1 — generation over composition. A new
2627    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
2628    ///   mechanically through the `all` short-circuit.
2629    fn is_saturated(&self) -> bool {
2630        <Self::Kind as tatara_closed_set::ClosedSet>::ALL
2631            .iter()
2632            .copied()
2633            .all(|k| self.has(k))
2634    }
2635
2636    /// Boolean cardinality "at-least-one" peer of
2637    /// [`Self::populated_kinds`] — `true` iff AT LEAST ONE slot on this
2638    /// tagged union is populated (i.e. the populated set is NON-empty).
2639    ///
2640    /// Default body:
2641    /// `<Self::Kind as ClosedSet>::ALL.iter().copied().any(|k| self.has(k))`
2642    /// — a short-circuiting closed-set walk under [`Self::has`] that
2643    /// returns `true` at the FIRST populated slot, WITHOUT materializing
2644    /// the [`Vec`] `populated_kinds` would build and WITHOUT paying for
2645    /// the `usize` `populated_kind_count` would count. The `any`
2646    /// composition short-circuits at the FIRST populated slot on every
2647    /// non-empty arm — strictly cheaper than either widened primitive
2648    /// `populated_kind_count() > 0` (which walks every slot) or
2649    /// `!populated_kinds().is_empty()` (which pays for the `Vec`
2650    /// allocation before the emptiness check).
2651    ///
2652    /// # Sibling to [`Self::is_empty`]
2653    ///
2654    /// Definitional-complement Boolean peer on the SAME populated
2655    /// cardinality axis: where [`Self::is_empty`] names the zero-arm
2656    /// (0 populated), `has_any_populated_kind` names the ≥ 1 halfspace
2657    /// (any positive cardinality). The composition law
2658    /// `has_any_populated_kind() == !is_empty()` binds the two primitives
2659    /// at the trait's default body — one bit-flip past [`Self::is_empty`]'s
2660    /// `!any` short-circuit. Byte-for-byte peer of
2661    /// [`Self::has_any_missing_kind`] under the (populated, missing)
2662    /// complement axis: where `has_any_missing_kind` names the ≥ 1
2663    /// missing halfspace via the negated `has`, this primitive names
2664    /// the ≥ 1 populated halfspace via the plain `has`.
2665    ///
2666    /// # Cardinality-grid closure
2667    ///
2668    /// Third row of the Boolean cardinality grid on the tagged-union
2669    /// parent axis — the SUBSET side of the complement dichotomy between
2670    /// the zero-arm and the at-least-one halfspace. The four rows now
2671    /// close the {0, ≥1, =1, ≥2} cardinality lattice on both the
2672    /// populated and missing axes:
2673    ///
2674    /// |                | populated axis                          | missing axis                           |
2675    /// |----------------|-----------------------------------------|----------------------------------------|
2676    /// | ZERO (== 0)    | [`Self::is_empty`]                      | [`Self::is_saturated`]                 |
2677    /// | AT LEAST ONE   | `has_any_populated_kind` (this)         | [`Self::has_any_missing_kind`]         |
2678    /// | UNIQUE (== 1)  | [`Self::has_unique_populated_kind`]     | [`Self::has_unique_missing_kind`]      |
2679    /// | AT LEAST TWO   | [`Self::has_multiple_populated_kinds`]  | [`Self::has_multiple_missing_kinds`]   |
2680    ///
2681    /// The AT LEAST ONE row partitions the ZERO row's exhaustive
2682    /// complement — for any given parent, `is_empty()` and
2683    /// `has_any_populated_kind()` XOR to `true` (exactly one returns
2684    /// `true`). The row is ALSO the disjunction of the UNIQUE and AT
2685    /// LEAST TWO rows: `has_any_populated_kind() ==
2686    /// has_unique_populated_kind() || has_multiple_populated_kinds()`
2687    /// — the {=1, ≥2} refinement of the ≥ 1 halfspace at ONE substrate
2688    /// site.
2689    ///
2690    /// # Truth table on the exactly-one-slot tagged-union contract
2691    ///
2692    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
2693    /// cardinality `N ≥ 1`:
2694    ///
2695    /// - Empty parent (0 populated, N missing): `false` — the SOLE arm
2696    ///   where `has_any_populated_kind` returns `false`.
2697    /// - Well-formed parent (1 populated, N-1 missing): `true`.
2698    /// - K-populated parent for `1 ≤ K ≤ N`: `true`.
2699    /// - Saturated parent (N populated, 0 missing): `true`.
2700    ///
2701    /// # Compounding future consumers
2702    ///
2703    /// - A boundary-progress "any content at all" diagnostic on an
2704    ///   aggregate condition-carrier reads
2705    ///   `parent.has_any_populated_kind()` at ONE substrate site — one
2706    ///   short-circuit walk, no allocation, and no readerly parse of
2707    ///   `!parent.is_empty()` inversion at the callsite.
2708    /// - An `is-non-empty` require-tag classifier arm reaches this
2709    ///   primitive at ONE call site — the SUBSET peer of the sibling
2710    ///   `is-empty` classifier arm, byte-for-byte symmetrical with the
2711    ///   sibling `has-any-missing-kind` arm under the (populated,
2712    ///   missing) complement axis.
2713    /// - A fast-path branch that discriminates "some populated" from
2714    ///   "all missing" (the resolver's non-`Empty`-arm halfspace) reads
2715    ///   `parent.has_any_populated_kind()` at ONE call site — same
2716    ///   FIRST-populated-slot short-circuit as [`Self::is_empty`], no
2717    ///   inversion.
2718    /// - A coherence check verifying "every production parent from a
2719    ///   `single_slot_X` factory is NON-empty" reads
2720    ///   `parent.has_any_populated_kind()` at ONE site rather than
2721    ///   `!parent.is_empty()` (which asks the reader to invert the
2722    ///   parse) or `parent.populated_kind_count() > 0` (which walks
2723    ///   every slot).
2724    ///
2725    /// A new [`Self::Kind`] variant added to
2726    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
2727    /// this primitive mechanically — the `any` short-circuit picks up
2728    /// the new slot as an additional first-hit candidate at every
2729    /// downstream callsite without further per-caller edit.
2730    ///
2731    /// # Theory grounding
2732    ///
2733    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2734    ///   The Boolean at-least-one projection on the populated axis
2735    ///   lives at ONE substrate site as a typed short-circuiting
2736    ///   closed-set walk `<Self::Kind as ClosedSet>::ALL.iter().any(has)`
2737    ///   — byte-for-byte definitional complement of [`Self::is_empty`]'s
2738    ///   `!<ALL>.iter().any(has)`, semantically identical to
2739    ///   `populated_kind_count() > 0` on every arm with the same
2740    ///   first-hit short-circuit that [`Self::is_empty`] enjoys.
2741    /// - THEORY.md §VI.1 — generation over composition. A new
2742    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
2743    ///   mechanically through the `any` short-circuit.
2744    fn has_any_populated_kind(&self) -> bool {
2745        <Self::Kind as tatara_closed_set::ClosedSet>::ALL
2746            .iter()
2747            .copied()
2748            .any(|k| self.has(k))
2749    }
2750
2751    /// Boolean cardinality "at-least-one" peer of [`Self::missing_kinds`]
2752    /// — `true` iff AT LEAST ONE slot on this tagged union is missing
2753    /// (i.e. the missing set is NON-empty).
2754    ///
2755    /// Default body:
2756    /// `<Self::Kind as ClosedSet>::ALL.iter().copied().any(|k| !self.has(k))`
2757    /// — a short-circuiting closed-set walk under a NEGATED [`Self::has`]
2758    /// that returns `true` at the FIRST missing slot, WITHOUT
2759    /// materializing the [`Vec`] `missing_kinds` would build and WITHOUT
2760    /// paying for the `usize` `missing_kind_count` would count. The
2761    /// `any` composition short-circuits at the FIRST missing slot on
2762    /// every non-saturated arm — strictly cheaper than either widened
2763    /// primitive `missing_kind_count() > 0` (which walks every slot) or
2764    /// `!missing_kinds().is_empty()` (which pays for the `Vec`
2765    /// allocation before the emptiness check).
2766    ///
2767    /// # Sibling to [`Self::is_saturated`]
2768    ///
2769    /// Definitional-complement Boolean peer on the SAME missing
2770    /// cardinality axis: where [`Self::is_saturated`] names the zero-arm
2771    /// (0 missing), `has_any_missing_kind` names the ≥ 1 missing
2772    /// halfspace (any positive missing cardinality). The composition
2773    /// law `has_any_missing_kind() == !is_saturated()` binds the two
2774    /// primitives at the trait's default body — one bit-flip past
2775    /// [`Self::is_saturated`]'s `all` short-circuit. Byte-for-byte peer
2776    /// of [`Self::has_any_populated_kind`] under the (populated,
2777    /// missing) complement axis: where `has_any_populated_kind` names
2778    /// the ≥ 1 populated halfspace via the plain `has`, this primitive
2779    /// names the ≥ 1 missing halfspace via the negated `has`.
2780    ///
2781    /// # Cardinality-grid closure
2782    ///
2783    /// Third row of the Boolean cardinality grid on the tagged-union
2784    /// parent axis — see [`Self::has_any_populated_kind`] for the full
2785    /// grid. The disjunctive decomposition
2786    /// `has_any_missing_kind() == has_unique_missing_kind() ||
2787    /// has_multiple_missing_kinds()` binds the ≥ 1 halfspace to the
2788    /// {=1, ≥2} refinement at ONE substrate site — byte-for-byte peer
2789    /// of the populated-axis disjunctive decomposition.
2790    ///
2791    /// # Truth table on the exactly-one-slot tagged-union contract
2792    ///
2793    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
2794    /// cardinality `N ≥ 1`:
2795    ///
2796    /// - Empty parent (0 populated, N missing): `true` — the empty
2797    ///   parent has EVERY slot missing.
2798    /// - Well-formed parent (1 populated, N-1 missing): `true` on any
2799    ///   `N ≥ 2`. On the degenerate `N == 1` closed set the well-formed
2800    ///   parent has 0 missing, so `has_any_missing_kind()` returns
2801    ///   `false` — but real-world tagged unions in this workspace all
2802    ///   have `N ≥ 2`.
2803    /// - K-populated parent for `0 ≤ K < N`: `true`.
2804    /// - Saturated parent (N populated, 0 missing): `false` — the SOLE
2805    ///   arm where `has_any_missing_kind` returns `false`.
2806    ///
2807    /// # Compounding future consumers
2808    ///
2809    /// - An operator-facing "not fully populated" diagnostic on an
2810    ///   aggregate condition-carrier reads
2811    ///   `parent.has_any_missing_kind()` at ONE substrate site — one
2812    ///   short-circuit walk, no allocation, no readerly parse of
2813    ///   `!parent.is_saturated()` inversion at the callsite.
2814    /// - A `has-any-missing-kind` require-tag classifier arm reaches
2815    ///   this primitive at ONE call site — the SUBSET peer of the
2816    ///   sibling `is-saturated` classifier arm, closed-set-complement
2817    ///   mirror of `has-any-populated-kind` on the populated axis.
2818    /// - A fast-path branch that discriminates "any slot still absent"
2819    ///   from "over-populated / saturated" reads
2820    ///   `parent.has_any_missing_kind()` at ONE call site — same
2821    ///   FIRST-missing-slot short-circuit as [`Self::is_saturated`],
2822    ///   no inversion.
2823    /// - A coherence check verifying "no production parent from a
2824    ///   `single_slot_X` factory is saturated" reads
2825    ///   `parent.has_any_missing_kind()` at ONE site — every
2826    ///   `ALL.len() ≥ 2` well-formed parent leaves `ALL.len() - 1 ≥ 1`
2827    ///   slot missing, so this predicate is a substrate structural pin
2828    ///   on the well-formed diagonal.
2829    ///
2830    /// A new [`Self::Kind`] variant added to
2831    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
2832    /// this primitive mechanically — the `any` short-circuit picks up
2833    /// the new slot as an additional first-hit candidate at every
2834    /// downstream callsite without further per-caller edit.
2835    ///
2836    /// # Theory grounding
2837    ///
2838    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2839    ///   The Boolean at-least-one projection on the missing axis lives
2840    ///   at ONE substrate site as a typed short-circuiting closed-set
2841    ///   walk `<Self::Kind as ClosedSet>::ALL.iter().any(|k| !has(k))`
2842    ///   — byte-for-byte definitional complement of
2843    ///   [`Self::is_saturated`]'s `<ALL>.iter().all(has)` (via the De
2844    ///   Morgan dual), semantically identical to
2845    ///   `missing_kind_count() > 0` on every arm with the same first-
2846    ///   hit short-circuit that [`Self::is_saturated`] enjoys.
2847    /// - THEORY.md §VI.1 — generation over composition. A new
2848    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
2849    ///   mechanically through the `any` short-circuit.
2850    fn has_any_missing_kind(&self) -> bool {
2851        <Self::Kind as tatara_closed_set::ClosedSet>::ALL
2852            .iter()
2853            .copied()
2854            .any(|k| !self.has(k))
2855    }
2856
2857    /// Boolean cardinality-mid-endpoint peer of
2858    /// [`Self::unique_populated_kind`] — `true` iff EXACTLY ONE slot on
2859    /// this tagged union is populated.
2860    ///
2861    /// Default body: `self.unique_populated_kind().is_some()` — the
2862    /// Boolean projection of the two-step-short-circuit closed-set walk
2863    /// [`Self::unique_populated_kind`] already performs, without paying
2864    /// for the [`Vec`] `populated_kinds` would build or the counter
2865    /// walk `populated_kind_count` would perform. The `unique_*`
2866    /// primitive short-circuits at the SECOND populated slot on the
2867    /// malformed arms, so the `is_some` projection here short-circuits
2868    /// on the same schedule — strictly cheaper than the widened
2869    /// primitives on every arm where the parent has ≥ 2 populated
2870    /// slots.
2871    ///
2872    /// # Sibling to [`Self::populated_kind_count`]
2873    ///
2874    /// Boolean cardinality-mid-endpoint peer of the scalar cardinality
2875    /// primitive — where `populated_kind_count` returns the FULL scalar
2876    /// (any `usize` in `0..=ALL.len()`), `has_unique_populated_kind`
2877    /// collapses that scalar to its one-arm Boolean projection. The
2878    /// composition law
2879    /// `has_unique_populated_kind() == (populated_kind_count() == 1)`
2880    /// binds the Boolean projection to the scalar primitive at the
2881    /// trait's default body — swept substrate-wide by
2882    /// [`assert_has_unique_populated_kind_matches_populated_kind_count`].
2883    /// Together with [`Self::is_empty`] (zero-arm of the populated
2884    /// axis) and [`Self::is_saturated`] (zero-arm of the missing
2885    /// axis), these three Boolean cardinality primitives close the
2886    /// substrate's 2×2 endpoint grid on the tagged-union parent axis:
2887    ///
2888    /// |          | populated                     | missing                        |
2889    /// |----------|-------------------------------|--------------------------------|
2890    /// | zero-arm | [`Self::is_empty`]            | [`Self::is_saturated`]         |
2891    /// | one-arm  | [`Self::has_unique_populated_kind`] | [`Self::has_unique_missing_kind`] |
2892    ///
2893    /// # Truth table on the exactly-one-slot tagged-union contract
2894    ///
2895    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
2896    /// cardinality `N ≥ 2`:
2897    ///
2898    /// - Empty parent (0 populated, N missing): `false`.
2899    /// - Well-formed parent (1 populated, N-1 missing): `true` — the
2900    ///   SOLE arm where `has_unique_populated_kind` returns `true`.
2901    ///   Aligns with [`Self::variant`]'s `Ok` arm (the single-populated
2902    ///   arm where the resolver returns exactly one variant) — this
2903    ///   primitive is the `bool`-valued projection of that Ok arm.
2904    /// - K-populated parent for `K ≥ 2`: `false`.
2905    /// - Saturated parent (N populated, 0 missing on any `N ≥ 2`
2906    ///   closed set): `false`.
2907    ///
2908    /// # Compounding future consumers
2909    ///
2910    /// - A fast-path branch that discriminates "well-formed" from
2911    ///   "empty or ambiguous" reads `parent.has_unique_populated_kind()`
2912    ///   at ONE substrate site with the same two-step short-circuit
2913    ///   walk `unique_populated_kind` already performs, rather than
2914    ///   reaching for `parent.variant().is_ok()` (which pays for the
2915    ///   borrowed-view projection AND the error-carrier
2916    ///   materialization on failing arms) or
2917    ///   `parent.populated_kind_count() == 1` (which walks every slot).
2918    /// - An operator-facing "well-formed" diagnostic on the resolver's
2919    ///   Ok arm reads `parent.has_unique_populated_kind()` at ONE
2920    ///   substrate site — one two-step short-circuit walk, no
2921    ///   allocation, no borrowed-view materialization.
2922    /// - A `has-unique-populated-kind` require-tag classifier arm
2923    ///   reaches this primitive at ONE call site, byte-for-byte
2924    ///   symmetrical with the sibling `is-empty` / `is-saturated` /
2925    ///   `has-unique-missing-kind` arms across the closed 2×2 grid.
2926    /// - A coherence check verifying "every production parent from a
2927    ///   `single_slot_X` factory is well-formed" reads
2928    ///   `parent.has_unique_populated_kind()` at ONE site rather than
2929    ///   the widened-primitive composition
2930    ///   `parent.populated_kind_count() == 1`.
2931    ///
2932    /// A new [`Self::Kind`] variant added to
2933    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
2934    /// this primitive mechanically through the `unique_populated_kind`
2935    /// short-circuit (the closed-set walk picks up the new entry as an
2936    /// additional short-circuit slot — a parent that populates ONLY
2937    /// the new variant returns `true` at every downstream callsite
2938    /// without further per-caller edit).
2939    ///
2940    /// # Theory grounding
2941    ///
2942    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2943    ///   The Boolean cardinality-mid-endpoint projection lives at ONE
2944    ///   substrate site as the `is_some` projection of the
2945    ///   `unique_populated_kind` two-step short-circuit walk — byte-
2946    ///   for-byte peer of `populated_kind_count()` composed against
2947    ///   `== 1`, but with a second-populated-slot short-circuit that
2948    ///   the scalar counter primitive does not offer.
2949    /// - THEORY.md §VI.1 — generation over composition. A new
2950    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
2951    ///   mechanically through the `unique_populated_kind` short-circuit.
2952    fn has_unique_populated_kind(&self) -> bool {
2953        self.unique_populated_kind().is_some()
2954    }
2955
2956    /// Boolean cardinality-mid-endpoint peer of
2957    /// [`Self::unique_missing_kind`] — `true` iff EXACTLY ONE slot on
2958    /// this tagged union is missing.
2959    ///
2960    /// Default body: `self.unique_missing_kind().is_some()` — the
2961    /// Boolean projection of the two-step-short-circuit closed-set
2962    /// walk [`Self::unique_missing_kind`] already performs under a
2963    /// negated `has` predicate, without paying for the [`Vec`]
2964    /// `missing_kinds` would build or the counter walk
2965    /// `missing_kind_count` would perform. The `unique_*` primitive
2966    /// short-circuits at the SECOND missing slot on the partial arms,
2967    /// so the `is_some` projection here short-circuits on the same
2968    /// schedule — strictly cheaper than the widened primitives on
2969    /// every arm where the parent has ≥ 2 missing slots.
2970    ///
2971    /// # Sibling to [`Self::missing_kind_count`]
2972    ///
2973    /// Boolean cardinality-mid-endpoint peer of the scalar complement
2974    /// cardinality primitive — where `missing_kind_count` returns the
2975    /// FULL scalar (any `usize` in `0..=ALL.len()`),
2976    /// `has_unique_missing_kind` collapses that scalar to its one-arm
2977    /// Boolean projection. The composition law
2978    /// `has_unique_missing_kind() == (missing_kind_count() == 1)`
2979    /// binds the Boolean projection to the scalar primitive at the
2980    /// trait's default body — swept substrate-wide by
2981    /// [`assert_has_unique_missing_kind_matches_missing_kind_count`].
2982    /// Byte-for-byte symmetrical with [`Self::has_unique_populated_kind`]
2983    /// under the (populated, missing) complement axis.
2984    ///
2985    /// # Truth table on the exactly-one-slot tagged-union contract
2986    ///
2987    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
2988    /// cardinality `N ≥ 2`:
2989    ///
2990    /// - Empty parent (0 populated, N missing): `false` on any
2991    ///   `N ≥ 2` closed set (on the degenerate `N == 1` closed set
2992    ///   empty and one-missing coincide; no production tagged union
2993    ///   in this workspace has `N == 1`).
2994    /// - Well-formed parent (1 populated, N-1 missing): `false` on
2995    ///   any `N ≥ 3` closed set. On `N == 2` well-formed and one-
2996    ///   missing coincide — the primitive returns `true` because
2997    ///   `N - 1 == 1`.
2998    /// - K-populated parent for `2 ≤ K ≤ N-1` on `N ≥ 3` closed sets:
2999    ///   `false` in general; `true` only on the `(N-1)`-populated arm
3000    ///   (near-saturation, one slot missing).
3001    /// - Saturated parent (N populated, 0 missing): `false`.
3002    ///
3003    /// # Compounding future consumers
3004    ///
3005    /// - A fast-path branch on the near-saturation arm (exactly one
3006    ///   slot missing, structurally malformed on any `N ≥ 3` tagged
3007    ///   union in that it composes multiple populated slots) reads
3008    ///   `parent.has_unique_missing_kind()` at ONE substrate site
3009    ///   with the same two-step short-circuit walk
3010    ///   `unique_missing_kind` already performs, rather than reaching
3011    ///   for `parent.missing_kind_count() == 1` (which walks every
3012    ///   slot).
3013    /// - An operator-facing "one slot away from saturated" diagnostic
3014    ///   on the near-saturation arm reads
3015    ///   `parent.has_unique_missing_kind()` at ONE substrate site.
3016    /// - A `has-unique-missing-kind` require-tag classifier arm
3017    ///   reaches this primitive at ONE call site, byte-for-byte
3018    ///   symmetrical with the sibling `has-unique-populated-kind` arm
3019    ///   under the (populated, missing) complement axis.
3020    ///
3021    /// A new [`Self::Kind`] variant added to
3022    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
3023    /// this primitive mechanically through the `unique_missing_kind`
3024    /// short-circuit.
3025    ///
3026    /// # Theory grounding
3027    ///
3028    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3029    ///   The Boolean cardinality-mid-endpoint projection on the
3030    ///   missing axis lives at ONE substrate site as the `is_some`
3031    ///   projection of the `unique_missing_kind` two-step short-circuit
3032    ///   walk — byte-for-byte peer of `missing_kind_count()` composed
3033    ///   against `== 1`, but with a second-missing-slot short-circuit
3034    ///   that the scalar counter primitive does not offer.
3035    /// - THEORY.md §VI.1 — generation over composition. A new
3036    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
3037    ///   mechanically through the `unique_missing_kind` short-circuit.
3038    fn has_unique_missing_kind(&self) -> bool {
3039        self.unique_missing_kind().is_some()
3040    }
3041
3042    /// Boolean cardinality many-arm peer of
3043    /// [`Self::has_unique_populated_kind`] — `true` iff TWO OR MORE
3044    /// slots on this tagged union are populated.
3045    ///
3046    /// Default body: a two-step-short-circuit closed-set walk under
3047    /// [`Self::has`] that pulls two hits off the filtered iterator
3048    /// and returns `true` iff both are `Some`, WITHOUT paying for the
3049    /// [`Vec`] `populated_kinds` would build or the counter walk
3050    /// `populated_kind_count` would perform. Short-circuits at the
3051    /// SECOND populated slot — strictly cheaper than either widened
3052    /// primitive on every arm past the second populated slot.
3053    ///
3054    /// # Sibling to the Boolean cardinality trichotomy
3055    ///
3056    /// Third arm of the {0, 1, ≥2} cardinality trichotomy on the
3057    /// populated axis, closing the natural partition alongside
3058    /// [`Self::is_empty`] (zero-arm) and
3059    /// [`Self::has_unique_populated_kind`] (one-arm). Every tagged-
3060    /// union state satisfies EXACTLY ONE of the three predicates —
3061    /// the three Boolean projections partition
3062    /// `0..=<Self::Kind as ClosedSet>::ALL.len()` at 0, 1, and ≥2
3063    /// respectively. Maps directly onto the three arms of the
3064    /// resolver contract [`Self::variant`] returns:
3065    ///
3066    /// | populated count | Boolean primitive                       | `variant()`             |
3067    /// |-----------------|-----------------------------------------|-------------------------|
3068    /// | 0               | [`Self::is_empty`]                      | `Err(Error::empty)`     |
3069    /// | 1               | [`Self::has_unique_populated_kind`]     | `Ok(Variant)`           |
3070    /// | ≥ 2             | `has_multiple_populated_kinds` (this)   | `Err(Error::ambiguous)` |
3071    ///
3072    /// The composition law `has_multiple_populated_kinds() ==
3073    /// (populated_kind_count() >= 2)` binds the Boolean projection
3074    /// to the scalar primitive at the trait's default body — swept
3075    /// substrate-wide by
3076    /// [`assert_has_multiple_populated_kinds_matches_populated_kind_count`].
3077    ///
3078    /// # Truth table on the exactly-one-slot tagged-union contract
3079    ///
3080    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3081    /// cardinality `N ≥ 2`:
3082    ///
3083    /// - Empty parent (0 populated): `false`.
3084    /// - Well-formed parent (1 populated): `false`.
3085    /// - K-populated parent for `K ≥ 2`: `true`.
3086    /// - Saturated parent (N populated, `N ≥ 2`): `true`.
3087    ///
3088    /// # Compounding future consumers
3089    ///
3090    /// - A fast-path branch that discriminates "ambiguous" from
3091    ///   "empty or well-formed" reads
3092    ///   `parent.has_multiple_populated_kinds()` at ONE substrate
3093    ///   site with a two-step short-circuit walk, rather than
3094    ///   `parent.variant().is_err_and(|e| matches!(e,
3095    ///   TaggedUnionError::Ambiguous))` (which materializes the
3096    ///   borrowed-view AND the error-carrier) or
3097    ///   `parent.populated_kind_count() >= 2` (which walks every
3098    ///   slot).
3099    /// - An operator-facing "over-populated / ambiguous carrier"
3100    ///   diagnostic reads `parent.has_multiple_populated_kinds()`
3101    ///   at ONE substrate site — one two-step short-circuit walk,
3102    ///   no allocation.
3103    /// - A `has-multiple-populated-kinds` require-tag classifier
3104    ///   arm reaches this primitive at ONE call site, byte-for-byte
3105    ///   symmetrical with the sibling zero-arm / one-arm classifier
3106    ///   arms across the closed 2×3 grid.
3107    ///
3108    /// A new [`Self::Kind`] variant added to
3109    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
3110    /// this primitive mechanically — the closed-set walk picks up
3111    /// the new slot as an additional two-step-short-circuit
3112    /// candidate.
3113    ///
3114    /// # Theory grounding
3115    ///
3116    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3117    ///   The Boolean cardinality many-arm projection lives at ONE
3118    ///   substrate site as a typed two-step-short-circuit walk over
3119    ///   `<Self::Kind as ClosedSet>::ALL` under [`Self::has`] — byte-
3120    ///   for-byte peer of `populated_kind_count()` composed against
3121    ///   `>= 2`, but with a second-populated-slot short-circuit that
3122    ///   the scalar counter primitive does not offer.
3123    /// - THEORY.md §VI.1 — generation over composition. A new
3124    ///   [`Self::Kind`] variant added to `ALL` reaches this
3125    ///   primitive mechanically.
3126    fn has_multiple_populated_kinds(&self) -> bool {
3127        let mut iter = <Self::Kind as tatara_closed_set::ClosedSet>::ALL
3128            .iter()
3129            .copied()
3130            .filter(|k| self.has(*k));
3131        iter.next().is_some() && iter.next().is_some()
3132    }
3133
3134    /// Boolean cardinality many-arm peer of
3135    /// [`Self::has_unique_missing_kind`] — `true` iff TWO OR MORE
3136    /// slots on this tagged union are missing.
3137    ///
3138    /// Default body: a two-step-short-circuit closed-set walk under
3139    /// a NEGATED [`Self::has`] predicate that pulls two hits off the
3140    /// filtered iterator and returns `true` iff both are `Some`.
3141    /// Byte-for-byte peer of [`Self::has_multiple_populated_kinds`]
3142    /// under the (populated, missing) complement axis.
3143    ///
3144    /// # Sibling to the Boolean cardinality trichotomy
3145    ///
3146    /// Third arm of the {0, 1, ≥2} cardinality trichotomy on the
3147    /// missing axis, closing the natural partition alongside
3148    /// [`Self::is_saturated`] (zero-arm) and
3149    /// [`Self::has_unique_missing_kind`] (one-arm). The composition
3150    /// law `has_multiple_missing_kinds() == (missing_kind_count() >=
3151    /// 2)` binds the Boolean projection to the scalar complement
3152    /// cardinality primitive at the trait's default body — swept
3153    /// substrate-wide by
3154    /// [`assert_has_multiple_missing_kinds_matches_missing_kind_count`].
3155    ///
3156    /// # Truth table on the exactly-one-slot tagged-union contract
3157    ///
3158    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3159    /// cardinality `N`:
3160    ///
3161    /// - Empty parent (0 populated, N missing): `true` iff `N ≥ 2`
3162    ///   (every production union in the workspace).
3163    /// - Well-formed parent (1 populated, N-1 missing): `true` iff
3164    ///   `N ≥ 3`. On `N == 2` the well-formed arm has exactly one
3165    ///   missing slot, so this primitive returns `false`.
3166    /// - K-populated parent for `K ≤ N-2`: `true`.
3167    /// - Near-saturated parent (N-1 populated, 1 missing): `false`
3168    ///   (exactly one missing, not many).
3169    /// - Saturated parent (N populated, 0 missing): `false`.
3170    ///
3171    /// # Compounding future consumers
3172    ///
3173    /// - A fast-path branch that discriminates "≥ 2 slots still
3174    ///   unfulfilled" from "0 or 1 slot still unfulfilled" (an
3175    ///   aggregate boundary progress-guard: at least two conditions
3176    ///   still open) reads `parent.has_multiple_missing_kinds()` at
3177    ///   ONE substrate site.
3178    /// - An operator-facing "≥ 2 dependencies still unfulfilled"
3179    ///   diagnostic reads `parent.has_multiple_missing_kinds()` at
3180    ///   ONE substrate site — one two-step short-circuit walk under
3181    ///   the negated predicate.
3182    /// - A `has-multiple-missing-kinds` require-tag classifier arm
3183    ///   reaches this primitive at ONE call site, byte-for-byte
3184    ///   symmetrical with `has_multiple_populated_kinds` under the
3185    ///   complement axis.
3186    ///
3187    /// # Theory grounding
3188    ///
3189    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3190    /// - THEORY.md §VI.1 — generation over composition.
3191    fn has_multiple_missing_kinds(&self) -> bool {
3192        let mut iter = <Self::Kind as tatara_closed_set::ClosedSet>::ALL
3193            .iter()
3194            .copied()
3195            .filter(|k| !self.has(*k));
3196        iter.next().is_some() && iter.next().is_some()
3197    }
3198
3199    /// Boolean cardinality "≤ 1" peer of
3200    /// [`Self::has_multiple_populated_kinds`] — `true` iff AT MOST ONE
3201    /// slot on this tagged union is populated (i.e. zero or one
3202    /// populated slot).
3203    ///
3204    /// Default body: the definitional Boolean negation
3205    /// `!self.has_multiple_populated_kinds()` — one bit-flip over the
3206    /// SAME two-step-short-circuit closed-set walk that
3207    /// [`Self::has_multiple_populated_kinds`] already runs, without
3208    /// re-authoring the fused loop and WITHOUT a second walk over the
3209    /// closed set. Strictly cheaper than either widened composition
3210    /// `self.is_empty() || self.has_unique_populated_kind()` (which
3211    /// walks the closed set TWICE — once under `all-missing`, once
3212    /// under `exactly-one`) or `self.populated_kind_count() <= 1`
3213    /// (which walks the closed set fully counting hits) on every arm.
3214    ///
3215    /// # Sibling to the Boolean cardinality "≥ 2" primitive
3216    ///
3217    /// Boolean-negation peer under `!(≥ 2) == (≤ 1)` — where
3218    /// [`Self::has_multiple_populated_kinds`] names the AMBIGUOUS arm
3219    /// of the resolver contract (the arm [`Self::variant`] returns
3220    /// `Err(Error::ambiguous)` on), `has_at_most_one_populated_kind`
3221    /// names its complement — the RESOLVEABLE-OR-EMPTY arm (the two
3222    /// arms of the resolver contract that DON'T return
3223    /// `Err(Error::ambiguous)`, i.e. `Ok(Variant)` OR
3224    /// `Err(Error::empty)`). The typed predicate for "this parent is
3225    /// not ambiguous" without inverting a
3226    /// `!parent.has_multiple_populated_kinds()` at every callsite.
3227    ///
3228    /// # Composition laws
3229    ///
3230    /// - `has_at_most_one_populated_kind() == !has_multiple_populated_kinds()`
3231    ///   — the definitional Boolean negation, at the trait default
3232    ///   body's SAME fused short-circuit walk.
3233    /// - `has_at_most_one_populated_kind() == (populated_kind_count() <= 1)`
3234    ///   — the scalar cardinality composition.
3235    /// - `has_at_most_one_populated_kind() == is_empty() || has_unique_populated_kind()`
3236    ///   — the union of the zero-arm and the one-arm of the
3237    ///   {0, 1, ≥ 2} cardinality trichotomy.
3238    ///
3239    /// All three laws hold on every arm and every closed-set kind —
3240    /// pinned as first-class typed invariants by the trait's own
3241    /// default body and swept substrate-wide by
3242    /// [`assert_has_at_most_one_populated_kind_matches_populated_kind_count`].
3243    ///
3244    /// # Truth table on the exactly-one-slot tagged-union contract
3245    ///
3246    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3247    /// cardinality `N ≥ 2`:
3248    ///
3249    /// - Empty parent (0 populated, N missing): `true` (0 ≤ 1).
3250    /// - Well-formed parent (1 populated, N-1 missing): `true` (1 ≤ 1)
3251    ///   — the SOLE `Ok` arm of [`Self::variant`] lies inside the
3252    ///   at-most-one region.
3253    /// - K-populated parent for `K ≥ 2`: `false` (K > 1).
3254    /// - Saturated parent (N populated, 0 missing on any `N ≥ 2`):
3255    ///   `false` (N ≥ 2 > 1).
3256    ///
3257    /// # Compounding future consumers
3258    ///
3259    /// - A fast-path branch on the resolver-clean arm that
3260    ///   discriminates "not ambiguous" (0 or 1 populated) from
3261    ///   "ambiguous" (≥ 2 populated) reads
3262    ///   `parent.has_at_most_one_populated_kind()` at ONE substrate
3263    ///   site — one two-step short-circuit walk with a bit-flip,
3264    ///   strictly cheaper than the widened union of the zero-arm and
3265    ///   one-arm.
3266    /// - An operator-facing "at most one populated variant" diagnostic
3267    ///   (the guard for downstream code that assumes non-ambiguous
3268    ///   dispatch) reads this primitive at ONE substrate site.
3269    /// - A `has-at-most-one-populated-kind` require-tag classifier arm
3270    ///   reaches this primitive at ONE call site, closing the
3271    ///   {0, 1, ≥ 2, ≤ 1} cardinality-Boolean grid alongside its
3272    ///   sibling `has-multiple-populated-kinds` under the Boolean
3273    ///   negation axis.
3274    ///
3275    /// A new [`Self::Kind`] variant added to
3276    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
3277    /// this primitive mechanically through the delegated
3278    /// [`Self::has_multiple_populated_kinds`] — the fused walk picks
3279    /// up the new slot as an additional short-circuit candidate at
3280    /// every downstream callsite without further per-caller edit.
3281    ///
3282    /// # Theory grounding
3283    ///
3284    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3285    ///   The "≤ 1" Boolean projection lives at ONE substrate site as
3286    ///   a definitional negation of the "≥ 2" projection; the two
3287    ///   forms `!has_multiple_populated_kinds()`,
3288    ///   `populated_kind_count() <= 1`, and
3289    ///   `is_empty() || has_unique_populated_kind()` compose through
3290    ///   the SAME two-step-short-circuit walk shape, byte-for-byte
3291    ///   identical on every arm.
3292    /// - THEORY.md §VI.1 — generation over composition. A new
3293    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
3294    ///   mechanically through the delegated
3295    ///   [`Self::has_multiple_populated_kinds`].
3296    fn has_at_most_one_populated_kind(&self) -> bool {
3297        !self.has_multiple_populated_kinds()
3298    }
3299
3300    /// Boolean cardinality "≤ 1" peer of
3301    /// [`Self::has_multiple_missing_kinds`] — `true` iff AT MOST ONE
3302    /// slot on this tagged union is missing (i.e. zero or one missing
3303    /// slot).
3304    ///
3305    /// Default body: the definitional Boolean negation
3306    /// `!self.has_multiple_missing_kinds()` — one bit-flip over the
3307    /// SAME two-step-short-circuit closed-set walk under a NEGATED
3308    /// [`Self::has`] predicate that [`Self::has_multiple_missing_kinds`]
3309    /// already runs, without re-authoring the fused loop and WITHOUT a
3310    /// second walk over the closed set. Strictly cheaper than either
3311    /// widened composition
3312    /// `self.is_saturated() || self.has_unique_missing_kind()` (which
3313    /// walks the closed set TWICE — once under `all-populated`, once
3314    /// under `exactly-one-missing`) or `self.missing_kind_count() <= 1`
3315    /// (which walks the closed set fully counting missing hits) on
3316    /// every arm.
3317    ///
3318    /// # Sibling to the Boolean cardinality "≥ 2" primitive
3319    ///
3320    /// Boolean-negation peer under `!(≥ 2) == (≤ 1)` — byte-for-byte
3321    /// symmetrical with [`Self::has_at_most_one_populated_kind`]
3322    /// under the (populated, missing) complement axis. Names the arm
3323    /// where the parent is SATURATED-OR-NEAR-SATURATED (zero or
3324    /// exactly one missing slot).
3325    ///
3326    /// # Composition laws
3327    ///
3328    /// - `has_at_most_one_missing_kind() == !has_multiple_missing_kinds()`
3329    ///   — the definitional Boolean negation.
3330    /// - `has_at_most_one_missing_kind() == (missing_kind_count() <= 1)`
3331    ///   — the scalar complement-cardinality composition.
3332    /// - `has_at_most_one_missing_kind() == is_saturated() || has_unique_missing_kind()`
3333    ///   — the union of the zero-missing-arm and the one-missing-arm
3334    ///   of the {0, 1, ≥ 2} cardinality trichotomy on the missing
3335    ///   axis.
3336    ///
3337    /// All three laws hold on every arm and every closed-set kind —
3338    /// pinned as first-class typed invariants by the trait's own
3339    /// default body and swept substrate-wide by
3340    /// [`assert_has_at_most_one_missing_kind_matches_missing_kind_count`].
3341    ///
3342    /// # Truth table on the exactly-one-slot tagged-union contract
3343    ///
3344    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3345    /// cardinality `N`:
3346    ///
3347    /// - Empty parent (0 populated, N missing): `true` iff `N ≤ 1`
3348    ///   (every production union in the workspace has `N ≥ 2`, so on
3349    ///   every production union the empty arm returns `false`).
3350    /// - Well-formed parent (1 populated, N-1 missing): `true` iff
3351    ///   `N - 1 ≤ 1`, i.e. `N ≤ 2` (on `N == 2` the well-formed arm
3352    ///   has exactly one missing slot; on `N ≥ 3` it has ≥ 2).
3353    /// - Near-saturated parent (N-1 populated, 1 missing): `true` (1 ≤ 1).
3354    /// - K-missing parent for `K ≥ 2`: `false`.
3355    /// - Saturated parent (N populated, 0 missing): `true` (0 ≤ 1).
3356    ///
3357    /// # Compounding future consumers
3358    ///
3359    /// - A fast-path branch on the near-saturated / saturated arms
3360    ///   that discriminates "at most one dependency still open" from
3361    ///   "≥ 2 dependencies still open" reads
3362    ///   `parent.has_at_most_one_missing_kind()` at ONE substrate
3363    ///   site — one two-step short-circuit walk with a bit-flip,
3364    ///   strictly cheaper than the widened union of the zero-arm and
3365    ///   one-arm.
3366    /// - An operator-facing "at most one dependency still unfulfilled"
3367    ///   diagnostic on an aggregate boundary progress-guard reads
3368    ///   this primitive at ONE substrate site.
3369    /// - A `has-at-most-one-missing-kind` require-tag classifier arm
3370    ///   reaches this primitive at ONE call site, closing the
3371    ///   {0, 1, ≥ 2, ≤ 1} cardinality-Boolean grid on the missing
3372    ///   axis alongside its sibling `has-multiple-missing-kinds`
3373    ///   under the Boolean negation axis.
3374    ///
3375    /// # Theory grounding
3376    ///
3377    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3378    ///   The "≤ 1" Boolean projection on the missing axis lives at
3379    ///   ONE substrate site as a definitional negation of the "≥ 2"
3380    ///   projection; the three composition forms
3381    ///   (`!has_multiple_missing_kinds()`,
3382    ///   `missing_kind_count() <= 1`, and
3383    ///   `is_saturated() || has_unique_missing_kind()`) compose
3384    ///   through the SAME two-step-short-circuit walk shape,
3385    ///   byte-for-byte identical on every arm.
3386    /// - THEORY.md §VI.1 — generation over composition. A new
3387    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
3388    ///   mechanically through the delegated
3389    ///   [`Self::has_multiple_missing_kinds`].
3390    fn has_at_most_one_missing_kind(&self) -> bool {
3391        !self.has_multiple_missing_kinds()
3392    }
3393
3394    /// Boolean parent-state middle-arm projection — `true` iff this
3395    /// tagged union has AT LEAST ONE populated slot AND AT LEAST ONE
3396    /// missing slot, i.e. it is neither [`Self::is_empty`] nor
3397    /// [`Self::is_saturated`].
3398    ///
3399    /// Default body: a FUSED short-circuit closed-set walk that tracks
3400    /// two Boolean flags (`has_populated`, `has_missing`) across
3401    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) under
3402    /// [`Self::has`] and returns `true` at the EARLIEST slot where
3403    /// both flags have flipped. Best-case O(2) walk (index 0 populated
3404    /// combined with index 1 missing, or vice versa); worst case walks
3405    /// the full closed set only when EVERY slot is populated or EVERY
3406    /// slot is missing (the two arms where the return value is `false`).
3407    /// Byte-for-byte cheaper than the widened composition
3408    /// `!self.is_empty() && !self.is_saturated()` (which walks the
3409    /// closed set TWICE — once under `any`, once under `all`) on every
3410    /// partially-populated arm.
3411    ///
3412    /// # Sibling to the parent-state trichotomy
3413    ///
3414    /// Middle arm of the natural `{Empty | Partial | Saturated}`
3415    /// parent-state trichotomy — orthogonal to the {0, 1, ≥2}
3416    /// cardinality trichotomies already closed on the populated /
3417    /// missing axes. Together with [`Self::is_empty`] (all-missing
3418    /// arm) and [`Self::is_saturated`] (all-populated arm), these three
3419    /// Boolean primitives partition every tagged-union state on the
3420    /// parent-state axis — EXACTLY ONE of the three returns `true` on
3421    /// any given parent whose `<Self::Kind as ClosedSet>::ALL.len() ≥
3422    /// 1`:
3423    ///
3424    /// | parent state | primitive                          | populated cardinality       |
3425    /// |--------------|------------------------------------|-----------------------------|
3426    /// | Empty        | [`Self::is_empty`]                 | `0`                         |
3427    /// | Partial      | `is_partially_populated` (this)    | `0 < populated < ALL.len()` |
3428    /// | Saturated    | [`Self::is_saturated`]             | `ALL.len()`                 |
3429    ///
3430    /// The trichotomy partition law
3431    /// `usize::from(is_empty()) + usize::from(is_partially_populated())
3432    /// + usize::from(is_saturated()) == 1` on every arm is a genuinely
3433    /// new proof binding the three parent-state endpoints together as
3434    /// a typed algebraic invariant — swept substrate-wide by
3435    /// [`assert_is_partially_populated_matches_cardinality`].
3436    ///
3437    /// # Composition laws
3438    ///
3439    /// - `is_partially_populated() == !is_empty() && !is_saturated()`
3440    ///   — the negation-of-both-endpoints composition, at the trait
3441    ///   default body's SAME fused short-circuit walk.
3442    /// - `is_partially_populated() == (populated_kind_count() > 0
3443    ///   && missing_kind_count() > 0)` — the paired scalar-projection
3444    ///   composition.
3445    /// - `is_partially_populated() == (0 < populated_kind_count()
3446    ///   && populated_kind_count() < ALL.len())` — the single-axis
3447    ///   strict-inequality composition (populated cardinality lies in
3448    ///   the open interval `(0, ALL.len())`).
3449    ///
3450    /// # Truth table on the exactly-one-slot tagged-union contract
3451    ///
3452    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3453    /// cardinality `N ≥ 2`:
3454    ///
3455    /// - Empty parent (0 populated, N missing): `false` (empty arm).
3456    /// - Well-formed parent (1 populated, N-1 missing on any `N ≥ 2`):
3457    ///   `true` — the SOLE `Ok` arm of [`Self::variant`] lies inside
3458    ///   the partial region.
3459    /// - K-populated parent for `0 < K < N`: `true`.
3460    /// - Saturated parent (N populated, 0 missing on any `N ≥ 2`):
3461    ///   `false` (saturated arm).
3462    ///
3463    /// # Compounding future consumers
3464    ///
3465    /// - A boundary-progress "some done, some pending" diagnostic on
3466    ///   an aggregate condition-carrier reads
3467    ///   `parent.is_partially_populated()` at ONE substrate site —
3468    ///   the exact "in flight" arm — rather than composing
3469    ///   `!parent.is_empty() && !parent.is_saturated()` (two closed-
3470    ///   set walks) or `parent.populated_kind_count() > 0 &&
3471    ///   parent.missing_kind_count() > 0` (two counter walks).
3472    /// - A fast-path branch that discriminates "mixed" from "empty or
3473    ///   saturated" reads this primitive with ONE fused short-circuit
3474    ///   walk, strictly cheaper than either widened composition.
3475    /// - An `is-partially-populated` require-tag classifier arm
3476    ///   reaches this primitive at ONE call site, byte-for-byte
3477    ///   symmetrical with the sibling `is-empty` / `is-saturated`
3478    ///   arms on the closed parent-state trichotomy.
3479    /// - An operator-facing "in-flight ambiguous carrier" diagnostic
3480    ///   (the resolver's `Err(Ambiguous)` arm's non-saturated sub-arm)
3481    ///   reads `parent.is_partially_populated() && parent.has_multiple_populated_kinds()`
3482    ///   composing two short-circuit walks — strictly cheaper than
3483    ///   materializing the `variant()` error carrier.
3484    ///
3485    /// A new [`Self::Kind`] variant added to
3486    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
3487    /// this primitive mechanically — the fused walk picks up the new
3488    /// slot as an additional short-circuit candidate (a parent that
3489    /// previously satisfied `is_partially_populated` because it had
3490    /// both populated and missing slots continues to satisfy it; a
3491    /// previously-saturated parent that leaves the new slot missing
3492    /// becomes partially populated at every downstream callsite
3493    /// without further per-caller edit).
3494    ///
3495    /// # Theory grounding
3496    ///
3497    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3498    ///   The parent-state middle-arm projection lives at ONE
3499    ///   substrate site as a fused short-circuit walk over
3500    ///   `<Self::Kind as ClosedSet>::ALL` under [`Self::has`] with
3501    ///   early exit on the first observed populated/missing pair —
3502    ///   byte-for-byte cheaper than the widened negation-of-both-
3503    ///   endpoints composition, and semantically identical on every
3504    ///   arm. The trichotomy partition law
3505    ///   `is_empty + is_partially_populated + is_saturated == 1`
3506    ///   lives at ONE substrate site inside the testkit's per-arm
3507    ///   sweep — pinned across every production tagged union at
3508    ///   compile time via the trait's default body composition, not
3509    ///   per-parent.
3510    /// - THEORY.md §VI.1 — generation over composition. A new
3511    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
3512    ///   mechanically through the fused walk — the trichotomy holds
3513    ///   on the widened kind set without further per-caller edit.
3514    fn is_partially_populated(&self) -> bool {
3515        let mut has_populated = false;
3516        let mut has_missing = false;
3517        for k in <Self::Kind as tatara_closed_set::ClosedSet>::ALL
3518            .iter()
3519            .copied()
3520        {
3521            if self.has(k) {
3522                has_populated = true;
3523            } else {
3524                has_missing = true;
3525            }
3526            if has_populated && has_missing {
3527                return true;
3528            }
3529        }
3530        false
3531    }
3532
3533    /// Kind-scoped strict refinement of [`Self::has`] — `true` iff the
3534    /// given `kind` is populated AND no OTHER slot on this tagged union
3535    /// is populated. The "exactly this one variant" predicate.
3536    ///
3537    /// Default body: a FUSED short-circuit closed-set walk under
3538    /// [`Self::has`] that returns `false` at the EARLIEST populated
3539    /// slot whose kind is NOT `kind`, and returns `true` iff the sweep
3540    /// completes with `kind` seen as the sole populated slot. Byte-for-
3541    /// byte cheaper than either widened composition
3542    /// `self.unique_populated_kind() == Some(kind)` (which walks until
3543    /// the SECOND populated slot before comparing) or
3544    /// `self.has(kind) && self.has_unique_populated_kind()` (two
3545    /// closed-set walks) on every arm where the parent carries a
3546    /// populated slot that isn't `kind`.
3547    ///
3548    /// # Sibling to [`Self::has`]
3549    ///
3550    /// Kind-scoped strict-refinement peer: `has(kind)` is the SUBSET
3551    /// predicate (`kind` populated, maybe others too); `has_only(kind)`
3552    /// is the EQUAL predicate (`kind` populated AND ONLY `kind`). The
3553    /// implication `has_only(kind) → has(kind)` binds the pair on the
3554    /// strict-refinement axis; the reverse implication holds only on
3555    /// well-formed parents (`has_unique_populated_kind() == true`).
3556    ///
3557    /// # Peer to [`Self::unique_populated_kind`]
3558    ///
3559    /// Same axis, argument-scoped projection: where
3560    /// `unique_populated_kind()` returns `Some(k)` iff exactly one slot
3561    /// is populated AND names which one, `has_only(kind)` returns
3562    /// `true` iff exactly one slot is populated AND that slot is the
3563    /// passed `kind`. The composition law
3564    /// `has_only(kind) == (unique_populated_kind() == Some(kind))`
3565    /// binds the two primitives at the trait's default body — swept
3566    /// substrate-wide by
3567    /// [`assert_has_only_matches_unique_populated_kind`].
3568    ///
3569    /// # Truth table on the exactly-one-slot tagged-union contract
3570    ///
3571    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3572    /// cardinality `N ≥ 2` and a fixed argument `kind`:
3573    ///
3574    /// - Empty parent (0 populated, N missing): `false` — no populated
3575    ///   slot, so `kind` isn't the sole populated kind.
3576    /// - Well-formed parent with `kind` populated (1 populated ==
3577    ///   kind): `true` — the SOLE arm where `has_only(kind)` returns
3578    ///   `true`. Aligns with [`Self::variant`]'s `Ok(Variant)` arm
3579    ///   where the resolver names the same kind.
3580    /// - Well-formed parent with other kind populated (1 populated !=
3581    ///   kind): `false` — the populated slot addresses a different
3582    ///   kind.
3583    /// - K-populated parent for `K ≥ 2`: `false` — multiple populated
3584    ///   slots, so no single kind is the "only" one.
3585    /// - Saturated parent (N populated, 0 missing on any `N ≥ 2`):
3586    ///   `false`.
3587    ///
3588    /// # Kind-domain exhaustivity
3589    ///
3590    /// A parent satisfies `has_only(k)` for AT MOST one `k`, since two
3591    /// distinct kinds cannot both be the sole populated slot. On the
3592    /// well-formed arm the count is exactly 1 (the addressed kind); on
3593    /// every non-well-formed arm the count is 0. This kind-domain
3594    /// exhaustivity law binds the argument-scoped projection to the
3595    /// arg-less uniqueness predicate at ONE substrate site.
3596    ///
3597    /// # Compounding future consumers
3598    ///
3599    /// - A dispatch table that runs a per-kind branch only when the
3600    ///   parent is unambiguously that kind reads `parent.has_only(k)`
3601    ///   at ONE substrate site with ONE fused short-circuit walk —
3602    ///   strictly cheaper than either widened composition.
3603    /// - An `is-only-<kind>` require-tag classifier arm reaches this
3604    ///   primitive at ONE call site — the kind-scoped peer of the
3605    ///   arg-less `has_unique_populated_kind` classifier.
3606    /// - A coherence check verifying "every parent from a
3607    ///   `single_slot_X(k)` factory is unambiguously kind `k`" reads
3608    ///   `parent.has_only(k)` at ONE site — the strongest structural
3609    ///   pin on the well-formed diagonal.
3610    /// - An operator-facing "unambiguously kind=<k>" diagnostic on the
3611    ///   resolver's Ok arm reads `parent.has_only(k)` after
3612    ///   `first_populated_kind` names the resolved kind — one walk, no
3613    ///   allocation, no `Option<Kind>` construction.
3614    ///
3615    /// A new [`Self::Kind`] variant added to
3616    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
3617    /// this primitive mechanically — the fused walk picks up the new
3618    /// slot as an additional short-circuit candidate at every
3619    /// downstream callsite without further per-caller edit.
3620    ///
3621    /// # Theory grounding
3622    ///
3623    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3624    ///   The kind-scoped strict-refinement projection lives at ONE
3625    ///   substrate site as a fused short-circuit walk over
3626    ///   `<Self::Kind as ClosedSet>::ALL` under [`Self::has`] with
3627    ///   early exit on the first populated slot whose kind is not
3628    ///   `kind` — byte-for-byte cheaper than the widened composition
3629    ///   `unique_populated_kind() == Some(kind)`, semantically
3630    ///   identical on every arm.
3631    /// - THEORY.md §VI.1 — generation over composition. A new
3632    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
3633    ///   mechanically through the fused walk.
3634    fn has_only(&self, kind: Self::Kind) -> bool
3635    where
3636        Self::Kind: PartialEq,
3637    {
3638        let mut saw_kind = false;
3639        for k in <Self::Kind as tatara_closed_set::ClosedSet>::ALL
3640            .iter()
3641            .copied()
3642        {
3643            if !self.has(k) {
3644                continue;
3645            }
3646            if k == kind {
3647                saw_kind = true;
3648            } else {
3649                return false;
3650            }
3651        }
3652        saw_kind
3653    }
3654
3655    /// Kind-scoped strict refinement of `!Self::has(kind)` — `true` iff
3656    /// the given `kind` is MISSING AND no OTHER slot on this tagged
3657    /// union is missing. The "exactly this one variant is absent"
3658    /// predicate — closed-set-complement mirror of [`Self::has_only`].
3659    ///
3660    /// Default body: a FUSED short-circuit closed-set walk under a
3661    /// negated [`Self::has`] that returns `false` at the EARLIEST
3662    /// missing slot whose kind is NOT `kind`, and returns `true` iff
3663    /// the sweep completes with `kind` seen as the sole missing slot.
3664    /// Byte-for-byte cheaper than either widened composition
3665    /// `self.unique_missing_kind() == Some(kind)` (which walks until
3666    /// the SECOND missing slot before comparing) or
3667    /// `!self.has(kind) && self.has_unique_missing_kind()` (two
3668    /// closed-set walks) on every arm where the parent carries a
3669    /// missing slot that isn't `kind`.
3670    ///
3671    /// # Sibling to [`Self::has_only`]
3672    ///
3673    /// Closed-set-complement peer of [`Self::has_only`] under a negated
3674    /// [`Self::has`] predicate — where `has_only(kind)` names parents
3675    /// whose SOLE populated slot is `kind`, `lacks_only(kind)` names
3676    /// parents whose SOLE missing slot is `kind`. Byte-for-byte
3677    /// symmetrical fused-walk shape; the two primitives are useful in
3678    /// DIFFERENT structural regimes: `has_only` names well-formed
3679    /// parents (1 of N populated); `lacks_only` names the missing-side
3680    /// complement (N-1 of N populated — the near-saturation arm). On
3681    /// tagged unions with `N == 2` the two coincide (a well-formed
3682    /// 1-of-2 parent has 1 missing too, so `has_only(a)` and
3683    /// `lacks_only(b)` name the same arm iff `a != b`).
3684    ///
3685    /// # Peer to [`Self::unique_missing_kind`]
3686    ///
3687    /// Same axis, argument-scoped projection: where
3688    /// `unique_missing_kind()` returns `Some(k)` iff exactly one slot
3689    /// is missing AND names which one, `lacks_only(kind)` returns
3690    /// `true` iff exactly one slot is missing AND that slot is the
3691    /// passed `kind`. The composition law
3692    /// `lacks_only(kind) == (unique_missing_kind() == Some(kind))`
3693    /// binds the two primitives at the trait's default body — swept
3694    /// substrate-wide by
3695    /// [`assert_lacks_only_matches_unique_missing_kind`].
3696    ///
3697    /// # Truth table on the exactly-one-slot tagged-union contract
3698    ///
3699    /// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
3700    /// cardinality `N ≥ 2` and a fixed argument `kind`:
3701    ///
3702    /// - Empty parent (0 populated, N missing): `false` on any `N ≥ 2`
3703    ///   — N missing slots, so `kind` isn't the sole missing kind.
3704    /// - Well-formed parent (1 populated, N-1 missing): `false` when
3705    ///   `N > 2` (N-1 ≥ 2 missing, no unique missing); on `N == 2`
3706    ///   with populated `p`, `lacks_only(kind) == (kind != p)` (the
3707    ///   one missing slot is the non-populated one).
3708    /// - N-1-populated parent (missing-side peer of the well-formed
3709    ///   arm, 1 missing): `true` iff `kind` names the sole missing
3710    ///   slot — the SOLE arm where `lacks_only(kind)` returns `true`
3711    ///   on any `N > 2` closed set.
3712    /// - Saturated parent (N populated, 0 missing): `false`.
3713    ///
3714    /// # Kind-domain exhaustivity
3715    ///
3716    /// A parent satisfies `lacks_only(k)` for AT MOST one `k`, since
3717    /// two distinct kinds cannot both be the sole missing slot. On
3718    /// the near-saturation arm the count is exactly 1 (the addressed
3719    /// missing kind); on every other arm the count is 0. This kind-
3720    /// domain exhaustivity law binds the argument-scoped projection
3721    /// to the arg-less uniqueness predicate at ONE substrate site,
3722    /// byte-for-byte peer of the `has_only` exhaustivity law under
3723    /// complement.
3724    ///
3725    /// # Kind-scoped implication
3726    ///
3727    /// `lacks_only(kind) → !has(kind)` — if `kind` is the sole missing
3728    /// slot then `kind` cannot be populated. Complement mirror of the
3729    /// `has_only(kind) → has(kind)` implication that binds
3730    /// [`Self::has_only`] to [`Self::has`] on the strict-refinement
3731    /// axis; here the implication binds `lacks_only` to `!has` on the
3732    /// closed-set-complement axis.
3733    ///
3734    /// # Compounding future consumers
3735    ///
3736    /// - An operator-facing "exactly one dependency still unfulfilled:
3737    ///   X" diagnostic on an aggregate boundary check whose `X` is
3738    ///   known statically reads `parent.lacks_only(X)` at ONE
3739    ///   substrate site — one fused short-circuit walk, no allocation,
3740    ///   strictly cheaper than the widened composition.
3741    /// - A `lacks-only-<kind>` require-tag classifier arm reaches this
3742    ///   primitive at ONE call site — the argument-scoped peer of the
3743    ///   arg-less `has_unique_missing_kind` classifier, closed-set-
3744    ///   complement mirror of the `is-only-<kind>` classifier arm on
3745    ///   the populated axis.
3746    /// - A coherence check verifying "the near-saturation parent from
3747    ///   an `all_but_one_slot_X(k)` factory is unambiguously missing
3748    ///   kind `k`" reads `parent.lacks_only(k)` at ONE site — the
3749    ///   strongest structural pin on the missing-side well-formed
3750    ///   diagonal.
3751    /// - A fast-path branch on the near-saturation arm that
3752    ///   discriminates "exactly one specific slot still empty" from
3753    ///   "0 or ≥ 2 still empty or some OTHER slot empty" reads
3754    ///   `parent.lacks_only(kind)` at ONE call site — the fused-walk
3755    ///   short-circuit is strictly cheaper than
3756    ///   `parent.unique_missing_kind() == Some(kind)` on every arm
3757    ///   where a first-missing-slot mismatch would prune the walk
3758    ///   before the second missing slot.
3759    ///
3760    /// A new [`Self::Kind`] variant added to
3761    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
3762    /// this primitive mechanically — the fused walk picks up the new
3763    /// slot as an additional short-circuit candidate at every
3764    /// downstream callsite without further per-caller edit.
3765    ///
3766    /// # Theory grounding
3767    ///
3768    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3769    ///   The kind-scoped strict-refinement projection on the missing
3770    ///   axis lives at ONE substrate site as a fused short-circuit
3771    ///   walk over `<Self::Kind as ClosedSet>::ALL` under a negated
3772    ///   [`Self::has`] with early exit on the first missing slot
3773    ///   whose kind is not `kind` — byte-for-byte peer of
3774    ///   [`Self::has_only`]'s fused walk under complement,
3775    ///   semantically identical to
3776    ///   `unique_missing_kind() == Some(kind)` on every arm.
3777    /// - THEORY.md §VI.1 — generation over composition. A new
3778    ///   [`Self::Kind`] variant added to `ALL` reaches this primitive
3779    ///   mechanically through the fused walk.
3780    fn lacks_only(&self, kind: Self::Kind) -> bool
3781    where
3782        Self::Kind: PartialEq,
3783    {
3784        let mut saw_kind = false;
3785        for k in <Self::Kind as tatara_closed_set::ClosedSet>::ALL
3786            .iter()
3787            .copied()
3788        {
3789            if self.has(k) {
3790                continue;
3791            }
3792            if k == kind {
3793                saw_kind = true;
3794            } else {
3795                return false;
3796            }
3797        }
3798        saw_kind
3799    }
3800}
3801
3802/// Generic diagnostic-stability testkit — pins that [`TaggedUnion::KIND_LIST`]
3803/// matches `<T::Kind as tatara_closed_set::ClosedSet>::labels_joined("/")`
3804/// byte-identically for every implementor.
3805///
3806/// Substrate primitive for the four sibling
3807/// `_error_empty_lists_every_kind_in_canonical_order` tests on
3808/// `ProcessSpec` ([`crate::intent::Intent`],
3809/// [`crate::encapsulates::EncapsulationKind`],
3810/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
3811/// that pre-lift each restated the same
3812/// `assert_eq!(<XxxKind as ClosedSet>::labels_joined("/"),
3813/// XXX_KIND_LIST)` two-argument comparison at their own test bodies —
3814/// byte-identical projections whose only per-carrier knobs (the Kind
3815/// type + the KIND_LIST constant) are the two associated items the
3816/// [`TaggedUnion`] trait names. Post-lift each site collapses to ONE
3817/// `assert_kind_list_matches_closed_set::<Xxx>()` invocation whose
3818/// body is the substrate primitive's own dispatch.
3819///
3820/// A fifth sibling tagged-union parent picks up the diagnostic-
3821/// stability check through ONE `impl TaggedUnion for X` block + ONE
3822/// `assert_kind_list_matches_closed_set::<X>()` call site — no
3823/// re-authored `<XKind as ClosedSet>::labels_joined("/")` composition
3824/// at the test site, no re-authored per-site `assert_eq!` pair.
3825#[track_caller]
3826pub fn assert_kind_list_matches_closed_set<T: TaggedUnion>() {
3827    let derived = <T::Kind as tatara_closed_set::ClosedSet>::labels_joined("/");
3828    assert_eq!(
3829        derived,
3830        T::KIND_LIST,
3831        "TaggedUnion KIND_LIST drift — must equal <T::Kind as ClosedSet>::labels_joined(\"/\")",
3832    );
3833}
3834
3835/// Generic presence-probe testkit — pins that [`TaggedUnion::has`]
3836/// agrees with [`VariantSelector::select`]`.is_some()` across every
3837/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) entry, both
3838/// on the diagonal (populated slot AND matching kind → `true`) and
3839/// off the diagonal (populated slot BUT other kind → `false`).
3840///
3841/// Substrate primitive for the presence-probe half of the tagged-
3842/// union contract — dispatch tables that key off `intent-<kind>` /
3843/// `channel-<kind>` / `source-<kind>` require-tags gain a `.has(k)`
3844/// call that structurally CANNOT drift from the closed-set sweep,
3845/// but the pin here surfaces a `has` override that would break the
3846/// contract (e.g. a future specialization that always returned
3847/// `false`) at ONE call site rather than at every downstream
3848/// dispatcher.
3849///
3850/// A fifth sibling tagged-union parent picks up the presence-probe
3851/// check through ONE `assert_has_matches_select::<X, _>(single_slot)`
3852/// invocation — no re-authored `for k in K::ALL { … }` sweep at the
3853/// test site.
3854#[track_caller]
3855pub fn assert_has_matches_select<T, F>(single_slot: F)
3856where
3857    T: TaggedUnion,
3858    T::Kind: PartialEq + std::fmt::Debug,
3859    F: Fn(T::Kind) -> T,
3860{
3861    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
3862        .iter()
3863        .copied()
3864    {
3865        let parent = single_slot(populated);
3866        for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
3867            .iter()
3868            .copied()
3869        {
3870            let expected = probed == populated;
3871            assert_eq!(
3872                parent.has(probed),
3873                expected,
3874                "TaggedUnion::has drift — populated={populated:?} probed={probed:?} expected={expected}",
3875            );
3876            assert_eq!(
3877                probed.select(&parent).is_some(),
3878                expected,
3879                "VariantSelector::select drift — populated={populated:?} probed={probed:?} expected={expected}",
3880            );
3881        }
3882    }
3883}
3884
3885/// Generic widened-probe testkit — pins that [`TaggedUnion::find`]
3886/// agrees with [`TaggedUnion::has`] AND with
3887/// [`VariantSelector::select`] across every
3888/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) entry, and
3889/// that the returned borrowed view round-trips through
3890/// [`VariantKind::variant_kind`] back to the addressing Kind on the
3891/// populated diagonal.
3892///
3893/// Substrate primitive for the widened half of the presence-probe
3894/// contract — dispatch tables that key off `intent-<kind>` /
3895/// `channel-<kind>` / `source-<kind>` require-tags gain a `.find(k)`
3896/// call whose return type carries the borrowed variant payload for
3897/// diagnostic composition (an operator-facing "channel-<kind>
3898/// matched with e.channel.<field>.<key>=<value>" message, a
3899/// coherence check that projects the borrowed variant into its
3900/// Kind for round-trip validation), and the pin here surfaces a
3901/// `find` override that would drift from the composition law
3902/// `has(k) == find(k).is_some()` at ONE call site rather than at
3903/// every downstream dispatcher.
3904///
3905/// The three sub-assertions swept per (populated, probed) pair:
3906///
3907/// 1. `parent.find(probed).is_some() == parent.has(probed)` — the
3908///    composition law binding [`TaggedUnion::has`] to
3909///    [`TaggedUnion::find`] via `find(k).is_some()`.
3910/// 2. `parent.find(probed).is_some() == probed.select(&parent).is_some()`
3911///    — the widened primitive delegates to
3912///    [`VariantSelector::select`] on the Kind, so a regression that
3913///    inlined a divergent walk body at the trait's `find` default
3914///    fails here rather than as silent drift at every downstream
3915///    diagnostic consumer.
3916/// 3. On the populated diagonal (`probed == populated`), the
3917///    returned borrowed view satisfies
3918///    `find(k).unwrap().variant_kind() == k` — the round-trip
3919///    contract that closes `find` (forward-widened) against
3920///    [`VariantKind::variant_kind`] (reverse projection).
3921///
3922/// A fifth sibling tagged-union parent picks up the widened-probe
3923/// check through ONE `assert_find_agrees_with_has::<X, _>(single_slot)`
3924/// invocation — no re-authored `for k in K::ALL { … }` sweep at the
3925/// test site.
3926#[track_caller]
3927pub fn assert_find_agrees_with_has<T, F>(single_slot: F)
3928where
3929    T: TaggedUnion,
3930    T::Kind: PartialEq + std::fmt::Debug,
3931    F: Fn(T::Kind) -> T,
3932{
3933    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
3934        .iter()
3935        .copied()
3936    {
3937        let parent = single_slot(populated);
3938        for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
3939            .iter()
3940            .copied()
3941        {
3942            let expected = probed == populated;
3943            let via_has = parent.has(probed);
3944            let via_find = parent.find(probed).is_some();
3945            let via_select = probed.select(&parent).is_some();
3946            assert_eq!(
3947                via_find, via_has,
3948                "TaggedUnion::find drifted from has — populated={populated:?} probed={probed:?}",
3949            );
3950            assert_eq!(
3951                via_find, via_select,
3952                "TaggedUnion::find drifted from VariantSelector::select — populated={populated:?} probed={probed:?}",
3953            );
3954            assert_eq!(
3955                via_find, expected,
3956                "TaggedUnion::find truth-table drift — populated={populated:?} probed={probed:?} expected={expected}",
3957            );
3958            if expected {
3959                let variant = parent.find(probed).unwrap_or_else(|| {
3960                    panic!("TaggedUnion::find must return Some for populated slot {probed:?}",)
3961                });
3962                assert_eq!(
3963                    <<T::Kind as VariantSelector<T>>::Variant<'_> as VariantKind<T::Kind>>::variant_kind(
3964                        &variant,
3965                    ),
3966                    probed,
3967                    "find→variant_kind round-trip failed for {probed:?}",
3968                );
3969            }
3970        }
3971    }
3972}
3973
3974/// Generic closed-set-inversion testkit — pins that
3975/// [`TaggedUnion::populated_kinds`] composes over
3976/// [`TaggedUnion::has`] across every
3977/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) entry on
3978/// the single-slot side, that the returned `Vec` is the canonical
3979/// [`ClosedSet::ALL`]-ordered filter of `has(k)`, and that on the
3980/// populated diagonal `single_slot(k).populated_kinds()` equals
3981/// `vec![k]` exactly (length 1, canonical ordered, no drift).
3982///
3983/// Parent-axis substrate primitive for the tagged-union closed-set-
3984/// inversion refinement — the peer of
3985/// [`crate::boundary::assert_slice_refinement_composition_laws`]'s
3986/// `distinct_kinds` sub-arm on the slice-level presence-probe axis,
3987/// lifted here to the tagged-union parent-level presence-probe axis
3988/// (same shape, same composition operator, second instance in the
3989/// workspace-wide closed-set-inversion refinement algebra).
3990///
3991/// The three sub-assertions swept per (populated, probed) pair:
3992///
3993/// 1. Per-kind membership: `parent.populated_kinds().contains(&k) ==
3994///    parent.has(k)` for every `k ∈ ClosedSet::ALL` — a regression
3995///    that overrode `populated_kinds` to skip a kind, drift the walk
3996///    order from canonical `ALL` to slot-encounter order, or return
3997///    a superset containing absent kinds surfaces at the specific
3998///    kind's per-pair assertion.
3999/// 2. Canonical `ALL`-filter equality:
4000///    `parent.populated_kinds() == ALL.iter().copied().filter(|k|
4001///    parent.has(*k)).collect()` — a regression that returned
4002///    duplicates (a naive override that skipped dedup by
4003///    construction) or drifted the walk order surfaces at the
4004///    post-loop equality assert.
4005/// 3. Single-slot diagonal: `single_slot(k).populated_kinds() ==
4006///    vec![k]` exactly — pins the single-populated arm's cardinality
4007///    (length 1) and ordering (the addressed kind's own position in
4008///    `ALL`) together at ONE assert.
4009///
4010/// Substrate primitive for future per-parent
4011/// `X_populated_kinds_matches_has` tests that would otherwise each
4012/// restate the same nested-`for populated in K::ALL { for probed in
4013/// K::ALL { … } }` sweep + canonical-order equality + single-slot
4014/// diagonal pin — every one of the four production `.variant()`
4015/// parents on `ProcessSpec` binds through this ONE primitive with a
4016/// per-site `single_slot` factory. A fifth sibling picks up the
4017/// closed-set-inversion check through ONE call site — no re-authored
4018/// `for k in K::ALL { … }` sweep at the test surface, no re-authored
4019/// `assert_eq!` triad.
4020///
4021/// The `single_slot` closure stays per-site — reused verbatim from
4022/// the sibling primitives ([`assert_variant_round_trip`],
4023/// [`assert_find_agrees_with_has`],
4024/// [`assert_single_slot_key_matches_label`]) — the closure IS the
4025/// "populate slot k" ground truth for the parent's field structure.
4026///
4027/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
4028/// through the `T: TaggedUnion` bound — `Lifetime`'s `variant()`
4029/// returns `Ok(Permanent)` on empty rather than an `Empty` typed
4030/// error, so its projection shape diverges from the four
4031/// Empty-projecting parents. Same reasoning as
4032/// [`assert_variant_round_trip`]'s /
4033/// [`assert_find_agrees_with_has`]'s exclusions.
4034#[track_caller]
4035pub fn assert_populated_kinds_matches_has<T, F>(single_slot: F)
4036where
4037    T: TaggedUnion,
4038    T::Kind: PartialEq + std::fmt::Debug,
4039    F: Fn(T::Kind) -> T,
4040{
4041    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4042        .iter()
4043        .copied()
4044    {
4045        let parent = single_slot(populated);
4046        let kinds = parent.populated_kinds();
4047        // Per-kind membership composition law.
4048        for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4049            .iter()
4050            .copied()
4051        {
4052            assert_eq!(
4053                kinds.contains(&probed),
4054                parent.has(probed),
4055                "TaggedUnion::populated_kinds().contains({probed:?}) drifted from has({probed:?}) — populated={populated:?}",
4056            );
4057        }
4058        // Canonical ALL-filter equality — pins dedup, walk order, and
4059        // membership consistency at ONE assert.
4060        let canonical: Vec<T::Kind> = <T::Kind as tatara_closed_set::ClosedSet>::ALL
4061            .iter()
4062            .copied()
4063            .filter(|k| parent.has(*k))
4064            .collect();
4065        assert_eq!(
4066            kinds, canonical,
4067            "TaggedUnion::populated_kinds() must yield ClosedSet::ALL-ordered subsequence where has is true (no duplicates, canonical order) — populated={populated:?}",
4068        );
4069        // Single-slot diagonal — the addressed slot IS the ONLY
4070        // populated slot on the parent single_slot produces, so the
4071        // canonical filter yields exactly [populated].
4072        assert_eq!(
4073            kinds,
4074            vec![populated],
4075            "TaggedUnion::populated_kinds() on single_slot({populated:?}) must return vec![{populated:?}] exactly",
4076        );
4077    }
4078}
4079
4080/// Generic two-slot closed-set-inversion testkit — peer of
4081/// [`assert_populated_kinds_matches_has`] on the ambiguous-parent
4082/// side. Pins that a `two_slot(a, b)` parent's `populated_kinds()`
4083/// yields the canonical `ClosedSet::ALL`-ordered pair
4084/// `[min_all(a,b), max_all(a,b)]` (length exactly 2, dedup + walk
4085/// order enforced), and that per-kind membership composes
4086/// byte-identically against `has(k)` on the malformed-parent arm.
4087///
4088/// The two-slot fixture is the SAME factory production sites already
4089/// hand [`assert_two_slots_ambiguous`] — every one of the four
4090/// production `.variant()` parents on `ProcessSpec` composes
4091/// `two_slot(a, b)` through per-field `Option::or` on
4092/// `single_slot(a)` and `single_slot(b)`, so BOTH slots on the
4093/// resulting parent are populated. The primitive's off-diagonal
4094/// sweep (`a != b`) pins that `populated_kinds()` NAMES both
4095/// populated slots on the malformed arm — the diagnostic-surface
4096/// promise the payload-free
4097/// [`TaggedUnionError::ambiguous`] carrier stops short of.
4098///
4099/// The three sub-assertions swept per `(a, b)` off-diagonal pair:
4100///
4101/// 1. Cardinality: `populated_kinds().len() == 2` — a regression
4102///    that returned a length-1 vec (silently short-circuiting on
4103///    the first populated slot; drifting the walk from `ALL` to
4104///    single-match `find`) fails HERE at the length assert.
4105/// 2. Per-kind membership: `populated_kinds().contains(&k) ==
4106///    has(k)` for every `k ∈ ClosedSet::ALL` — the composition law
4107///    of the closed-set-inversion refinement, pinned on the
4108///    multi-populated arm.
4109/// 3. Canonical `ALL`-filter equality:
4110///    `populated_kinds() == ALL.iter().copied().filter(|k|
4111///    parent.has(*k)).collect()` — pins the walk order (a
4112///    regression that yielded `[b, a]` because it walked the two
4113///    populated slots in construction order instead of
4114///    `ClosedSet::ALL` order fails at the equality assert).
4115///
4116/// A fifth sibling tagged-union parent picks up the two-slot
4117/// closed-set-inversion check through ONE call site — no
4118/// re-authored nested-for sweep at the test surface, no re-authored
4119/// `assert_eq!` triad.
4120///
4121/// Same `Lifetime` exclusion as [`assert_populated_kinds_matches_has`]:
4122/// the `T: TaggedUnion` bound doesn't reach it.
4123#[track_caller]
4124pub fn assert_populated_kinds_across_pairs<T, F>(two_slot: F)
4125where
4126    T: TaggedUnion,
4127    T::Kind: PartialEq + std::fmt::Debug,
4128    F: Fn(T::Kind, T::Kind) -> T,
4129{
4130    for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4131        .iter()
4132        .copied()
4133    {
4134        for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4135            .iter()
4136            .copied()
4137        {
4138            if a == b {
4139                continue;
4140            }
4141            let parent = two_slot(a, b);
4142            let kinds = parent.populated_kinds();
4143            assert_eq!(
4144                kinds.len(),
4145                2,
4146                "TaggedUnion::populated_kinds() on two_slot({a:?}, {b:?}) must return exactly two populated kinds, got {kinds:?}",
4147            );
4148            for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4149                .iter()
4150                .copied()
4151            {
4152                assert_eq!(
4153                    kinds.contains(&probed),
4154                    parent.has(probed),
4155                    "TaggedUnion::populated_kinds().contains({probed:?}) drifted from has({probed:?}) — (a, b)=({a:?}, {b:?})",
4156                );
4157            }
4158            let canonical: Vec<T::Kind> = <T::Kind as tatara_closed_set::ClosedSet>::ALL
4159                .iter()
4160                .copied()
4161                .filter(|k| parent.has(*k))
4162                .collect();
4163            assert_eq!(
4164                kinds, canonical,
4165                "TaggedUnion::populated_kinds() must yield ClosedSet::ALL-ordered pair on two_slot({a:?}, {b:?}) — got {kinds:?}, expected {canonical:?}",
4166            );
4167        }
4168    }
4169}
4170
4171/// Generic scalar-cardinality testkit — pins that
4172/// [`TaggedUnion::populated_kind_count`] agrees with
4173/// [`TaggedUnion::populated_kinds`]`.len()` across every
4174/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
4175/// arrangement AND that on the populated diagonal
4176/// `single_slot(k).populated_kind_count()` equals `1` exactly (aligned
4177/// with the single-slot arm's `populated_kinds()` returning
4178/// `vec![k]`).
4179///
4180/// Parent-axis substrate primitive for the scalar-cardinality
4181/// refinement of the tagged-union closed-set-inversion axis — the
4182/// scalar projection of [`assert_populated_kinds_matches_has`]'s
4183/// widened primitive. Together they close the two-refinement
4184/// composition contract that binds
4185/// [`TaggedUnion::populated_kind_count`] against
4186/// [`TaggedUnion::populated_kinds`]:
4187///
4188/// 1. **`count ↔ kinds.len()`**: `populated_kind_count() ==
4189///    populated_kinds().len()` — a regression that overrode
4190///    `populated_kind_count` to skip a kind (returning `0` on a
4191///    populated parent), double-count a slot (returning `2` on a
4192///    single-slot parent), or drift the walk from `ClosedSet::ALL`
4193///    surfaces at the substrate boundary here.
4194/// 2. **Single-slot diagonal**: `single_slot(k).populated_kind_count()
4195///    == 1` — pins the well-formed arm's expected cardinality
4196///    against the empty (`0`) and Ambiguous (`≥ 2`) arms, at ONE
4197///    `assert_eq!` per addressed kind.
4198///
4199/// Substrate primitive for future per-parent
4200/// `X_populated_kind_count_matches_populated_kinds_len` tests that
4201/// would otherwise each restate the same nested-`for k in K::ALL {
4202/// … }` sweep + composition-law equality + single-slot cardinality
4203/// pin — every one of the four production `.variant()` parents on
4204/// `ProcessSpec` binds through this ONE primitive with a per-site
4205/// `single_slot` factory. A fifth sibling picks up the scalar-
4206/// cardinality check through ONE call site — no re-authored
4207/// `for k in K::ALL { … }` sweep at the test surface, no re-authored
4208/// `assert_eq!` pair.
4209///
4210/// The `single_slot` closure stays per-site — reused verbatim from
4211/// the sibling primitives ([`assert_variant_round_trip`],
4212/// [`assert_find_agrees_with_has`],
4213/// [`assert_populated_kinds_matches_has`],
4214/// [`assert_single_slot_key_matches_label`]) — the closure IS the
4215/// "populate slot k" ground truth for the parent's field structure.
4216///
4217/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
4218/// through the `T: TaggedUnion` bound — `Lifetime`'s `variant()`
4219/// returns `Ok(Permanent)` on empty rather than an `Empty` typed
4220/// error, so its projection shape diverges from the four
4221/// Empty-projecting parents. Same reasoning as
4222/// [`assert_variant_round_trip`]'s /
4223/// [`assert_find_agrees_with_has`]'s /
4224/// [`assert_populated_kinds_matches_has`]'s exclusions.
4225#[track_caller]
4226pub fn assert_populated_kind_count_matches_populated_kinds<T, F>(single_slot: F)
4227where
4228    T: TaggedUnion,
4229    T::Kind: PartialEq + std::fmt::Debug,
4230    F: Fn(T::Kind) -> T,
4231{
4232    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4233        .iter()
4234        .copied()
4235    {
4236        let parent = single_slot(populated);
4237        let count = parent.populated_kind_count();
4238        let kinds_len = parent.populated_kinds().len();
4239        // Composition law: scalar cardinality projection agrees with
4240        // the widened primitive's `Vec::len()`.
4241        assert_eq!(
4242            count, kinds_len,
4243            "TaggedUnion::populated_kind_count() drifted from populated_kinds().len() — populated={populated:?}",
4244        );
4245        // Single-slot diagonal — a well-formed parent from single_slot
4246        // populates exactly the addressed slot, so the scalar cardinality
4247        // is 1.
4248        assert_eq!(
4249            count, 1,
4250            "TaggedUnion::populated_kind_count() on single_slot({populated:?}) must equal 1 exactly (well-formed arm cardinality)",
4251        );
4252    }
4253}
4254
4255/// Generic closed-set-COMPLEMENT testkit — pins that
4256/// [`TaggedUnion::missing_kinds`] composes over
4257/// [`TaggedUnion::has`] under NEGATION across every
4258/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) entry on
4259/// the single-slot side, that the returned `Vec` is the canonical
4260/// [`ClosedSet::ALL`]-ordered filter of `!has(k)`, that on the
4261/// populated diagonal `single_slot(k).missing_kinds()` equals
4262/// `ALL \ {k}` exactly (length `ALL.len() - 1`, canonical ordered,
4263/// `k` absent), AND that the partition law
4264/// `populated_kinds() ∪ missing_kinds() == ClosedSet::ALL` (with
4265/// the two sets disjoint) holds byte-identically.
4266///
4267/// Parent-axis substrate primitive for the tagged-union closed-set-
4268/// complement refinement — the peer of
4269/// [`crate::boundary::assert_slice_refinement_composition_laws`]'s
4270/// `missing_kinds` sub-arm on the slice-level presence-probe axis,
4271/// lifted here to the tagged-union parent-level presence-probe axis
4272/// (same shape, same composition operator under negation, second
4273/// instance in the workspace-wide closed-set-complement refinement
4274/// algebra).
4275///
4276/// The FOUR sub-assertions swept per populated slot:
4277///
4278/// 1. Per-kind membership under negation:
4279///    `parent.missing_kinds().contains(&k) == !parent.has(k)` for
4280///    every `k ∈ ClosedSet::ALL` — a regression that overrode
4281///    `missing_kinds` to skip a kind, drift the walk order from
4282///    canonical `ALL`, or return a superset containing populated
4283///    kinds surfaces at the specific kind's per-pair assertion.
4284/// 2. Canonical `ALL`-filter equality under negation:
4285///    `parent.missing_kinds() == ALL.iter().copied().filter(|k|
4286///    !parent.has(*k)).collect()` — a regression that returned
4287///    duplicates or drifted the walk order surfaces at the
4288///    post-loop equality assert.
4289/// 3. Single-slot diagonal: `single_slot(k).missing_kinds()`
4290///    equals `ALL` with `k` removed — length exactly `ALL.len() - 1`,
4291///    canonical order preserved. Pins the well-formed arm's
4292///    complement cardinality.
4293/// 4. Partition law: `populated_kinds() ∪ missing_kinds() ==
4294///    ClosedSet::ALL` byte-identically (concatenated then re-sorted
4295///    into canonical `ALL` order) AND the two sets are disjoint
4296///    (no kind appears in both). A regression on either side of the
4297///    partition (a kind that appears in NEITHER, or in BOTH) fails
4298///    HERE at the partition assert — the compound-lift's most-
4299///    load-bearing invariant.
4300///
4301/// Substrate primitive for future per-parent
4302/// `X_missing_kinds_matches_has` tests that would otherwise each
4303/// restate the same nested-`for populated in K::ALL { for probed
4304/// in K::ALL { … } }` sweep + canonical-order equality + single-
4305/// slot diagonal pin + partition-law composition — every one of
4306/// the four production `.variant()` parents on `ProcessSpec` binds
4307/// through this ONE primitive with a per-site `single_slot`
4308/// factory. A fifth sibling picks up the closed-set-complement
4309/// check through ONE call site — no re-authored `for k in K::ALL
4310/// { … }` sweep at the test surface, no re-authored `assert_eq!`
4311/// quad.
4312///
4313/// The `single_slot` closure stays per-site — reused verbatim from
4314/// the sibling primitives ([`assert_variant_round_trip`],
4315/// [`assert_find_agrees_with_has`],
4316/// [`assert_populated_kinds_matches_has`],
4317/// [`assert_populated_kind_count_matches_populated_kinds`],
4318/// [`assert_single_slot_key_matches_label`]).
4319///
4320/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
4321/// through the `T: TaggedUnion` bound — same reasoning as the
4322/// sibling primitives.
4323#[track_caller]
4324pub fn assert_missing_kinds_matches_has<T, F>(single_slot: F)
4325where
4326    T: TaggedUnion,
4327    T::Kind: PartialEq + std::fmt::Debug,
4328    F: Fn(T::Kind) -> T,
4329{
4330    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4331        .iter()
4332        .copied()
4333    {
4334        let parent = single_slot(populated);
4335        let missing = parent.missing_kinds();
4336        let populated_kinds = parent.populated_kinds();
4337        // Per-kind membership composition law under negation, AND the
4338        // XOR partition arm: every k ∈ ALL appears in exactly one of
4339        // (populated_kinds, missing_kinds).
4340        for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4341            .iter()
4342            .copied()
4343        {
4344            assert_eq!(
4345                missing.contains(&probed),
4346                !parent.has(probed),
4347                "TaggedUnion::missing_kinds().contains({probed:?}) drifted from !has({probed:?}) — populated={populated:?}",
4348            );
4349            // XOR partition law: k ∈ populated_kinds ⊕ k ∈ missing_kinds
4350            // — every closed-set entry lives on EXACTLY ONE side of the
4351            // partition (populated OR missing, never both, never neither).
4352            let in_populated = populated_kinds.contains(&probed);
4353            let in_missing = missing.contains(&probed);
4354            assert!(
4355                in_populated ^ in_missing,
4356                "partition law violated — {probed:?} appears in {} of (populated_kinds, missing_kinds), not exactly one (populated={populated:?})",
4357                (in_populated as u8) + (in_missing as u8),
4358            );
4359        }
4360        // Canonical ALL-filter equality under negation — pins dedup,
4361        // walk order, and membership consistency at ONE assert.
4362        let canonical: Vec<T::Kind> = <T::Kind as tatara_closed_set::ClosedSet>::ALL
4363            .iter()
4364            .copied()
4365            .filter(|k| !parent.has(*k))
4366            .collect();
4367        assert_eq!(
4368            missing, canonical,
4369            "TaggedUnion::missing_kinds() must yield ClosedSet::ALL-ordered subsequence where !has is true (no duplicates, canonical order) — populated={populated:?}",
4370        );
4371        // Single-slot diagonal — a well-formed parent from single_slot
4372        // populates exactly the addressed slot, so the missing set is
4373        // `ALL \ {populated}` in canonical order (length ALL.len() - 1,
4374        // `populated` absent).
4375        let expected_missing: Vec<T::Kind> = <T::Kind as tatara_closed_set::ClosedSet>::ALL
4376            .iter()
4377            .copied()
4378            .filter(|k| *k != populated)
4379            .collect();
4380        assert_eq!(
4381            missing, expected_missing,
4382            "TaggedUnion::missing_kinds() on single_slot({populated:?}) must return ClosedSet::ALL with {populated:?} removed",
4383        );
4384    }
4385}
4386
4387/// Generic scalar-cardinality testkit for the closed-set-complement
4388/// axis — pins that [`TaggedUnion::missing_kind_count`] agrees with
4389/// [`TaggedUnion::missing_kinds`]`.len()` across every
4390/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
4391/// arrangement AND that on the populated diagonal
4392/// `single_slot(k).missing_kind_count()` equals `ALL.len() - 1`
4393/// exactly (aligned with the single-slot arm's `missing_kinds()`
4394/// returning `ALL \ {k}`) AND that the scalar partition law
4395/// `populated_kind_count() + missing_kind_count() == ALL.len()`
4396/// holds byte-identically.
4397///
4398/// Parent-axis substrate primitive for the scalar-cardinality
4399/// refinement of the tagged-union closed-set-complement axis — the
4400/// scalar projection of [`assert_missing_kinds_matches_has`]'s
4401/// widened primitive. Together they close the three-refinement
4402/// composition contract that binds
4403/// [`TaggedUnion::missing_kind_count`] against
4404/// [`TaggedUnion::missing_kinds`] and against
4405/// [`TaggedUnion::populated_kind_count`]:
4406///
4407/// 1. **`count ↔ kinds.len()`**: `missing_kind_count() ==
4408///    missing_kinds().len()` — a regression that overrode
4409///    `missing_kind_count` to skip a kind (returning the populated
4410///    count instead), double-count a slot, or drift the walk from
4411///    `ClosedSet::ALL` surfaces at the substrate boundary here.
4412/// 2. **Single-slot diagonal**: `single_slot(k).missing_kind_count()
4413///    == ALL.len() - 1` — pins the well-formed arm's complement
4414///    cardinality against the empty (`ALL.len()`) and Ambiguous
4415///    (`< ALL.len() - 1`) arms.
4416/// 3. **Scalar partition law**: `populated_kind_count() +
4417///    missing_kind_count() == ALL.len()` — the scalar consequence
4418///    of the `(populated_kinds, missing_kinds)` partition law that
4419///    [`assert_missing_kinds_matches_has`] pins at the widened-
4420///    primitive layer. A regression on either scalar side (an
4421///    off-by-one on missing, a drift on populated) fails HERE at
4422///    the sum assertion.
4423///
4424/// Substrate primitive for future per-parent
4425/// `X_missing_kind_count_matches_missing_kinds_len` tests that
4426/// would otherwise each restate the same nested-`for k in K::ALL {
4427/// … }` sweep + composition-law equality + single-slot cardinality
4428/// pin + scalar partition — every one of the four production
4429/// `.variant()` parents on `ProcessSpec` binds through this ONE
4430/// primitive with a per-site `single_slot` factory. A fifth sibling
4431/// picks up the scalar-cardinality check through ONE call site.
4432///
4433/// The `single_slot` closure stays per-site — reused verbatim from
4434/// the sibling primitives ([`assert_variant_round_trip`],
4435/// [`assert_find_agrees_with_has`],
4436/// [`assert_populated_kinds_matches_has`],
4437/// [`assert_populated_kind_count_matches_populated_kinds`],
4438/// [`assert_missing_kinds_matches_has`],
4439/// [`assert_single_slot_key_matches_label`]).
4440///
4441/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
4442/// through the `T: TaggedUnion` bound — same reasoning as the
4443/// sibling primitives.
4444#[track_caller]
4445pub fn assert_missing_kind_count_matches_missing_kinds<T, F>(single_slot: F)
4446where
4447    T: TaggedUnion,
4448    T::Kind: PartialEq + std::fmt::Debug,
4449    F: Fn(T::Kind) -> T,
4450{
4451    let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
4452    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4453        .iter()
4454        .copied()
4455    {
4456        let parent = single_slot(populated);
4457        let count = parent.missing_kind_count();
4458        let missing_len = parent.missing_kinds().len();
4459        // Composition law: scalar cardinality projection agrees with
4460        // the widened primitive's `Vec::len()`.
4461        assert_eq!(
4462            count, missing_len,
4463            "TaggedUnion::missing_kind_count() drifted from missing_kinds().len() — populated={populated:?}",
4464        );
4465        // Single-slot diagonal — a well-formed parent from single_slot
4466        // populates exactly the addressed slot, so the missing count is
4467        // ALL.len() - 1.
4468        assert_eq!(
4469            count,
4470            all_len - 1,
4471            "TaggedUnion::missing_kind_count() on single_slot({populated:?}) must equal ALL.len() - 1 exactly (well-formed arm complement cardinality)",
4472        );
4473        // Scalar partition law: populated_kind_count + missing_kind_count == ALL.len().
4474        let populated_count = parent.populated_kind_count();
4475        assert_eq!(
4476            populated_count + count,
4477            all_len,
4478            "scalar partition law violated — populated_kind_count + missing_kind_count must equal ClosedSet::ALL.len() (populated={populated:?})",
4479        );
4480    }
4481}
4482
4483/// Generic earliest-populated-kind testkit — pins that
4484/// [`TaggedUnion::first_populated_kind`] agrees with
4485/// [`TaggedUnion::populated_kinds`]`.first().copied()` across every
4486/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
4487/// arrangement AND that on the populated diagonal
4488/// `single_slot(k).first_populated_kind()` equals `Some(k)` exactly.
4489///
4490/// Parent-axis substrate primitive for the earliest-element scalar
4491/// projection of the tagged-union closed-set-inversion axis — the
4492/// `Option<Kind>`-valued projection of
4493/// [`assert_populated_kinds_matches_has`]'s widened primitive. The
4494/// three sub-assertions swept per populated slot:
4495///
4496/// 1. **`first ↔ kinds.first().copied()`**: `first_populated_kind() ==
4497///    populated_kinds().first().copied()` — a regression that
4498///    overrode `first_populated_kind` to skip the earliest match (a
4499///    `.rev().find(...)` inlined by mistake), drop the short-circuit
4500///    (allocating a full `Vec` at the callsite), or drift the walk
4501///    from `ClosedSet::ALL` surfaces here.
4502/// 2. **Single-slot diagonal**: `single_slot(k).first_populated_kind()
4503///    == Some(k)` — the earliest populated slot on a well-formed
4504///    parent IS the sole populated slot.
4505/// 3. **Emptiness composition law**: `first_populated_kind().is_none()
4506///    == (populated_kind_count() == 0)` — the earliest-element
4507///    projection agrees with the scalar cardinality on the empty
4508///    boundary. (Trivially `false == false` on every single-slot
4509///    arrangement; the load-bearing case is the sibling
4510///    empty-parent probe outside this primitive.)
4511///
4512/// A fifth sibling picks up the earliest-populated check through ONE
4513/// call site — no re-authored `for k in K::ALL` sweep, no re-authored
4514/// `assert_eq!(single_slot(k).first_populated_kind(), Some(k))`.
4515///
4516/// Same `Lifetime` exclusion as the sibling primitives.
4517#[track_caller]
4518pub fn assert_first_populated_kind_matches_populated_kinds<T, F>(single_slot: F)
4519where
4520    T: TaggedUnion,
4521    T::Kind: PartialEq + std::fmt::Debug,
4522    F: Fn(T::Kind) -> T,
4523{
4524    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4525        .iter()
4526        .copied()
4527    {
4528        let parent = single_slot(populated);
4529        let first = parent.first_populated_kind();
4530        let via_kinds = parent.populated_kinds().first().copied();
4531        // Composition law: earliest-element projection agrees with the
4532        // widened primitive's `Vec::first().copied()`.
4533        assert_eq!(
4534            first, via_kinds,
4535            "TaggedUnion::first_populated_kind() drifted from populated_kinds().first().copied() — populated={populated:?}",
4536        );
4537        // Single-slot diagonal — a well-formed parent from single_slot
4538        // populates exactly the addressed slot, so the earliest
4539        // populated slot IS that slot.
4540        assert_eq!(
4541            first,
4542            Some(populated),
4543            "TaggedUnion::first_populated_kind() on single_slot({populated:?}) must equal Some({populated:?}) exactly",
4544        );
4545        // Emptiness composition law on the well-formed diagonal —
4546        // exactly-one is a strictly non-empty populated set, so the
4547        // scalar cardinality and the earliest-element `is_some()`
4548        // agree.
4549        assert_eq!(
4550            first.is_some(),
4551            parent.populated_kind_count() > 0,
4552            "first_populated_kind().is_some() drifted from (populated_kind_count() > 0) — populated={populated:?}",
4553        );
4554    }
4555}
4556
4557/// Generic earliest-missing-kind testkit — pins that
4558/// [`TaggedUnion::first_missing_kind`] agrees with
4559/// [`TaggedUnion::missing_kinds`]`.first().copied()` across every
4560/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
4561/// arrangement AND that on the populated diagonal
4562/// `single_slot(k).first_missing_kind()` equals the earliest `ALL`
4563/// entry NOT equal to `k`.
4564///
4565/// Parent-axis substrate primitive for the earliest-element scalar
4566/// projection of the tagged-union closed-set-complement axis — the
4567/// `Option<Kind>`-valued projection of
4568/// [`assert_missing_kinds_matches_has`]'s widened primitive under a
4569/// negated `has` predicate. The three sub-assertions swept per
4570/// populated slot:
4571///
4572/// 1. **`first ↔ missing.first().copied()`**: `first_missing_kind()
4573///    == missing_kinds().first().copied()` — a regression that
4574///    overrode `first_missing_kind` to drop the negation (returning
4575///    the populated side instead) or drift the walk from
4576///    `ClosedSet::ALL` surfaces here.
4577/// 2. **Single-slot diagonal**: `single_slot(k).first_missing_kind()`
4578///    equals the earliest `ALL` entry not equal to `k` — a well-
4579///    formed parent's missing set is `ALL \ {k}` in canonical order,
4580///    so its earliest element is `ALL[0]` when `k != ALL[0]`, else
4581///    `ALL[1]`.
4582/// 3. **Emptiness composition law**: `first_missing_kind().is_some()
4583///    == (missing_kind_count() > 0)` — the earliest-missing
4584///    projection agrees with the scalar complement cardinality.
4585///    Non-trivial on the single-slot arm when `ALL.len() > 1`.
4586///
4587/// A fifth sibling picks up the earliest-missing check through ONE
4588/// call site.
4589///
4590/// Same `Lifetime` exclusion as the sibling primitives.
4591#[track_caller]
4592pub fn assert_first_missing_kind_matches_missing_kinds<T, F>(single_slot: F)
4593where
4594    T: TaggedUnion,
4595    T::Kind: PartialEq + std::fmt::Debug,
4596    F: Fn(T::Kind) -> T,
4597{
4598    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4599        .iter()
4600        .copied()
4601    {
4602        let parent = single_slot(populated);
4603        let first = parent.first_missing_kind();
4604        let via_missing = parent.missing_kinds().first().copied();
4605        // Composition law: earliest-element projection agrees with the
4606        // widened primitive's `Vec::first().copied()`.
4607        assert_eq!(
4608            first, via_missing,
4609            "TaggedUnion::first_missing_kind() drifted from missing_kinds().first().copied() — populated={populated:?}",
4610        );
4611        // Single-slot diagonal — the missing set is ALL \ {populated}
4612        // in canonical order, so its earliest element is the earliest
4613        // ALL entry not equal to populated.
4614        let expected_first_missing = <T::Kind as tatara_closed_set::ClosedSet>::ALL
4615            .iter()
4616            .copied()
4617            .find(|k| *k != populated);
4618        assert_eq!(
4619            first, expected_first_missing,
4620            "TaggedUnion::first_missing_kind() on single_slot({populated:?}) must equal earliest ClosedSet::ALL entry != {populated:?}",
4621        );
4622        // Emptiness composition law — the earliest-missing projection
4623        // agrees with the scalar complement cardinality's positivity.
4624        assert_eq!(
4625            first.is_some(),
4626            parent.missing_kind_count() > 0,
4627            "first_missing_kind().is_some() drifted from (missing_kind_count() > 0) — populated={populated:?}",
4628        );
4629    }
4630}
4631
4632/// Generic latest-populated-kind testkit — pins that
4633/// [`TaggedUnion::last_populated_kind`] agrees with
4634/// [`TaggedUnion::populated_kinds`]`.last().copied()` across every
4635/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
4636/// arrangement AND that on the populated diagonal
4637/// `single_slot(k).last_populated_kind()` equals `Some(k)` exactly.
4638///
4639/// Parent-axis substrate primitive for the latest-element scalar
4640/// projection of the tagged-union closed-set-inversion axis — the
4641/// `Option<Kind>`-valued REVERSED-walk peer of
4642/// [`assert_first_populated_kind_matches_populated_kinds`]'s
4643/// earliest-element projection. The three sub-assertions swept per
4644/// populated slot:
4645///
4646/// 1. **`last ↔ kinds.last().copied()`**: `last_populated_kind() ==
4647///    populated_kinds().last().copied()` — a regression that overrode
4648///    `last_populated_kind` to walk `ALL` forward (defeating the
4649///    time-reversal), drop the short-circuit, or drift the walk from
4650///    `ClosedSet::ALL` surfaces here.
4651/// 2. **Single-slot diagonal**: `single_slot(k).last_populated_kind()
4652///    == Some(k)` — the sole populated slot on a well-formed parent
4653///    IS both the earliest AND the latest populated slot (the
4654///    endpoint projections agree on the exactly-one arm).
4655/// 3. **Emptiness composition law**: `last_populated_kind().is_none()
4656///    == (populated_kind_count() == 0)` — the latest-element
4657///    projection agrees with the scalar cardinality on the empty
4658///    boundary. (Trivially `false == false` on every single-slot
4659///    arrangement; the load-bearing case is the sibling empty-parent
4660///    probe outside this primitive.)
4661///
4662/// A fifth sibling picks up the latest-populated check through ONE
4663/// call site — no re-authored reversed `for k in K::ALL.iter().rev()`
4664/// sweep at the test surface, no re-authored
4665/// `assert_eq!(single_slot(k).last_populated_kind(), Some(k))`.
4666///
4667/// Same `Lifetime` exclusion as the sibling primitives.
4668#[track_caller]
4669pub fn assert_last_populated_kind_matches_populated_kinds<T, F>(single_slot: F)
4670where
4671    T: TaggedUnion,
4672    T::Kind: PartialEq + std::fmt::Debug,
4673    F: Fn(T::Kind) -> T,
4674{
4675    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4676        .iter()
4677        .copied()
4678    {
4679        let parent = single_slot(populated);
4680        let last = parent.last_populated_kind();
4681        let via_kinds = parent.populated_kinds().last().copied();
4682        // Composition law: latest-element projection agrees with the
4683        // widened primitive's `Vec::last().copied()`.
4684        assert_eq!(
4685            last, via_kinds,
4686            "TaggedUnion::last_populated_kind() drifted from populated_kinds().last().copied() — populated={populated:?}",
4687        );
4688        // Single-slot diagonal — the sole populated slot IS both the
4689        // earliest and the latest, so the endpoint projections
4690        // coincide.
4691        assert_eq!(
4692            last,
4693            Some(populated),
4694            "TaggedUnion::last_populated_kind() on single_slot({populated:?}) must equal Some({populated:?}) exactly",
4695        );
4696        // Emptiness composition law on the well-formed diagonal.
4697        assert_eq!(
4698            last.is_some(),
4699            parent.populated_kind_count() > 0,
4700            "last_populated_kind().is_some() drifted from (populated_kind_count() > 0) — populated={populated:?}",
4701        );
4702    }
4703}
4704
4705/// Generic latest-missing-kind testkit — pins that
4706/// [`TaggedUnion::last_missing_kind`] agrees with
4707/// [`TaggedUnion::missing_kinds`]`.last().copied()` across every
4708/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
4709/// arrangement AND that on the populated diagonal
4710/// `single_slot(k).last_missing_kind()` equals the latest `ALL` entry
4711/// NOT equal to `k`.
4712///
4713/// Parent-axis substrate primitive for the latest-element scalar
4714/// projection of the tagged-union closed-set-complement axis — the
4715/// `Option<Kind>`-valued REVERSED-walk peer of
4716/// [`assert_first_missing_kind_matches_missing_kinds`]'s
4717/// earliest-element projection under a negated `has` predicate. The
4718/// three sub-assertions swept per populated slot:
4719///
4720/// 1. **`last ↔ missing.last().copied()`**: `last_missing_kind() ==
4721///    missing_kinds().last().copied()` — a regression that overrode
4722///    `last_missing_kind` to walk `ALL` forward (defeating the
4723///    time-reversal), drop the negation (returning the populated
4724///    side's latest instead), or drift the walk from `ClosedSet::ALL`
4725///    surfaces here.
4726/// 2. **Single-slot diagonal**: `single_slot(k).last_missing_kind()`
4727///    equals the LATEST `ALL` entry not equal to `k` — a well-formed
4728///    parent's missing set is `ALL \ {k}` in canonical order, so its
4729///    latest element is `ALL[ALL.len()-1]` when `k != ALL[ALL.len()-1]`,
4730///    else `ALL[ALL.len()-2]`.
4731/// 3. **Emptiness composition law**: `last_missing_kind().is_some()
4732///    == (missing_kind_count() > 0)` — the latest-missing projection
4733///    agrees with the scalar complement cardinality. Non-trivial on
4734///    the single-slot arm when `ALL.len() > 1`.
4735///
4736/// A fifth sibling picks up the latest-missing check through ONE call
4737/// site.
4738///
4739/// Same `Lifetime` exclusion as the sibling primitives.
4740#[track_caller]
4741pub fn assert_last_missing_kind_matches_missing_kinds<T, F>(single_slot: F)
4742where
4743    T: TaggedUnion,
4744    T::Kind: PartialEq + std::fmt::Debug,
4745    F: Fn(T::Kind) -> T,
4746{
4747    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4748        .iter()
4749        .copied()
4750    {
4751        let parent = single_slot(populated);
4752        let last = parent.last_missing_kind();
4753        let via_missing = parent.missing_kinds().last().copied();
4754        // Composition law: latest-element projection agrees with the
4755        // widened primitive's `Vec::last().copied()`.
4756        assert_eq!(
4757            last, via_missing,
4758            "TaggedUnion::last_missing_kind() drifted from missing_kinds().last().copied() — populated={populated:?}",
4759        );
4760        // Single-slot diagonal — the missing set is ALL \ {populated}
4761        // in canonical order, so its latest element is the latest ALL
4762        // entry not equal to populated.
4763        let expected_last_missing = <T::Kind as tatara_closed_set::ClosedSet>::ALL
4764            .iter()
4765            .rev()
4766            .copied()
4767            .find(|k| *k != populated);
4768        assert_eq!(
4769            last, expected_last_missing,
4770            "TaggedUnion::last_missing_kind() on single_slot({populated:?}) must equal latest ClosedSet::ALL entry != {populated:?}",
4771        );
4772        // Emptiness composition law — the latest-missing projection
4773        // agrees with the scalar complement cardinality's positivity.
4774        assert_eq!(
4775            last.is_some(),
4776            parent.missing_kind_count() > 0,
4777            "last_missing_kind().is_some() drifted from (missing_kind_count() > 0) — populated={populated:?}",
4778        );
4779    }
4780}
4781
4782/// Generic exactly-one-populated-kind testkit — pins that
4783/// [`TaggedUnion::unique_populated_kind`] returns `Some(k)` iff exactly
4784/// one slot is populated (and names that slot's kind), and `None` on
4785/// every empty / ambiguous parent, across every
4786/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
4787/// arrangement.
4788///
4789/// Parent-axis substrate primitive for the exactly-one-hit scalar
4790/// projection of the tagged-union closed-set-inversion axis — the
4791/// `Option<Kind>`-valued exactly-one peer of
4792/// [`assert_first_populated_kind_matches_populated_kinds`] and
4793/// [`assert_last_populated_kind_matches_populated_kinds`]'s endpoint
4794/// projections. The four sub-assertions swept per populated slot:
4795///
4796/// 1. **`unique ↔ exactly-one on kinds`**: `unique_populated_kind() ==
4797///    Some(k)` iff `populated_kinds() == vec![k]` — a regression that
4798///    dropped the second-hit short-circuit (returning `Some(first)`
4799///    on a two-populated parent) fails on the sibling
4800///    two-populated pin above.
4801/// 2. **Single-slot diagonal**: `single_slot(k).unique_populated_kind()
4802///    == Some(k)` — the sole populated slot IS the unique populated
4803///    kind.
4804/// 3. **Cardinality composition law**:
4805///    `unique_populated_kind().is_some() == (populated_kind_count()
4806///    == 1)` — the exactly-one predicate agrees with the scalar
4807///    cardinality on every well-formed / empty / ambiguous arm.
4808/// 4. **Endpoint agreement on Some**: on the `Some` arm,
4809///    `unique_populated_kind() == first_populated_kind() ==
4810///    last_populated_kind()` — the three endpoint-projection
4811///    primitives coincide on the exactly-one arm and DIVERGE only on
4812///    the ambiguous arm.
4813///
4814/// A fifth sibling picks up the exactly-one-populated check through
4815/// ONE call site — no re-authored `count == 1` composition at the
4816/// test surface, no re-authored `single_slot(k).unique_populated_kind()
4817/// == Some(k)` diagonal pin, no re-authored endpoint-agreement
4818/// projection.
4819///
4820/// Same `Lifetime` exclusion as the sibling primitives.
4821#[track_caller]
4822pub fn assert_unique_populated_kind_matches_populated_kinds<T, F>(single_slot: F)
4823where
4824    T: TaggedUnion,
4825    T::Kind: PartialEq + std::fmt::Debug,
4826    F: Fn(T::Kind) -> T,
4827{
4828    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4829        .iter()
4830        .copied()
4831    {
4832        let parent = single_slot(populated);
4833        let unique = parent.unique_populated_kind();
4834        // Composition law: exactly-one predicate on the widened primitive.
4835        let kinds = parent.populated_kinds();
4836        let expected = if kinds.len() == 1 {
4837            Some(kinds[0])
4838        } else {
4839            None
4840        };
4841        assert_eq!(
4842            unique, expected,
4843            "TaggedUnion::unique_populated_kind() drifted from (populated_kinds().len() == 1 ? Some(kinds[0]) : None) — populated={populated:?}",
4844        );
4845        // Single-slot diagonal — a well-formed parent from single_slot
4846        // populates exactly the addressed slot, so the unique populated
4847        // kind IS that slot.
4848        assert_eq!(
4849            unique,
4850            Some(populated),
4851            "TaggedUnion::unique_populated_kind() on single_slot({populated:?}) must equal Some({populated:?}) exactly",
4852        );
4853        // Cardinality composition law — exactly-one predicate agrees
4854        // with the scalar cardinality's equality-to-one.
4855        assert_eq!(
4856            unique.is_some(),
4857            parent.populated_kind_count() == 1,
4858            "unique_populated_kind().is_some() drifted from (populated_kind_count() == 1) — populated={populated:?}",
4859        );
4860        // Endpoint-agreement — on the Some arm the three endpoint
4861        // projections coincide.
4862        if unique.is_some() {
4863            assert_eq!(
4864                unique,
4865                parent.first_populated_kind(),
4866                "unique_populated_kind() must equal first_populated_kind() on the Some arm — populated={populated:?}",
4867            );
4868            assert_eq!(
4869                unique,
4870                parent.last_populated_kind(),
4871                "unique_populated_kind() must equal last_populated_kind() on the Some arm — populated={populated:?}",
4872            );
4873        }
4874    }
4875}
4876
4877/// Generic exactly-one-missing-kind testkit — pins that
4878/// [`TaggedUnion::unique_missing_kind`] returns `Some(k)` iff exactly
4879/// one slot is missing (and names that slot's kind), and `None` on
4880/// every parent whose missing-set cardinality is not one, across
4881/// every [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-
4882/// slot arrangement.
4883///
4884/// Parent-axis substrate primitive for the exactly-one-hit scalar
4885/// projection of the tagged-union closed-set-COMPLEMENT axis under a
4886/// negated `has` predicate. The three sub-assertions swept per
4887/// populated slot (single-slot diagonal only — on any tagged union
4888/// with `ALL.len() > 2` the single-slot arrangement has ≥ 2 missing
4889/// slots, so the primitive returns `None`; the load-bearing `Some`
4890/// pins are the sibling near-saturation probes outside this
4891/// primitive):
4892///
4893/// 1. **`unique ↔ exactly-one on missing`**: `unique_missing_kind()
4894///    == Some(k)` iff `missing_kinds() == vec![k]` — a regression
4895///    that dropped the second-hit short-circuit (returning
4896///    `Some(first)` on a two-missing parent) fails here.
4897/// 2. **Cardinality composition law**:
4898///    `unique_missing_kind().is_some() == (missing_kind_count() ==
4899///    1)` — the exactly-one predicate agrees with the scalar
4900///    complement cardinality on every well-formed / empty / ambiguous
4901///    arm.
4902/// 3. **Endpoint agreement on Some**: on the `Some` arm,
4903///    `unique_missing_kind() == first_missing_kind() ==
4904///    last_missing_kind()` — the three endpoint-projection
4905///    primitives on the missing axis coincide when exactly one slot
4906///    is empty.
4907///
4908/// A fifth sibling picks up the exactly-one-missing check through
4909/// ONE call site.
4910///
4911/// Same `Lifetime` exclusion as the sibling primitives.
4912#[track_caller]
4913pub fn assert_unique_missing_kind_matches_missing_kinds<T, F>(single_slot: F)
4914where
4915    T: TaggedUnion,
4916    T::Kind: PartialEq + std::fmt::Debug,
4917    F: Fn(T::Kind) -> T,
4918{
4919    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
4920        .iter()
4921        .copied()
4922    {
4923        let parent = single_slot(populated);
4924        let unique = parent.unique_missing_kind();
4925        // Composition law: exactly-one predicate on the widened
4926        // primitive.
4927        let missing = parent.missing_kinds();
4928        let expected = if missing.len() == 1 {
4929            Some(missing[0])
4930        } else {
4931            None
4932        };
4933        assert_eq!(
4934            unique, expected,
4935            "TaggedUnion::unique_missing_kind() drifted from (missing_kinds().len() == 1 ? Some(missing[0]) : None) — populated={populated:?}",
4936        );
4937        // Cardinality composition law — exactly-one predicate agrees
4938        // with the scalar complement cardinality's equality-to-one.
4939        assert_eq!(
4940            unique.is_some(),
4941            parent.missing_kind_count() == 1,
4942            "unique_missing_kind().is_some() drifted from (missing_kind_count() == 1) — populated={populated:?}",
4943        );
4944        // Endpoint-agreement — on the Some arm the three endpoint
4945        // projections on the missing axis coincide.
4946        if unique.is_some() {
4947            assert_eq!(
4948                unique,
4949                parent.first_missing_kind(),
4950                "unique_missing_kind() must equal first_missing_kind() on the Some arm — populated={populated:?}",
4951            );
4952            assert_eq!(
4953                unique,
4954                parent.last_missing_kind(),
4955                "unique_missing_kind() must equal last_missing_kind() on the Some arm — populated={populated:?}",
4956            );
4957        }
4958    }
4959}
4960
4961/// Generic zero-populated-cardinality Boolean testkit — pins that
4962/// [`TaggedUnion::is_empty`] agrees with the scalar cardinality
4963/// primitive's equality-to-zero across every
4964/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
4965/// arrangement AND the empty-parent baseline.
4966///
4967/// Parent-axis substrate primitive for the Boolean cardinality-
4968/// endpoint scalar projection of the tagged-union closed-set-inversion
4969/// axis under a zero-arm equality — the `bool`-valued zero-endpoint
4970/// peer of [`assert_populated_kind_count_matches_populated_kinds`]'s
4971/// scalar cardinality projection. The three sub-assertions swept per
4972/// populated slot + the ONE baseline sub-assertion on the empty
4973/// parent:
4974///
4975/// 1. **Cardinality composition law**: `is_empty() ==
4976///    (populated_kind_count() == 0)` — the Boolean projection agrees
4977///    with the scalar cardinality's zero-arm equality on every empty /
4978///    well-formed / partial / saturated arm. Byte-identical to the
4979///    trait's default body, pinning it substrate-wide so a regression
4980///    that overrides `is_empty` to skip the sweep or return the wrong
4981///    Boolean fails here.
4982/// 2. **Widened-primitive agreement**: `is_empty() ==
4983///    populated_kinds().is_empty()` — the two zero-arm projections of
4984///    the populated cardinality (via `is_empty()` short-circuit walk
4985///    vs. via `populated_kinds()` Vec materialization then `.is_empty()`)
4986///    coincide byte-identically.
4987/// 3. **Single-slot diagonal**: `single_slot(k).is_empty() == false` —
4988///    a well-formed parent from `single_slot` populates exactly the
4989///    addressed slot, so it CANNOT be empty. Pins that the primitive
4990///    doesn't drift onto the populated side of the endpoint.
4991/// 4. **Empty-parent baseline** (swept once outside the per-`k` loop):
4992///    `T::empty(T::KIND_LIST).is_empty() == true` (via a constructed
4993///    all-`None` parent since [`TaggedUnionError::empty`] is on the
4994///    error carrier, not the parent factory — the parent-side empty
4995///    fixture is composed by the caller through `Default` on the
4996///    sibling scaffold). Pins the primitive's zero-arm — a regression
4997///    that inverted the negation surfaces here.
4998///
4999/// A fifth sibling tagged-union parent picks up the zero-cardinality-
5000/// Boolean check through ONE `impl TaggedUnion for X` block + ONE
5001/// per-site `single_slot_X` factory + ONE per-site `empty_X` factory,
5002/// plus ONE call site — no re-authored `is_empty` sweep at the test
5003/// surface.
5004///
5005/// Same `Lifetime` exclusion as the sibling primitives — see
5006/// [`assert_two_slots_ambiguous`].
5007///
5008/// # Theory grounding
5009///
5010/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
5011///   Boolean zero-endpoint projection binds through the SAME shape
5012///   the scalar cardinality binds through (a closed-set walk under
5013///   `Self::has`), differing only in the return-type collapse
5014///   (`bool` vs. `usize`) and the short-circuit gate (`!any` vs.
5015///   `count`).
5016/// - THEORY.md §VI.1 — generation over composition. A new
5017///   [`Self::Kind`] variant added to `ALL` reaches this primitive
5018///   mechanically through the `any` short-circuit at the trait's
5019///   default body.
5020#[track_caller]
5021pub fn assert_is_empty_matches_populated_kind_count<T, F, G>(single_slot: F, empty_parent: G)
5022where
5023    T: TaggedUnion,
5024    T::Kind: PartialEq + std::fmt::Debug,
5025    F: Fn(T::Kind) -> T,
5026    G: Fn() -> T,
5027{
5028    // Empty-parent baseline — the SOLE arm where `is_empty()` returns
5029    // `true`. The caller supplies the empty-parent fixture (an all-
5030    // `None` construction on the sibling scaffold's field structure).
5031    let empty = empty_parent();
5032    assert!(
5033        empty.is_empty(),
5034        "TaggedUnion::is_empty() on empty_parent() must equal true",
5035    );
5036    assert_eq!(
5037        empty.is_empty(),
5038        empty.populated_kind_count() == 0,
5039        "empty_parent().is_empty() drifted from (populated_kind_count() == 0)",
5040    );
5041    assert_eq!(
5042        empty.is_empty(),
5043        empty.populated_kinds().is_empty(),
5044        "empty_parent().is_empty() drifted from populated_kinds().is_empty()",
5045    );
5046
5047    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5048        .iter()
5049        .copied()
5050    {
5051        let parent = single_slot(populated);
5052        let is_empty = parent.is_empty();
5053        // Cardinality composition law — Boolean projection agrees with
5054        // the scalar cardinality's zero-arm equality.
5055        assert_eq!(
5056            is_empty,
5057            parent.populated_kind_count() == 0,
5058            "TaggedUnion::is_empty() drifted from (populated_kind_count() == 0) — populated={populated:?}",
5059        );
5060        // Widened-primitive agreement — the two zero-arm projections
5061        // of the populated cardinality coincide.
5062        assert_eq!(
5063            is_empty,
5064            parent.populated_kinds().is_empty(),
5065            "TaggedUnion::is_empty() drifted from populated_kinds().is_empty() — populated={populated:?}",
5066        );
5067        // Single-slot diagonal — a well-formed parent from single_slot
5068        // is NEVER empty.
5069        assert!(
5070            !is_empty,
5071            "TaggedUnion::is_empty() on single_slot({populated:?}) must equal false",
5072        );
5073    }
5074}
5075
5076/// Generic zero-missing-cardinality Boolean testkit — pins that
5077/// [`TaggedUnion::is_saturated`] agrees with the scalar complement
5078/// cardinality primitive's equality-to-zero across every
5079/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
5080/// arrangement AND the empty-parent baseline.
5081///
5082/// Parent-axis substrate primitive for the Boolean cardinality-
5083/// endpoint scalar projection of the tagged-union closed-set-COMPLEMENT
5084/// axis under a zero-arm equality — the `bool`-valued top-endpoint
5085/// peer of [`assert_missing_kind_count_matches_missing_kinds`]'s
5086/// scalar complement cardinality projection. The three sub-assertions
5087/// swept per populated slot + the ONE baseline sub-assertion on the
5088/// empty parent:
5089///
5090/// 1. **Cardinality composition law**: `is_saturated() ==
5091///    (missing_kind_count() == 0)` — the Boolean projection agrees
5092///    with the scalar complement cardinality's zero-arm equality on
5093///    every empty / well-formed / partial / saturated arm. Byte-
5094///    identical to the trait's default body, pinning it substrate-
5095///    wide so a regression that overrides `is_saturated` to skip the
5096///    sweep or return the wrong Boolean fails here.
5097/// 2. **Widened-primitive agreement**: `is_saturated() ==
5098///    missing_kinds().is_empty()` — the two zero-arm projections of
5099///    the missing cardinality (via `is_saturated()` short-circuit walk
5100///    vs. via `missing_kinds()` Vec materialization then
5101///    `.is_empty()`) coincide byte-identically.
5102/// 3. **Single-slot diagonal** (on `ALL.len() ≥ 2` closed sets):
5103///    `single_slot(k).is_saturated() == false` — a well-formed parent
5104///    from `single_slot` populates exactly one slot, leaving at least
5105///    one slot missing (`ALL.len() - 1 ≥ 1`), so it CANNOT be
5106///    saturated on any real-world tagged union in this workspace.
5107///    Pins that the primitive doesn't drift onto the missing-side
5108///    zero endpoint.
5109/// 4. **Empty-parent baseline** (swept once outside the per-`k` loop):
5110///    `empty_parent().is_saturated() == false` (empty has EVERY slot
5111///    missing, so `ALL.len() ≥ 1` missing, NEVER zero). Pins the
5112///    primitive's opposite-arm on the same fixture the empty-Boolean
5113///    peer pins its zero-arm.
5114///
5115/// A fifth sibling tagged-union parent picks up the zero-complement-
5116/// cardinality-Boolean check through ONE `impl TaggedUnion for X`
5117/// block + ONE per-site `single_slot_X` factory + ONE per-site
5118/// `empty_X` factory + ONE call site — no re-authored `is_saturated`
5119/// sweep at the test surface.
5120///
5121/// Same `Lifetime` exclusion as the sibling primitives.
5122///
5123/// # Theory grounding
5124///
5125/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
5126///   Boolean top-endpoint projection binds through the SAME shape
5127///   the scalar complement cardinality binds through (a closed-set
5128///   walk under `Self::has`), differing only in the return-type
5129///   collapse (`bool` vs. `usize`) and the short-circuit gate (`all`
5130///   vs. `count`).
5131/// - THEORY.md §VI.1 — generation over composition. A new
5132///   [`Self::Kind`] variant added to `ALL` reaches this primitive
5133///   mechanically through the `all` short-circuit at the trait's
5134///   default body.
5135#[track_caller]
5136pub fn assert_is_saturated_matches_missing_kind_count<T, F, G>(single_slot: F, empty_parent: G)
5137where
5138    T: TaggedUnion,
5139    T::Kind: PartialEq + std::fmt::Debug,
5140    F: Fn(T::Kind) -> T,
5141    G: Fn() -> T,
5142{
5143    // Empty-parent baseline — the empty parent has EVERY slot missing,
5144    // so `is_saturated()` returns `false` (the opposite endpoint of
5145    // where `is_empty()` returns `true`).
5146    let empty = empty_parent();
5147    assert!(
5148        !empty.is_saturated(),
5149        "TaggedUnion::is_saturated() on empty_parent() must equal false — every slot is missing",
5150    );
5151    assert_eq!(
5152        empty.is_saturated(),
5153        empty.missing_kind_count() == 0,
5154        "empty_parent().is_saturated() drifted from (missing_kind_count() == 0)",
5155    );
5156    assert_eq!(
5157        empty.is_saturated(),
5158        empty.missing_kinds().is_empty(),
5159        "empty_parent().is_saturated() drifted from missing_kinds().is_empty()",
5160    );
5161
5162    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5163        .iter()
5164        .copied()
5165    {
5166        let parent = single_slot(populated);
5167        let is_saturated = parent.is_saturated();
5168        // Cardinality composition law — Boolean projection agrees with
5169        // the scalar complement cardinality's zero-arm equality.
5170        assert_eq!(
5171            is_saturated,
5172            parent.missing_kind_count() == 0,
5173            "TaggedUnion::is_saturated() drifted from (missing_kind_count() == 0) — populated={populated:?}",
5174        );
5175        // Widened-primitive agreement — the two zero-arm projections
5176        // of the missing cardinality coincide.
5177        assert_eq!(
5178            is_saturated,
5179            parent.missing_kinds().is_empty(),
5180            "TaggedUnion::is_saturated() drifted from missing_kinds().is_empty() — populated={populated:?}",
5181        );
5182        // Single-slot diagonal (on any `ALL.len() ≥ 2` closed set) — a
5183        // well-formed parent leaves `ALL.len() - 1 ≥ 1` missing, so it
5184        // CANNOT be saturated. This holds for every production tagged
5185        // union in the workspace (all have `ALL.len() ≥ 2`).
5186        assert!(
5187            !is_saturated,
5188            "TaggedUnion::is_saturated() on single_slot({populated:?}) must equal false — ALL.len() >= 2",
5189        );
5190    }
5191}
5192
5193/// Generic at-least-one-populated-cardinality Boolean testkit — pins
5194/// that [`TaggedUnion::has_any_populated_kind`] agrees with its
5195/// definitional complement [`TaggedUnion::is_empty`] AND with the
5196/// scalar cardinality primitive's strict-inequality-to-zero across
5197/// every [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-
5198/// slot arrangement AND the empty-parent baseline.
5199///
5200/// Parent-axis substrate primitive for the Boolean at-least-one
5201/// halfspace projection on the tagged-union closed-set-inversion axis
5202/// — the `bool`-valued definitional complement of
5203/// [`assert_is_empty_matches_populated_kind_count`]'s zero-endpoint
5204/// Boolean projection, and the SUBSET peer of the zero-arm Boolean on
5205/// the populated cardinality lattice. The four sub-assertions swept
5206/// per populated slot + the ONE baseline sub-assertion on the empty
5207/// parent:
5208///
5209/// 1. **Definitional complement law**: `has_any_populated_kind() ==
5210///    !is_empty()` — the SUBSET Boolean is the bit-flip of the
5211///    zero-endpoint Boolean on every empty / well-formed / partial /
5212///    saturated arm. Byte-identical to the trait's default body
5213///    (both walk `<Self::Kind as ClosedSet>::ALL.iter().any(has)`,
5214///    the endpoint arm negates the whole expression), pinning the
5215///    pair substrate-wide so a regression that overrides
5216///    `has_any_populated_kind` to skip the sweep or drift off the
5217///    complement law surfaces here.
5218/// 2. **Cardinality composition law**: `has_any_populated_kind() ==
5219///    (populated_kind_count() > 0)` — the ≥ 1 halfspace agrees with
5220///    the scalar cardinality's strict-inequality-to-zero on every arm.
5221/// 3. **Widened-primitive agreement**: `has_any_populated_kind() ==
5222///    !populated_kinds().is_empty()` — the two at-least-one
5223///    projections of the populated cardinality (via
5224///    `has_any_populated_kind()` short-circuit walk vs. via
5225///    `populated_kinds()` `Vec` materialization then `!is_empty()`)
5226///    coincide byte-identically.
5227/// 4. **Single-slot diagonal**: `single_slot(k).has_any_populated_kind()
5228///    == true` — a well-formed parent from `single_slot` populates
5229///    exactly one slot, so the ≥ 1 halfspace returns `true`. Pins
5230///    that the primitive doesn't drift off the well-formed arm.
5231/// 5. **Empty-parent baseline** (swept once outside the per-`k` loop):
5232///    `empty_parent().has_any_populated_kind() == false` (empty has
5233///    zero populated). Pins the primitive's opposite arm on the same
5234///    fixture the zero-endpoint peer pins its zero-arm — the only arm
5235///    where the ≥ 1 halfspace returns `false`.
5236///
5237/// A fifth sibling tagged-union parent picks up the at-least-one-
5238/// populated-cardinality-Boolean check through ONE `impl TaggedUnion
5239/// for X` block + ONE per-site `single_slot_X` factory + ONE per-site
5240/// `empty_X` factory + ONE call site — no re-authored
5241/// `has_any_populated_kind` sweep at the test surface.
5242///
5243/// Same `Lifetime` exclusion as the sibling primitives — see
5244/// [`assert_two_slots_ambiguous`].
5245///
5246/// # Theory grounding
5247///
5248/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
5249///   Boolean at-least-one halfspace projection binds through the SAME
5250///   shape [`assert_is_empty_matches_populated_kind_count`] binds
5251///   through (a closed-set `any` walk under `Self::has`), differing
5252///   only in the final negation the zero-endpoint applies — pinned as
5253///   the definitional-complement law at ONE substrate site inside the
5254///   testkit's per-arm sweep.
5255/// - THEORY.md §VI.1 — generation over composition. A new
5256///   [`Self::Kind`] variant added to `ALL` reaches this primitive
5257///   mechanically through the `any` short-circuit at the trait's
5258///   default body.
5259#[track_caller]
5260pub fn assert_has_any_populated_kind_matches_populated_kind_count<T, F, G>(
5261    single_slot: F,
5262    empty_parent: G,
5263) where
5264    T: TaggedUnion,
5265    T::Kind: PartialEq + std::fmt::Debug,
5266    F: Fn(T::Kind) -> T,
5267    G: Fn() -> T,
5268{
5269    // Empty-parent baseline — the SOLE arm where
5270    // `has_any_populated_kind()` returns `false`. The definitional
5271    // complement law binds this to `is_empty() == true`.
5272    let empty = empty_parent();
5273    assert!(
5274        !empty.has_any_populated_kind(),
5275        "TaggedUnion::has_any_populated_kind() on empty_parent() must equal false",
5276    );
5277    assert_eq!(
5278        empty.has_any_populated_kind(),
5279        !empty.is_empty(),
5280        "empty_parent().has_any_populated_kind() drifted from !is_empty()",
5281    );
5282    assert_eq!(
5283        empty.has_any_populated_kind(),
5284        empty.populated_kind_count() > 0,
5285        "empty_parent().has_any_populated_kind() drifted from (populated_kind_count() > 0)",
5286    );
5287    assert_eq!(
5288        empty.has_any_populated_kind(),
5289        !empty.populated_kinds().is_empty(),
5290        "empty_parent().has_any_populated_kind() drifted from !populated_kinds().is_empty()",
5291    );
5292
5293    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5294        .iter()
5295        .copied()
5296    {
5297        let parent = single_slot(populated);
5298        let has_any = parent.has_any_populated_kind();
5299        // Definitional complement law — SUBSET Boolean is the bit-flip
5300        // of the zero-endpoint Boolean.
5301        assert_eq!(
5302            has_any,
5303            !parent.is_empty(),
5304            "TaggedUnion::has_any_populated_kind() drifted from !is_empty() — populated={populated:?}",
5305        );
5306        // Cardinality composition law — ≥ 1 halfspace agrees with
5307        // scalar cardinality's strict-inequality-to-zero.
5308        assert_eq!(
5309            has_any,
5310            parent.populated_kind_count() > 0,
5311            "TaggedUnion::has_any_populated_kind() drifted from (populated_kind_count() > 0) — populated={populated:?}",
5312        );
5313        // Widened-primitive agreement — the two at-least-one projections
5314        // of the populated cardinality coincide.
5315        assert_eq!(
5316            has_any,
5317            !parent.populated_kinds().is_empty(),
5318            "TaggedUnion::has_any_populated_kind() drifted from !populated_kinds().is_empty() — populated={populated:?}",
5319        );
5320        // Single-slot diagonal — a well-formed parent from single_slot
5321        // is ALWAYS at least one populated.
5322        assert!(
5323            has_any,
5324            "TaggedUnion::has_any_populated_kind() on single_slot({populated:?}) must equal true",
5325        );
5326    }
5327}
5328
5329/// Generic at-least-one-missing-cardinality Boolean testkit — pins
5330/// that [`TaggedUnion::has_any_missing_kind`] agrees with its
5331/// definitional complement [`TaggedUnion::is_saturated`] AND with the
5332/// scalar complement cardinality primitive's strict-inequality-to-zero
5333/// across every [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
5334/// single-slot arrangement AND the empty-parent baseline.
5335///
5336/// Parent-axis substrate primitive for the Boolean at-least-one
5337/// halfspace projection on the tagged-union closed-set-COMPLEMENT axis
5338/// — the `bool`-valued definitional complement of
5339/// [`assert_is_saturated_matches_missing_kind_count`]'s zero-endpoint
5340/// Boolean projection, and the SUBSET peer of the zero-arm Boolean on
5341/// the missing cardinality lattice. Byte-for-byte symmetrical with
5342/// [`assert_has_any_populated_kind_matches_populated_kind_count`]
5343/// under the (populated, missing) complement axis.
5344///
5345/// The four sub-assertions swept per populated slot + the ONE baseline
5346/// sub-assertion on the empty parent:
5347///
5348/// 1. **Definitional complement law**: `has_any_missing_kind() ==
5349///    !is_saturated()` — the SUBSET Boolean is the bit-flip of the
5350///    zero-endpoint Boolean on every arm. Byte-identical to the trait's
5351///    default body (via De Morgan: `any(|k| !has(k)) == !all(|k|
5352///    has(k))`), pinning the pair substrate-wide.
5353/// 2. **Cardinality composition law**: `has_any_missing_kind() ==
5354///    (missing_kind_count() > 0)` — the ≥ 1 halfspace agrees with the
5355///    scalar complement cardinality's strict-inequality-to-zero on
5356///    every arm.
5357/// 3. **Widened-primitive agreement**: `has_any_missing_kind() ==
5358///    !missing_kinds().is_empty()` — the two at-least-one projections
5359///    of the missing cardinality coincide byte-identically.
5360/// 4. **Single-slot diagonal** (on `ALL.len() ≥ 2` closed sets):
5361///    `single_slot(k).has_any_missing_kind() == true` — a well-formed
5362///    parent from `single_slot` populates exactly one slot, leaving at
5363///    least one slot missing (`ALL.len() - 1 ≥ 1`), so the ≥ 1 missing
5364///    halfspace returns `true` on every real-world tagged union in
5365///    this workspace.
5366/// 5. **Empty-parent baseline** (swept once outside the per-`k` loop):
5367///    `empty_parent().has_any_missing_kind() == true` (empty has EVERY
5368///    slot missing on any `N ≥ 1`, so ≥ 1 missing). Pins the
5369///    primitive's non-saturated arm on the same fixture the zero-
5370///    endpoint peer pins its opposite arm.
5371///
5372/// Same `Lifetime` exclusion as the sibling primitives.
5373///
5374/// # Theory grounding
5375///
5376/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
5377///   Boolean at-least-one halfspace projection on the missing axis
5378///   binds through the SAME shape
5379///   [`assert_is_saturated_matches_missing_kind_count`] binds through
5380///   (a closed-set walk under `Self::has`), pinned as the
5381///   definitional-complement law at ONE substrate site inside the
5382///   testkit's per-arm sweep — the trait's default body composes
5383///   `any(|k| !has(k))` which is De-Morgan-equivalent to
5384///   `!all(|k| has(k))`, the exact expression `is_saturated()`
5385///   negates.
5386/// - THEORY.md §VI.1 — generation over composition. A new
5387///   [`Self::Kind`] variant added to `ALL` reaches this primitive
5388///   mechanically through the `any` short-circuit at the trait's
5389///   default body.
5390#[track_caller]
5391pub fn assert_has_any_missing_kind_matches_missing_kind_count<T, F, G>(
5392    single_slot: F,
5393    empty_parent: G,
5394) where
5395    T: TaggedUnion,
5396    T::Kind: PartialEq + std::fmt::Debug,
5397    F: Fn(T::Kind) -> T,
5398    G: Fn() -> T,
5399{
5400    // Empty-parent baseline — the empty parent has EVERY slot missing,
5401    // so `has_any_missing_kind()` returns `true` (the opposite endpoint
5402    // of where `is_saturated()` returns `true`).
5403    let empty = empty_parent();
5404    assert!(
5405        empty.has_any_missing_kind(),
5406        "TaggedUnion::has_any_missing_kind() on empty_parent() must equal true — every slot is missing",
5407    );
5408    assert_eq!(
5409        empty.has_any_missing_kind(),
5410        !empty.is_saturated(),
5411        "empty_parent().has_any_missing_kind() drifted from !is_saturated()",
5412    );
5413    assert_eq!(
5414        empty.has_any_missing_kind(),
5415        empty.missing_kind_count() > 0,
5416        "empty_parent().has_any_missing_kind() drifted from (missing_kind_count() > 0)",
5417    );
5418    assert_eq!(
5419        empty.has_any_missing_kind(),
5420        !empty.missing_kinds().is_empty(),
5421        "empty_parent().has_any_missing_kind() drifted from !missing_kinds().is_empty()",
5422    );
5423
5424    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5425        .iter()
5426        .copied()
5427    {
5428        let parent = single_slot(populated);
5429        let has_any = parent.has_any_missing_kind();
5430        // Definitional complement law — SUBSET Boolean is the bit-flip
5431        // of the zero-endpoint Boolean.
5432        assert_eq!(
5433            has_any,
5434            !parent.is_saturated(),
5435            "TaggedUnion::has_any_missing_kind() drifted from !is_saturated() — populated={populated:?}",
5436        );
5437        // Cardinality composition law — ≥ 1 halfspace agrees with
5438        // scalar complement cardinality's strict-inequality-to-zero.
5439        assert_eq!(
5440            has_any,
5441            parent.missing_kind_count() > 0,
5442            "TaggedUnion::has_any_missing_kind() drifted from (missing_kind_count() > 0) — populated={populated:?}",
5443        );
5444        // Widened-primitive agreement — the two at-least-one projections
5445        // of the missing cardinality coincide.
5446        assert_eq!(
5447            has_any,
5448            !parent.missing_kinds().is_empty(),
5449            "TaggedUnion::has_any_missing_kind() drifted from !missing_kinds().is_empty() — populated={populated:?}",
5450        );
5451        // Single-slot diagonal (on any `ALL.len() ≥ 2` closed set) — a
5452        // well-formed parent leaves `ALL.len() - 1 ≥ 1` missing, so
5453        // ≥ 1 missing halfspace holds. Every production tagged union
5454        // in the workspace has `ALL.len() ≥ 2`.
5455        assert!(
5456            has_any,
5457            "TaggedUnion::has_any_missing_kind() on single_slot({populated:?}) must equal true — ALL.len() >= 2",
5458        );
5459    }
5460}
5461
5462/// Generic one-populated-cardinality Boolean testkit — pins that
5463/// [`TaggedUnion::has_unique_populated_kind`] agrees with the scalar
5464/// cardinality primitive's equality-to-one across every
5465/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
5466/// arrangement AND the empty-parent baseline.
5467///
5468/// Parent-axis substrate primitive for the Boolean cardinality-mid-
5469/// endpoint scalar projection of the tagged-union closed-set-inversion
5470/// axis under a one-arm equality — the `bool`-valued one-endpoint peer
5471/// of [`assert_populated_kind_count_matches_populated_kinds`]'s scalar
5472/// cardinality projection. Together with [`assert_is_empty_matches_populated_kind_count`]
5473/// and [`assert_is_saturated_matches_missing_kind_count`] this closes
5474/// the substrate's 2×2 Boolean-endpoint sweep on the tagged-union
5475/// parent axis. The three sub-assertions swept per populated slot +
5476/// the ONE baseline sub-assertion on the empty parent:
5477///
5478/// 1. **Cardinality composition law**: `has_unique_populated_kind() ==
5479///    (populated_kind_count() == 1)` — the Boolean projection agrees
5480///    with the scalar cardinality's one-arm equality on every empty /
5481///    well-formed / partial / saturated arm. Byte-identical to the
5482///    trait's default body composed with `unique_populated_kind`,
5483///    pinning it substrate-wide so a regression that overrides
5484///    `has_unique_populated_kind` to skip the sweep or return the
5485///    wrong Boolean fails here.
5486/// 2. **Unique-primitive agreement**: `has_unique_populated_kind() ==
5487///    unique_populated_kind().is_some()` — the trait's default body,
5488///    pinned explicitly so a regression on the `unique_*` primitive
5489///    or on the Boolean projection's `is_some` collapse surfaces at
5490///    ONE assertion.
5491/// 3. **Single-slot diagonal**: `single_slot(k).has_unique_populated_kind()
5492///    == true` — a well-formed parent from `single_slot` populates
5493///    exactly one slot, so the one-arm Boolean returns `true`. Pins
5494///    that the primitive doesn't drift off the well-formed arm.
5495/// 4. **Empty-parent baseline** (swept once outside the per-`k` loop):
5496///    `empty_parent().has_unique_populated_kind() == false` (zero
5497///    populated, not one). Pins the primitive's opposite-arm on the
5498///    same fixture the zero-endpoint peer pins its zero-arm.
5499///
5500/// A fifth sibling tagged-union parent picks up the one-cardinality-
5501/// Boolean check through ONE `impl TaggedUnion for X` block plus ONE
5502/// per-site `single_slot_X` factory plus ONE per-site `empty_X` factory
5503/// plus ONE call site — no re-authored `has_unique_populated_kind`
5504/// sweep at the test surface.
5505///
5506/// Same `Lifetime` exclusion as the sibling primitives — see
5507/// [`assert_two_slots_ambiguous`].
5508///
5509/// # Theory grounding
5510///
5511/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
5512///   Boolean one-endpoint projection binds through the SAME shape
5513///   the scalar cardinality binds through (a closed-set walk under
5514///   `Self::has` composed with a two-step short-circuit), differing
5515///   only in the return-type collapse (`bool` vs. `usize`) and the
5516///   equality gate (`is_some` vs. `== 1`).
5517/// - THEORY.md §VI.1 — generation over composition. A new
5518///   [`Self::Kind`] variant added to `ALL` reaches this primitive
5519///   mechanically through the `unique_populated_kind` two-step short-
5520///   circuit at the trait's default body.
5521#[track_caller]
5522pub fn assert_has_unique_populated_kind_matches_populated_kind_count<T, F, G>(
5523    single_slot: F,
5524    empty_parent: G,
5525) where
5526    T: TaggedUnion,
5527    T::Kind: PartialEq + std::fmt::Debug,
5528    F: Fn(T::Kind) -> T,
5529    G: Fn() -> T,
5530{
5531    // Empty-parent baseline — the empty parent has ZERO populated
5532    // slots, so `has_unique_populated_kind()` returns `false` (the
5533    // opposite endpoint of where a single-slot parent returns `true`).
5534    let empty = empty_parent();
5535    assert!(
5536        !empty.has_unique_populated_kind(),
5537        "TaggedUnion::has_unique_populated_kind() on empty_parent() must equal false",
5538    );
5539    assert_eq!(
5540        empty.has_unique_populated_kind(),
5541        empty.populated_kind_count() == 1,
5542        "empty_parent().has_unique_populated_kind() drifted from (populated_kind_count() == 1)",
5543    );
5544    assert_eq!(
5545        empty.has_unique_populated_kind(),
5546        empty.unique_populated_kind().is_some(),
5547        "empty_parent().has_unique_populated_kind() drifted from unique_populated_kind().is_some()",
5548    );
5549
5550    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5551        .iter()
5552        .copied()
5553    {
5554        let parent = single_slot(populated);
5555        let has_unique = parent.has_unique_populated_kind();
5556        // Cardinality composition law — Boolean projection agrees with
5557        // the scalar cardinality's one-arm equality.
5558        assert_eq!(
5559            has_unique,
5560            parent.populated_kind_count() == 1,
5561            "TaggedUnion::has_unique_populated_kind() drifted from (populated_kind_count() == 1) — populated={populated:?}",
5562        );
5563        // Unique-primitive agreement — the Boolean is the `is_some`
5564        // projection of the Option-valued unique primitive.
5565        assert_eq!(
5566            has_unique,
5567            parent.unique_populated_kind().is_some(),
5568            "TaggedUnion::has_unique_populated_kind() drifted from unique_populated_kind().is_some() — populated={populated:?}",
5569        );
5570        // Single-slot diagonal — a well-formed parent from single_slot
5571        // has exactly one populated slot, so the one-arm Boolean is
5572        // `true`.
5573        assert!(
5574            has_unique,
5575            "TaggedUnion::has_unique_populated_kind() on single_slot({populated:?}) must equal true",
5576        );
5577    }
5578}
5579
5580/// Generic one-missing-cardinality Boolean testkit — pins that
5581/// [`TaggedUnion::has_unique_missing_kind`] agrees with the scalar
5582/// complement cardinality primitive's equality-to-one across every
5583/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
5584/// arrangement AND the empty-parent baseline.
5585///
5586/// Parent-axis substrate primitive for the Boolean cardinality-mid-
5587/// endpoint scalar projection of the tagged-union closed-set-COMPLEMENT
5588/// axis under a one-arm equality — the `bool`-valued one-endpoint peer
5589/// of [`assert_missing_kind_count_matches_missing_kinds`]'s scalar
5590/// complement cardinality projection. Byte-for-byte symmetrical with
5591/// [`assert_has_unique_populated_kind_matches_populated_kind_count`]
5592/// under the (populated, missing) complement axis. The three
5593/// sub-assertions swept per populated slot + the baseline sub-assertion
5594/// on the empty parent:
5595///
5596/// 1. **Cardinality composition law**: `has_unique_missing_kind() ==
5597///    (missing_kind_count() == 1)` — the Boolean projection agrees
5598///    with the scalar complement cardinality's one-arm equality on
5599///    every empty / well-formed / partial / saturated arm.
5600/// 2. **Unique-primitive agreement**: `has_unique_missing_kind() ==
5601///    unique_missing_kind().is_some()` — the trait's default body,
5602///    pinned explicitly.
5603/// 3. **Single-slot diagonal on `ALL.len() ≥ 3` closed sets**:
5604///    `single_slot(k).has_unique_missing_kind() == false` — a well-
5605///    formed parent leaves `ALL.len() - 1 ≥ 2` missing on any
5606///    `ALL.len() ≥ 3` closed set, so the one-arm Boolean returns
5607///    `false`. On the degenerate `ALL.len() == 2` closed set (e.g.
5608///    `Lifetime`, which this testkit excludes through the `TaggedUnion`
5609///    bound) well-formed and one-missing coincide; on every
5610///    production tagged union in the workspace (`ALL.len() ≥ 3`) the
5611///    diagonal returns `false`.
5612/// 4. **Empty-parent baseline**: `empty_parent().has_unique_missing_kind()
5613///    == false` (empty has EVERY slot missing, `ALL.len() ≥ 2` on
5614///    every production union, so never exactly one).
5615///
5616/// A fifth sibling tagged-union parent picks up the one-complement-
5617/// cardinality-Boolean check through ONE `impl TaggedUnion for X`
5618/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
5619/// `empty_X` factory plus ONE call site — no re-authored
5620/// `has_unique_missing_kind` sweep at the test surface.
5621///
5622/// Same `Lifetime` exclusion as the sibling primitives.
5623///
5624/// # Theory grounding
5625///
5626/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
5627/// - THEORY.md §VI.1 — generation over composition.
5628#[track_caller]
5629pub fn assert_has_unique_missing_kind_matches_missing_kind_count<T, F, G>(
5630    single_slot: F,
5631    empty_parent: G,
5632) where
5633    T: TaggedUnion,
5634    T::Kind: PartialEq + std::fmt::Debug,
5635    F: Fn(T::Kind) -> T,
5636    G: Fn() -> T,
5637{
5638    // Empty-parent baseline — the empty parent has ALL.len() missing
5639    // slots, so `has_unique_missing_kind()` returns `false` on any
5640    // ALL.len() >= 2 closed set (every production union).
5641    let empty = empty_parent();
5642    assert!(
5643        !empty.has_unique_missing_kind(),
5644        "TaggedUnion::has_unique_missing_kind() on empty_parent() must equal false — ALL.len() >= 2 missing",
5645    );
5646    assert_eq!(
5647        empty.has_unique_missing_kind(),
5648        empty.missing_kind_count() == 1,
5649        "empty_parent().has_unique_missing_kind() drifted from (missing_kind_count() == 1)",
5650    );
5651    assert_eq!(
5652        empty.has_unique_missing_kind(),
5653        empty.unique_missing_kind().is_some(),
5654        "empty_parent().has_unique_missing_kind() drifted from unique_missing_kind().is_some()",
5655    );
5656
5657    let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
5658    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5659        .iter()
5660        .copied()
5661    {
5662        let parent = single_slot(populated);
5663        let has_unique = parent.has_unique_missing_kind();
5664        // Cardinality composition law — Boolean projection agrees with
5665        // the scalar complement cardinality's one-arm equality.
5666        assert_eq!(
5667            has_unique,
5668            parent.missing_kind_count() == 1,
5669            "TaggedUnion::has_unique_missing_kind() drifted from (missing_kind_count() == 1) — populated={populated:?}",
5670        );
5671        // Unique-primitive agreement — the Boolean is the `is_some`
5672        // projection of the Option-valued unique primitive.
5673        assert_eq!(
5674            has_unique,
5675            parent.unique_missing_kind().is_some(),
5676            "TaggedUnion::has_unique_missing_kind() drifted from unique_missing_kind().is_some() — populated={populated:?}",
5677        );
5678        // Single-slot diagonal — a well-formed parent has ALL.len() - 1
5679        // missing slots. On ALL.len() == 2 the diagonal returns `true`
5680        // (2 - 1 == 1); on ALL.len() >= 3 it returns `false`.
5681        let expected_diagonal = all_len == 2;
5682        assert_eq!(
5683            has_unique,
5684            expected_diagonal,
5685            "TaggedUnion::has_unique_missing_kind() on single_slot({populated:?}) must equal {expected_diagonal} (ALL.len() == {all_len} → missing == {})",
5686            all_len - 1,
5687        );
5688    }
5689}
5690
5691/// Generic ≥2-populated-cardinality Boolean testkit — pins that
5692/// [`TaggedUnion::has_multiple_populated_kinds`] agrees with the
5693/// scalar cardinality primitive's `>= 2` inequality across every
5694/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
5695/// arrangement, every off-diagonal two-slot pair, AND the empty-
5696/// parent baseline.
5697///
5698/// Parent-axis substrate primitive for the Boolean cardinality many-
5699/// arm scalar projection of the tagged-union closed-set-inversion
5700/// axis under a `>= 2` inequality — third arm of the {0, 1, ≥2}
5701/// cardinality trichotomy on the populated axis, byte-for-byte peer
5702/// of [`assert_is_empty_matches_populated_kind_count`] (zero-arm) and
5703/// [`assert_has_unique_populated_kind_matches_populated_kind_count`]
5704/// (one-arm). The primitives partition every tagged-union state — on
5705/// any parent EXACTLY ONE of `is_empty()`,
5706/// `has_unique_populated_kind()`, `has_multiple_populated_kinds()`
5707/// returns `true`, closing the trichotomy at the trait's default
5708/// bodies. The four sub-assertions swept per populated slot + the
5709/// baseline sub-assertions + the two-slot sweep:
5710///
5711/// 1. **Cardinality composition law**: `has_multiple_populated_kinds()
5712///    == (populated_kind_count() >= 2)` on every empty / well-formed
5713///    / two-slot / saturated arm.
5714/// 2. **Trichotomy partition law**: EXACTLY ONE of `is_empty()`,
5715///    `has_unique_populated_kind()`, `has_multiple_populated_kinds()`
5716///    returns `true` on every arm swept — pinned as
5717///    `usize::from(is_empty()) + usize::from(has_unique_populated_kind())
5718///    + usize::from(has_multiple_populated_kinds()) == 1`.
5719/// 3. **Empty-parent baseline**: `empty_parent().has_multiple_populated_kinds()
5720///    == false` (zero populated, not many).
5721/// 4. **Single-slot diagonal**:
5722///    `single_slot(k).has_multiple_populated_kinds() == false` on
5723///    every `k` in `ClosedSet::ALL` (one populated, not many).
5724/// 5. **Two-slot diagonal**: for every off-diagonal `(a, b)` pair,
5725///    `two_slot(a, b).has_multiple_populated_kinds() == true` (two
5726///    populated, definitively many).
5727///
5728/// A fifth sibling tagged-union parent picks up the many-cardinality
5729/// Boolean check through ONE `impl TaggedUnion for X` block plus ONE
5730/// per-site `single_slot_X` factory plus ONE per-site `two_slot_X`
5731/// factory plus ONE per-site `empty_X` factory plus ONE call site.
5732///
5733/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
5734/// primitives — `Lifetime` doesn't impl [`TaggedUnion`].
5735///
5736/// # Theory grounding
5737///
5738/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
5739/// - THEORY.md §VI.1 — generation over composition.
5740#[track_caller]
5741pub fn assert_has_multiple_populated_kinds_matches_populated_kind_count<T, F, G, H>(
5742    single_slot: F,
5743    two_slot: G,
5744    empty_parent: H,
5745) where
5746    T: TaggedUnion,
5747    T::Kind: PartialEq + std::fmt::Debug,
5748    F: Fn(T::Kind) -> T,
5749    G: Fn(T::Kind, T::Kind) -> T,
5750    H: Fn() -> T,
5751{
5752    // Empty-parent baseline — zero populated slots, so
5753    // `has_multiple_populated_kinds()` returns `false`.
5754    let empty = empty_parent();
5755    assert!(
5756        !empty.has_multiple_populated_kinds(),
5757        "TaggedUnion::has_multiple_populated_kinds() on empty_parent() must equal false",
5758    );
5759    assert_eq!(
5760        empty.has_multiple_populated_kinds(),
5761        empty.populated_kind_count() >= 2,
5762        "empty_parent().has_multiple_populated_kinds() drifted from (populated_kind_count() >= 2)",
5763    );
5764    // Trichotomy partition on the empty arm — is_empty is true, the
5765    // other two are false.
5766    assert_eq!(
5767        usize::from(empty.is_empty())
5768            + usize::from(empty.has_unique_populated_kind())
5769            + usize::from(empty.has_multiple_populated_kinds()),
5770        1,
5771        "empty_parent() must satisfy EXACTLY ONE of is_empty / has_unique_populated_kind / has_multiple_populated_kinds",
5772    );
5773
5774    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5775        .iter()
5776        .copied()
5777    {
5778        let parent = single_slot(populated);
5779        let has_multiple = parent.has_multiple_populated_kinds();
5780        // Cardinality composition law.
5781        assert_eq!(
5782            has_multiple,
5783            parent.populated_kind_count() >= 2,
5784            "TaggedUnion::has_multiple_populated_kinds() drifted from (populated_kind_count() >= 2) — populated={populated:?}",
5785        );
5786        // Single-slot diagonal — one populated, not many.
5787        assert!(
5788            !has_multiple,
5789            "TaggedUnion::has_multiple_populated_kinds() on single_slot({populated:?}) must equal false",
5790        );
5791        // Trichotomy partition on the well-formed arm —
5792        // has_unique_populated_kind is true, the other two are false.
5793        assert_eq!(
5794            usize::from(parent.is_empty())
5795                + usize::from(parent.has_unique_populated_kind())
5796                + usize::from(has_multiple),
5797            1,
5798            "single_slot({populated:?}) must satisfy EXACTLY ONE of is_empty / has_unique_populated_kind / has_multiple_populated_kinds",
5799        );
5800    }
5801
5802    // Two-slot sweep — every off-diagonal pair has ≥ 2 populated.
5803    for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5804        .iter()
5805        .copied()
5806    {
5807        for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5808            .iter()
5809            .copied()
5810        {
5811            if a == b {
5812                continue;
5813            }
5814            let parent = two_slot(a, b);
5815            let has_multiple = parent.has_multiple_populated_kinds();
5816            assert!(
5817                has_multiple,
5818                "TaggedUnion::has_multiple_populated_kinds() on two_slot({a:?}, {b:?}) must equal true",
5819            );
5820            assert_eq!(
5821                has_multiple,
5822                parent.populated_kind_count() >= 2,
5823                "TaggedUnion::has_multiple_populated_kinds() drifted from (populated_kind_count() >= 2) — pair=({a:?}, {b:?})",
5824            );
5825            // Trichotomy partition on the two-slot arm —
5826            // has_multiple_populated_kinds is true, the other two
5827            // are false.
5828            assert_eq!(
5829                usize::from(parent.is_empty())
5830                    + usize::from(parent.has_unique_populated_kind())
5831                    + usize::from(has_multiple),
5832                1,
5833                "two_slot({a:?}, {b:?}) must satisfy EXACTLY ONE of is_empty / has_unique_populated_kind / has_multiple_populated_kinds",
5834            );
5835        }
5836    }
5837}
5838
5839/// Generic ≥2-missing-cardinality Boolean testkit — pins that
5840/// [`TaggedUnion::has_multiple_missing_kinds`] agrees with the scalar
5841/// complement cardinality primitive's `>= 2` inequality across every
5842/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
5843/// arrangement, every off-diagonal two-slot pair, AND the empty-
5844/// parent baseline.
5845///
5846/// Byte-for-byte peer of
5847/// [`assert_has_multiple_populated_kinds_matches_populated_kind_count`]
5848/// under the (populated, missing) complement axis. Third arm of the
5849/// {0, 1, ≥2} cardinality trichotomy on the missing axis, closing the
5850/// natural partition alongside
5851/// [`assert_is_saturated_matches_missing_kind_count`] (zero-arm) and
5852/// [`assert_has_unique_missing_kind_matches_missing_kind_count`]
5853/// (one-arm). Same trichotomy partition law:
5854/// `is_saturated() + has_unique_missing_kind() +
5855/// has_multiple_missing_kinds() == 1` on every arm.
5856///
5857/// The single-slot diagonal expectation depends on `ALL.len()`:
5858///
5859/// - `ALL.len() == 2`: well-formed has 1 missing, so
5860///   `has_multiple_missing_kinds() == false` (production `Lifetime`
5861///   is excluded via the `TaggedUnion` bound anyway).
5862/// - `ALL.len() >= 3`: well-formed has `ALL.len() - 1 >= 2` missing,
5863///   so `has_multiple_missing_kinds() == true`.
5864///
5865/// The two-slot diagonal expectation similarly depends:
5866///
5867/// - `ALL.len() == 3`: two_slot has `3 - 2 == 1` missing → `false`.
5868/// - `ALL.len() >= 4`: two_slot has `ALL.len() - 2 >= 2` missing →
5869///   `true`.
5870///
5871/// A fifth sibling tagged-union parent picks up the many-complement-
5872/// cardinality Boolean check through ONE `impl TaggedUnion for X`
5873/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
5874/// `two_slot_X` factory plus ONE per-site `empty_X` factory plus ONE
5875/// call site.
5876///
5877/// # Theory grounding
5878///
5879/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
5880/// - THEORY.md §VI.1 — generation over composition.
5881#[track_caller]
5882pub fn assert_has_multiple_missing_kinds_matches_missing_kind_count<T, F, G, H>(
5883    single_slot: F,
5884    two_slot: G,
5885    empty_parent: H,
5886) where
5887    T: TaggedUnion,
5888    T::Kind: PartialEq + std::fmt::Debug,
5889    F: Fn(T::Kind) -> T,
5890    G: Fn(T::Kind, T::Kind) -> T,
5891    H: Fn() -> T,
5892{
5893    let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
5894    // Empty-parent baseline — ALL.len() missing slots, so
5895    // `has_multiple_missing_kinds()` returns `true` on any
5896    // ALL.len() >= 2 closed set.
5897    let empty = empty_parent();
5898    let empty_expected = all_len >= 2;
5899    assert_eq!(
5900        empty.has_multiple_missing_kinds(),
5901        empty_expected,
5902        "TaggedUnion::has_multiple_missing_kinds() on empty_parent() must equal {empty_expected} (ALL.len() == {all_len})",
5903    );
5904    assert_eq!(
5905        empty.has_multiple_missing_kinds(),
5906        empty.missing_kind_count() >= 2,
5907        "empty_parent().has_multiple_missing_kinds() drifted from (missing_kind_count() >= 2)",
5908    );
5909    // Trichotomy partition on the empty arm — has_multiple_missing_kinds
5910    // is true (ALL.len() >= 2), is_saturated + has_unique_missing_kind
5911    // are false.
5912    assert_eq!(
5913        usize::from(empty.is_saturated())
5914            + usize::from(empty.has_unique_missing_kind())
5915            + usize::from(empty.has_multiple_missing_kinds()),
5916        1,
5917        "empty_parent() must satisfy EXACTLY ONE of is_saturated / has_unique_missing_kind / has_multiple_missing_kinds",
5918    );
5919
5920    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5921        .iter()
5922        .copied()
5923    {
5924        let parent = single_slot(populated);
5925        let has_multiple = parent.has_multiple_missing_kinds();
5926        // Cardinality composition law.
5927        assert_eq!(
5928            has_multiple,
5929            parent.missing_kind_count() >= 2,
5930            "TaggedUnion::has_multiple_missing_kinds() drifted from (missing_kind_count() >= 2) — populated={populated:?}",
5931        );
5932        // Single-slot diagonal — well-formed has ALL.len() - 1
5933        // missing. `>= 2` iff `ALL.len() >= 3`.
5934        let expected_diagonal = all_len >= 3;
5935        assert_eq!(
5936            has_multiple,
5937            expected_diagonal,
5938            "TaggedUnion::has_multiple_missing_kinds() on single_slot({populated:?}) must equal {expected_diagonal} (ALL.len() == {all_len} → missing == {})",
5939            all_len - 1,
5940        );
5941        // Trichotomy partition on the well-formed arm.
5942        assert_eq!(
5943            usize::from(parent.is_saturated())
5944                + usize::from(parent.has_unique_missing_kind())
5945                + usize::from(has_multiple),
5946            1,
5947            "single_slot({populated:?}) must satisfy EXACTLY ONE of is_saturated / has_unique_missing_kind / has_multiple_missing_kinds",
5948        );
5949    }
5950
5951    // Two-slot sweep — every off-diagonal pair has ALL.len() - 2
5952    // missing.
5953    for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5954        .iter()
5955        .copied()
5956    {
5957        for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
5958            .iter()
5959            .copied()
5960        {
5961            if a == b {
5962                continue;
5963            }
5964            let parent = two_slot(a, b);
5965            let has_multiple = parent.has_multiple_missing_kinds();
5966            let expected_two_slot = all_len >= 4;
5967            assert_eq!(
5968                has_multiple,
5969                expected_two_slot,
5970                "TaggedUnion::has_multiple_missing_kinds() on two_slot({a:?}, {b:?}) must equal {expected_two_slot} (ALL.len() == {all_len} → missing == {})",
5971                all_len - 2,
5972            );
5973            assert_eq!(
5974                has_multiple,
5975                parent.missing_kind_count() >= 2,
5976                "TaggedUnion::has_multiple_missing_kinds() drifted from (missing_kind_count() >= 2) — pair=({a:?}, {b:?})",
5977            );
5978            // Trichotomy partition on the two-slot arm.
5979            assert_eq!(
5980                usize::from(parent.is_saturated())
5981                    + usize::from(parent.has_unique_missing_kind())
5982                    + usize::from(has_multiple),
5983                1,
5984                "two_slot({a:?}, {b:?}) must satisfy EXACTLY ONE of is_saturated / has_unique_missing_kind / has_multiple_missing_kinds",
5985            );
5986        }
5987    }
5988}
5989
5990/// Generic ≤1-populated-cardinality Boolean testkit — pins that
5991/// [`TaggedUnion::has_at_most_one_populated_kind`] agrees with all
5992/// THREE of its composition laws across every
5993/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
5994/// arrangement, every off-diagonal two-slot pair, AND the empty-parent
5995/// baseline.
5996///
5997/// Boolean-negation peer of
5998/// [`assert_has_multiple_populated_kinds_matches_populated_kind_count`]
5999/// under `!(≥ 2) == (≤ 1)` — closes the `{≥ 2, ≤ 1}` Boolean-negation
6000/// pair on the populated cardinality axis. The three composition laws
6001/// swept per arm:
6002///
6003/// 1. **Definitional Boolean-negation law**:
6004///    `has_at_most_one_populated_kind() == !has_multiple_populated_kinds()`
6005///    — the trait's default body binds the two forms as one bit-flip
6006///    over the SAME two-step-short-circuit closed-set walk.
6007/// 2. **Scalar cardinality composition law**:
6008///    `has_at_most_one_populated_kind() == (populated_kind_count() <= 1)`
6009///    — the Boolean projection agrees with the scalar count's `<= 1`
6010///    inequality.
6011/// 3. **Trichotomy union composition law**:
6012///    `has_at_most_one_populated_kind() == is_empty() || has_unique_populated_kind()`
6013///    — the union of the zero-arm and the one-arm of the
6014///    {0, 1, ≥ 2} cardinality trichotomy.
6015///
6016/// The three arm expectations:
6017///
6018/// - **Empty-parent baseline**: `has_at_most_one_populated_kind() ==
6019///   true` (0 ≤ 1).
6020/// - **Single-slot diagonal**: `has_at_most_one_populated_kind() ==
6021///   true` (1 ≤ 1) — the SOLE `Ok` arm of [`TaggedUnion::variant`]
6022///   lies inside the at-most-one region.
6023/// - **Two-slot sweep**: `has_at_most_one_populated_kind() == false`
6024///   (2 > 1) — the AMBIGUOUS arm sits outside the at-most-one region.
6025///
6026/// A fifth sibling tagged-union parent picks up the ≤1-populated-
6027/// cardinality Boolean check through ONE `impl TaggedUnion for X`
6028/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
6029/// `two_slot_X` factory plus ONE per-site `empty_X` factory plus ONE
6030/// call site — no re-authored per-site sweep.
6031///
6032/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
6033/// primitives — `Lifetime` doesn't impl [`TaggedUnion`].
6034///
6035/// # Theory grounding
6036///
6037/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
6038///   three composition laws bind the ≤1-populated Boolean projection
6039///   to the widened `!has_multiple_populated_kinds`, the scalar
6040///   `populated_kind_count <= 1`, and the union of zero-arm ∪ one-arm
6041///   at ONE substrate site each — swept across every production
6042///   tagged union at the testkit's per-arm sweep, not per-parent.
6043/// - THEORY.md §VI.1 — generation over composition. A new
6044///   [`Self::Kind`] variant added to `ALL` reaches the primitive
6045///   mechanically through the delegated
6046///   [`TaggedUnion::has_multiple_populated_kinds`].
6047#[track_caller]
6048pub fn assert_has_at_most_one_populated_kind_matches_populated_kind_count<T, F, G, H>(
6049    single_slot: F,
6050    two_slot: G,
6051    empty_parent: H,
6052) where
6053    T: TaggedUnion,
6054    T::Kind: PartialEq + std::fmt::Debug,
6055    F: Fn(T::Kind) -> T,
6056    G: Fn(T::Kind, T::Kind) -> T,
6057    H: Fn() -> T,
6058{
6059    // Empty-parent baseline — zero populated slots, so
6060    // `has_at_most_one_populated_kind()` returns `true` (0 <= 1).
6061    let empty = empty_parent();
6062    assert!(
6063        empty.has_at_most_one_populated_kind(),
6064        "TaggedUnion::has_at_most_one_populated_kind() on empty_parent() must equal true",
6065    );
6066    // Definitional Boolean-negation composition law on the empty arm.
6067    assert_eq!(
6068        empty.has_at_most_one_populated_kind(),
6069        !empty.has_multiple_populated_kinds(),
6070        "empty_parent().has_at_most_one_populated_kind() drifted from !has_multiple_populated_kinds()",
6071    );
6072    // Scalar cardinality composition law on the empty arm.
6073    assert_eq!(
6074        empty.has_at_most_one_populated_kind(),
6075        empty.populated_kind_count() <= 1,
6076        "empty_parent().has_at_most_one_populated_kind() drifted from (populated_kind_count() <= 1)",
6077    );
6078    // Trichotomy union composition law on the empty arm.
6079    assert_eq!(
6080        empty.has_at_most_one_populated_kind(),
6081        empty.is_empty() || empty.has_unique_populated_kind(),
6082        "empty_parent().has_at_most_one_populated_kind() drifted from (is_empty() || has_unique_populated_kind())",
6083    );
6084
6085    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6086        .iter()
6087        .copied()
6088    {
6089        let parent = single_slot(populated);
6090        let has_at_most_one = parent.has_at_most_one_populated_kind();
6091        // Single-slot diagonal — one populated (1 <= 1).
6092        assert!(
6093            has_at_most_one,
6094            "TaggedUnion::has_at_most_one_populated_kind() on single_slot({populated:?}) must equal true",
6095        );
6096        // Definitional Boolean-negation composition law.
6097        assert_eq!(
6098            has_at_most_one,
6099            !parent.has_multiple_populated_kinds(),
6100            "TaggedUnion::has_at_most_one_populated_kind() drifted from !has_multiple_populated_kinds() — populated={populated:?}",
6101        );
6102        // Scalar cardinality composition law.
6103        assert_eq!(
6104            has_at_most_one,
6105            parent.populated_kind_count() <= 1,
6106            "TaggedUnion::has_at_most_one_populated_kind() drifted from (populated_kind_count() <= 1) — populated={populated:?}",
6107        );
6108        // Trichotomy union composition law.
6109        assert_eq!(
6110            has_at_most_one,
6111            parent.is_empty() || parent.has_unique_populated_kind(),
6112            "TaggedUnion::has_at_most_one_populated_kind() drifted from (is_empty() || has_unique_populated_kind()) — populated={populated:?}",
6113        );
6114    }
6115
6116    // Two-slot sweep — every off-diagonal pair has 2 populated (> 1).
6117    for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6118        .iter()
6119        .copied()
6120    {
6121        for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6122            .iter()
6123            .copied()
6124        {
6125            if a == b {
6126                continue;
6127            }
6128            let parent = two_slot(a, b);
6129            let has_at_most_one = parent.has_at_most_one_populated_kind();
6130            assert!(
6131                !has_at_most_one,
6132                "TaggedUnion::has_at_most_one_populated_kind() on two_slot({a:?}, {b:?}) must equal false",
6133            );
6134            // Definitional Boolean-negation composition law.
6135            assert_eq!(
6136                has_at_most_one,
6137                !parent.has_multiple_populated_kinds(),
6138                "TaggedUnion::has_at_most_one_populated_kind() drifted from !has_multiple_populated_kinds() — pair=({a:?}, {b:?})",
6139            );
6140            // Scalar cardinality composition law.
6141            assert_eq!(
6142                has_at_most_one,
6143                parent.populated_kind_count() <= 1,
6144                "TaggedUnion::has_at_most_one_populated_kind() drifted from (populated_kind_count() <= 1) — pair=({a:?}, {b:?})",
6145            );
6146            // Trichotomy union composition law.
6147            assert_eq!(
6148                has_at_most_one,
6149                parent.is_empty() || parent.has_unique_populated_kind(),
6150                "TaggedUnion::has_at_most_one_populated_kind() drifted from (is_empty() || has_unique_populated_kind()) — pair=({a:?}, {b:?})",
6151            );
6152        }
6153    }
6154}
6155
6156/// Generic ≤1-missing-cardinality Boolean testkit — pins that
6157/// [`TaggedUnion::has_at_most_one_missing_kind`] agrees with all THREE
6158/// of its composition laws across every
6159/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
6160/// arrangement, every off-diagonal two-slot pair, AND the empty-parent
6161/// baseline.
6162///
6163/// Byte-for-byte peer of
6164/// [`assert_has_at_most_one_populated_kind_matches_populated_kind_count`]
6165/// under the (populated, missing) complement axis, and Boolean-negation
6166/// peer of
6167/// [`assert_has_multiple_missing_kinds_matches_missing_kind_count`]
6168/// under `!(≥ 2) == (≤ 1)` — closes the `{≥ 2, ≤ 1}` Boolean-negation
6169/// pair on the missing cardinality axis. Same three composition laws:
6170///
6171/// 1. **Definitional Boolean-negation law**:
6172///    `has_at_most_one_missing_kind() == !has_multiple_missing_kinds()`.
6173/// 2. **Scalar complement-cardinality composition law**:
6174///    `has_at_most_one_missing_kind() == (missing_kind_count() <= 1)`.
6175/// 3. **Trichotomy union composition law**:
6176///    `has_at_most_one_missing_kind() == is_saturated() || has_unique_missing_kind()`.
6177///
6178/// The three arm expectations depend on `ALL.len()`:
6179///
6180/// - **Empty-parent baseline** (on `ALL.len() ≥ 2`):
6181///   `has_at_most_one_missing_kind() == false` (ALL.len() missing
6182///   slots, so ≥ 2).
6183/// - **Single-slot diagonal**: `has_at_most_one_missing_kind() == true`
6184///   iff `ALL.len() - 1 <= 1`, i.e. `ALL.len() <= 2`. Every production
6185///   tagged union in this workspace has `ALL.len() ≥ 3`, so the
6186///   single-slot diagonal returns `false` on every production arm.
6187///   (Kept general for future 2-variant tagged unions.)
6188/// - **Two-slot sweep**: `has_at_most_one_missing_kind() == true` iff
6189///   `ALL.len() - 2 <= 1`, i.e. `ALL.len() <= 3`. On production unions
6190///   with `ALL.len() == 3` (e.g. two-arm plus one — none currently),
6191///   two_slot returns `true`; on `ALL.len() >= 4` it returns `false`.
6192///
6193/// A fifth sibling tagged-union parent picks up the ≤1-missing-
6194/// cardinality Boolean check through ONE `impl TaggedUnion for X`
6195/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
6196/// `two_slot_X` factory plus ONE per-site `empty_X` factory plus ONE
6197/// call site.
6198///
6199/// # Theory grounding
6200///
6201/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
6202/// - THEORY.md §VI.1 — generation over composition.
6203#[track_caller]
6204pub fn assert_has_at_most_one_missing_kind_matches_missing_kind_count<T, F, G, H>(
6205    single_slot: F,
6206    two_slot: G,
6207    empty_parent: H,
6208) where
6209    T: TaggedUnion,
6210    T::Kind: PartialEq + std::fmt::Debug,
6211    F: Fn(T::Kind) -> T,
6212    G: Fn(T::Kind, T::Kind) -> T,
6213    H: Fn() -> T,
6214{
6215    let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
6216    // Empty-parent baseline — ALL.len() missing slots, so
6217    // `has_at_most_one_missing_kind()` returns `true` iff ALL.len() <= 1.
6218    let empty = empty_parent();
6219    let empty_expected = all_len <= 1;
6220    assert_eq!(
6221        empty.has_at_most_one_missing_kind(),
6222        empty_expected,
6223        "TaggedUnion::has_at_most_one_missing_kind() on empty_parent() must equal {empty_expected} (ALL.len() == {all_len})",
6224    );
6225    // Definitional Boolean-negation composition law on the empty arm.
6226    assert_eq!(
6227        empty.has_at_most_one_missing_kind(),
6228        !empty.has_multiple_missing_kinds(),
6229        "empty_parent().has_at_most_one_missing_kind() drifted from !has_multiple_missing_kinds()",
6230    );
6231    // Scalar complement-cardinality composition law on the empty arm.
6232    assert_eq!(
6233        empty.has_at_most_one_missing_kind(),
6234        empty.missing_kind_count() <= 1,
6235        "empty_parent().has_at_most_one_missing_kind() drifted from (missing_kind_count() <= 1)",
6236    );
6237    // Trichotomy union composition law on the empty arm.
6238    assert_eq!(
6239        empty.has_at_most_one_missing_kind(),
6240        empty.is_saturated() || empty.has_unique_missing_kind(),
6241        "empty_parent().has_at_most_one_missing_kind() drifted from (is_saturated() || has_unique_missing_kind())",
6242    );
6243
6244    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6245        .iter()
6246        .copied()
6247    {
6248        let parent = single_slot(populated);
6249        let has_at_most_one = parent.has_at_most_one_missing_kind();
6250        // Single-slot diagonal — well-formed parent has ALL.len() - 1
6251        // missing. `<= 1` iff `ALL.len() <= 2`.
6252        let expected_diagonal = all_len <= 2;
6253        assert_eq!(
6254            has_at_most_one,
6255            expected_diagonal,
6256            "TaggedUnion::has_at_most_one_missing_kind() on single_slot({populated:?}) must equal {expected_diagonal} (ALL.len() == {all_len} → missing == {})",
6257            all_len - 1,
6258        );
6259        // Definitional Boolean-negation composition law.
6260        assert_eq!(
6261            has_at_most_one,
6262            !parent.has_multiple_missing_kinds(),
6263            "TaggedUnion::has_at_most_one_missing_kind() drifted from !has_multiple_missing_kinds() — populated={populated:?}",
6264        );
6265        // Scalar complement-cardinality composition law.
6266        assert_eq!(
6267            has_at_most_one,
6268            parent.missing_kind_count() <= 1,
6269            "TaggedUnion::has_at_most_one_missing_kind() drifted from (missing_kind_count() <= 1) — populated={populated:?}",
6270        );
6271        // Trichotomy union composition law.
6272        assert_eq!(
6273            has_at_most_one,
6274            parent.is_saturated() || parent.has_unique_missing_kind(),
6275            "TaggedUnion::has_at_most_one_missing_kind() drifted from (is_saturated() || has_unique_missing_kind()) — populated={populated:?}",
6276        );
6277    }
6278
6279    // Two-slot sweep — every off-diagonal pair has ALL.len() - 2
6280    // missing. `<= 1` iff `ALL.len() <= 3`.
6281    for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6282        .iter()
6283        .copied()
6284    {
6285        for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6286            .iter()
6287            .copied()
6288        {
6289            if a == b {
6290                continue;
6291            }
6292            let parent = two_slot(a, b);
6293            let has_at_most_one = parent.has_at_most_one_missing_kind();
6294            let expected_two_slot = all_len <= 3;
6295            assert_eq!(
6296                has_at_most_one,
6297                expected_two_slot,
6298                "TaggedUnion::has_at_most_one_missing_kind() on two_slot({a:?}, {b:?}) must equal {expected_two_slot} (ALL.len() == {all_len} → missing == {})",
6299                all_len - 2,
6300            );
6301            // Definitional Boolean-negation composition law.
6302            assert_eq!(
6303                has_at_most_one,
6304                !parent.has_multiple_missing_kinds(),
6305                "TaggedUnion::has_at_most_one_missing_kind() drifted from !has_multiple_missing_kinds() — pair=({a:?}, {b:?})",
6306            );
6307            // Scalar complement-cardinality composition law.
6308            assert_eq!(
6309                has_at_most_one,
6310                parent.missing_kind_count() <= 1,
6311                "TaggedUnion::has_at_most_one_missing_kind() drifted from (missing_kind_count() <= 1) — pair=({a:?}, {b:?})",
6312            );
6313            // Trichotomy union composition law.
6314            assert_eq!(
6315                has_at_most_one,
6316                parent.is_saturated() || parent.has_unique_missing_kind(),
6317                "TaggedUnion::has_at_most_one_missing_kind() drifted from (is_saturated() || has_unique_missing_kind()) — pair=({a:?}, {b:?})",
6318            );
6319        }
6320    }
6321}
6322
6323/// Generic parent-state-middle-arm Boolean testkit — pins that
6324/// [`TaggedUnion::is_partially_populated`] agrees with the paired
6325/// scalar-cardinality strict-inequality composition
6326/// `(populated_kind_count() > 0 && missing_kind_count() > 0)` across
6327/// every [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-
6328/// slot arrangement, every off-diagonal two-slot pair, AND the empty-
6329/// parent baseline.
6330///
6331/// Parent-state-axis substrate primitive for the Boolean middle-arm
6332/// projection of the `{Empty | Partial | Saturated}` trichotomy —
6333/// orthogonal to the {0, 1, ≥2} cardinality trichotomies already
6334/// closed on the populated / missing axes. The four sub-assertions
6335/// swept per populated slot + the four baseline sub-assertions on the
6336/// empty parent + the four sub-assertions swept per off-diagonal pair
6337/// bind FOUR composition laws per arm:
6338///
6339/// 1. **Widened negation-of-both-endpoints composition law**:
6340///    `is_partially_populated() == !is_empty() && !is_saturated()` —
6341///    the natural composition that the trait's default body's fused
6342///    walk collapses into ONE closed-set traversal. Pinned so a
6343///    regression that overrides `is_partially_populated` to skip the
6344///    sweep or return the wrong Boolean fails here at the widened
6345///    negation.
6346/// 2. **Paired scalar-cardinality composition law**:
6347///    `is_partially_populated() == (populated_kind_count() > 0 &&
6348///    missing_kind_count() > 0)` — the Boolean projection agrees with
6349///    the paired scalar-cardinality strict-inequality composition on
6350///    every empty / well-formed / partial / saturated arm.
6351/// 3. **Single-axis open-interval composition law**:
6352///    `is_partially_populated() == (0 < populated_kind_count() &&
6353///    populated_kind_count() < ALL.len())` — the Boolean projection
6354///    agrees with the single-axis strict-inequality composition
6355///    (populated cardinality lies in the open interval `(0, ALL.len())`).
6356/// 4. **Parent-state trichotomy partition law**:
6357///    `usize::from(is_empty()) + usize::from(is_partially_populated()) + usize::from(is_saturated()) == 1`
6358///    — EXACTLY ONE of the three parent-state Boolean primitives
6359///    returns `true` on every arm. This is the genuinely new proof
6360///    this testkit adds: the natural parent-state trichotomy
6361///    partitions every tagged-union state coherently, and this law
6362///    lives at ONE substrate site inside the testkit's per-arm sweep,
6363///    pinned across every production tagged union.
6364///
6365/// The three arm expectations:
6366///
6367/// - **Empty-parent baseline** (swept once outside the per-`k` loop):
6368///   `empty_parent().is_partially_populated() == false` (zero
6369///   populated, so the negation `!is_empty()` fails). Pins the
6370///   primitive's opposite-arm on the same fixture the empty-Boolean
6371///   peer pins its zero-arm.
6372/// - **Single-slot diagonal** (on `ALL.len() ≥ 2` closed sets):
6373///   `single_slot(k).is_partially_populated() == true` — a well-formed
6374///   parent from `single_slot` populates exactly one slot (0 <
6375///   populated < N), so the middle arm returns `true`. Pins the
6376///   primitive doesn't drift onto either endpoint.
6377/// - **Two-slot sweep** (on `ALL.len() ≥ 3` closed sets, which every
6378///   production tagged union in the workspace satisfies):
6379///   `two_slot(a, b).is_partially_populated() == true` — an
6380///   off-diagonal pair populates exactly two slots (0 < 2 <= N-1 < N
6381///   for N ≥ 3), so the middle arm returns `true`. On `ALL.len() ==
6382///   2` (production `Lifetime` excluded via the `TaggedUnion` bound)
6383///   two_slot would be saturated (`false`), but no production tagged
6384///   union has `ALL.len() == 2`.
6385///
6386/// A fifth sibling tagged-union parent picks up the middle-arm-
6387/// Boolean check through ONE `impl TaggedUnion for X` block plus ONE
6388/// per-site `single_slot_X` factory plus ONE per-site `two_slot_X`
6389/// factory plus ONE per-site `empty_X` factory plus ONE call site —
6390/// no re-authored `is_partially_populated` sweep at the test surface.
6391///
6392/// Same `Lifetime` exclusion as the sibling primitives — see
6393/// [`assert_two_slots_ambiguous`].
6394///
6395/// # Theory grounding
6396///
6397/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
6398///   Boolean parent-state middle-arm projection binds through the
6399///   SAME shape the two endpoint primitives bind through (a closed-
6400///   set walk under `Self::has`), differing only in the fused
6401///   short-circuit gate (both flags flipped) versus the endpoint
6402///   primitives' single-flag `any` / `all` short-circuits. The
6403///   trichotomy partition law lives at ONE substrate site inside the
6404///   testkit's per-arm sweep — pinned across every production tagged
6405///   union at compile time via the trait's default body composition,
6406///   not per-parent.
6407/// - THEORY.md §VI.1 — generation over composition. A new
6408///   [`Self::Kind`] variant added to `ALL` reaches this primitive
6409///   mechanically through the fused walk at the trait's default body.
6410#[track_caller]
6411pub fn assert_is_partially_populated_matches_cardinality<T, F, G, H>(
6412    single_slot: F,
6413    two_slot: G,
6414    empty_parent: H,
6415) where
6416    T: TaggedUnion,
6417    T::Kind: PartialEq + std::fmt::Debug,
6418    F: Fn(T::Kind) -> T,
6419    G: Fn(T::Kind, T::Kind) -> T,
6420    H: Fn() -> T,
6421{
6422    let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
6423
6424    // Empty-parent baseline — zero populated slots, so
6425    // `is_partially_populated()` returns `false` (the empty arm of the
6426    // parent-state trichotomy, not the partial arm).
6427    let empty = empty_parent();
6428    // Anchor the baseline factory on the genuine empty arm — a saturated
6429    // factory would also return `false` from `is_partially_populated()`
6430    // (both endpoints of the trichotomy sit on the `false` side of the
6431    // middle-arm), so this explicit `is_empty()` pin distinguishes the
6432    // empty arm from the saturated arm on the baseline.
6433    assert!(
6434        empty.is_empty(),
6435        "TaggedUnion::is_partially_populated() testkit: empty_parent() must satisfy is_empty() == true",
6436    );
6437    assert!(
6438        !empty.is_partially_populated(),
6439        "TaggedUnion::is_partially_populated() on empty_parent() must equal false",
6440    );
6441    // Widened negation-of-both-endpoints composition law on the empty
6442    // arm.
6443    assert_eq!(
6444        empty.is_partially_populated(),
6445        !empty.is_empty() && !empty.is_saturated(),
6446        "empty_parent().is_partially_populated() drifted from (!is_empty() && !is_saturated())",
6447    );
6448    // Paired scalar-cardinality composition law on the empty arm.
6449    assert_eq!(
6450        empty.is_partially_populated(),
6451        empty.populated_kind_count() > 0 && empty.missing_kind_count() > 0,
6452        "empty_parent().is_partially_populated() drifted from (populated_kind_count() > 0 && missing_kind_count() > 0)",
6453    );
6454    // Parent-state trichotomy partition law on the empty arm —
6455    // is_empty is true, the other two are false.
6456    assert_eq!(
6457        usize::from(empty.is_empty())
6458            + usize::from(empty.is_partially_populated())
6459            + usize::from(empty.is_saturated()),
6460        1,
6461        "empty_parent() must satisfy EXACTLY ONE of is_empty / is_partially_populated / is_saturated",
6462    );
6463
6464    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6465        .iter()
6466        .copied()
6467    {
6468        let parent = single_slot(populated);
6469        let is_partial = parent.is_partially_populated();
6470        // Widened negation-of-both-endpoints composition law.
6471        assert_eq!(
6472            is_partial,
6473            !parent.is_empty() && !parent.is_saturated(),
6474            "TaggedUnion::is_partially_populated() drifted from (!is_empty() && !is_saturated()) — populated={populated:?}",
6475        );
6476        // Paired scalar-cardinality composition law.
6477        assert_eq!(
6478            is_partial,
6479            parent.populated_kind_count() > 0 && parent.missing_kind_count() > 0,
6480            "TaggedUnion::is_partially_populated() drifted from (populated_kind_count() > 0 && missing_kind_count() > 0) — populated={populated:?}",
6481        );
6482        // Single-axis open-interval composition law.
6483        assert_eq!(
6484            is_partial,
6485            0 < parent.populated_kind_count() && parent.populated_kind_count() < all_len,
6486            "TaggedUnion::is_partially_populated() drifted from (0 < populated_kind_count() < ALL.len()) — populated={populated:?}",
6487        );
6488        // Single-slot diagonal (on any `ALL.len() ≥ 2` closed set) —
6489        // well-formed has 1 populated + `ALL.len() - 1 ≥ 1` missing,
6490        // so the middle arm returns `true`. This holds for every
6491        // production tagged union in the workspace (all have
6492        // `ALL.len() ≥ 2`).
6493        assert!(
6494            is_partial,
6495            "TaggedUnion::is_partially_populated() on single_slot({populated:?}) must equal true — ALL.len() >= 2",
6496        );
6497        // Parent-state trichotomy partition on the well-formed arm.
6498        assert_eq!(
6499            usize::from(parent.is_empty())
6500                + usize::from(is_partial)
6501                + usize::from(parent.is_saturated()),
6502            1,
6503            "single_slot({populated:?}) must satisfy EXACTLY ONE of is_empty / is_partially_populated / is_saturated",
6504        );
6505    }
6506
6507    // Two-slot sweep — every off-diagonal pair has 2 populated
6508    // + `ALL.len() - 2` missing.
6509    for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6510        .iter()
6511        .copied()
6512    {
6513        for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6514            .iter()
6515            .copied()
6516        {
6517            if a == b {
6518                continue;
6519            }
6520            let parent = two_slot(a, b);
6521            let is_partial = parent.is_partially_populated();
6522            // Widened negation-of-both-endpoints composition law.
6523            assert_eq!(
6524                is_partial,
6525                !parent.is_empty() && !parent.is_saturated(),
6526                "TaggedUnion::is_partially_populated() drifted from (!is_empty() && !is_saturated()) — pair=({a:?}, {b:?})",
6527            );
6528            // Paired scalar-cardinality composition law.
6529            assert_eq!(
6530                is_partial,
6531                parent.populated_kind_count() > 0 && parent.missing_kind_count() > 0,
6532                "TaggedUnion::is_partially_populated() drifted from (populated_kind_count() > 0 && missing_kind_count() > 0) — pair=({a:?}, {b:?})",
6533            );
6534            // Two-slot diagonal — on `ALL.len() >= 3` the two-slot
6535            // parent has 2 populated + `ALL.len() - 2 >= 1` missing,
6536            // so the middle arm returns `true`. On `ALL.len() == 2`
6537            // (excluded via the `TaggedUnion` bound anyway) two_slot
6538            // would be saturated (`false`).
6539            let expected_two_slot = all_len >= 3;
6540            assert_eq!(
6541                is_partial,
6542                expected_two_slot,
6543                "TaggedUnion::is_partially_populated() on two_slot({a:?}, {b:?}) must equal {expected_two_slot} (ALL.len() == {all_len})",
6544            );
6545            // Parent-state trichotomy partition on the two-slot arm.
6546            assert_eq!(
6547                usize::from(parent.is_empty())
6548                    + usize::from(is_partial)
6549                    + usize::from(parent.is_saturated()),
6550                1,
6551                "two_slot({a:?}, {b:?}) must satisfy EXACTLY ONE of is_empty / is_partially_populated / is_saturated",
6552            );
6553        }
6554    }
6555}
6556
6557/// Generic kind-scoped strict-refinement testkit — pins that
6558/// [`TaggedUnion::has_only`] agrees with the widened composition
6559/// `unique_populated_kind() == Some(kind)` across every
6560/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) `× ALL`
6561/// single-slot (populated, probed) pair, every off-diagonal two-slot
6562/// pair `× ALL`, AND the empty-parent baseline `× ALL`.
6563///
6564/// Kind-scoped-strict-refinement-axis substrate primitive for the
6565/// argument-taking uniqueness peer of [`TaggedUnion::has`] — the
6566/// EQUAL predicate to `has`'s SUBSET predicate. FIVE composition laws
6567/// per arm are pinned per (populated / pair / empty × probed) sub-
6568/// assertion:
6569///
6570/// 1. **Widened uniqueness composition law**:
6571///    `has_only(kind) == (unique_populated_kind() == Some(kind))` —
6572///    the canonical composition that the trait's default body's fused
6573///    walk collapses into ONE short-circuit closed-set traversal.
6574///    Pinned so a regression that overrides `has_only` to skip the
6575///    sweep, drop the "no other populated" check, or return the wrong
6576///    Boolean fails here at the widened uniqueness composition.
6577/// 2. **Cardinality-refinement composition law**:
6578///    `has_only(kind) == (has(kind) && has_unique_populated_kind())`
6579///    — the paired-endpoint composition binding the strict refinement
6580///    to the arg-less uniqueness predicate. Pinned so a regression
6581///    that drops the "exactly one populated" check (returning `true`
6582///    on a multi-populated parent whose SET of populated kinds
6583///    contains `kind`) is caught here.
6584/// 3. **Kind-scoped implication law**:
6585///    `has_only(kind) → has(kind)` — every arm where `has_only`
6586///    returns `true` must satisfy `has(kind) == true` (the SUBSET
6587///    predicate must accept every parent the EQUAL predicate
6588///    accepts). Pinned so a regression that returns `true` on an
6589///    empty parent or a parent that populates a DIFFERENT kind is
6590///    caught here.
6591/// 4. **Kind-domain exhaustivity law**:
6592///    `<Kind as ClosedSet>::ALL.iter().filter(|k|
6593///    parent.has_only(*k)).count() ≤ 1` on every arm — a parent
6594///    satisfies `has_only(k)` for AT MOST one `k`, since two distinct
6595///    kinds cannot both be the sole populated slot. On the well-
6596///    formed arm the count is exactly 1 (the addressed kind); on the
6597///    empty AND multi-populated arms the count is 0. This kind-domain
6598///    exhaustivity law binds the argument-scoped projection to the
6599///    arg-less uniqueness predicate at ONE substrate site.
6600/// 5. **Well-formed diagonal law**:
6601///    `single_slot(k).has_only(k) == true` on every `k ∈
6602///    ClosedSet::ALL` — the single-slot factory constructs a well-
6603///    formed parent, so every `has_only(k)` on the diagonal is
6604///    `true`. Pinned so a regression that returns `false` on the
6605///    well-formed arm (e.g. a typo `!self.has(k)` in the trait
6606///    default) is caught here.
6607///
6608/// The three arm expectations:
6609///
6610/// - **Empty-parent baseline** (swept `× ALL` outside the per-slot
6611///   loop): `empty_parent().has_only(k) == false` for every `k` — no
6612///   populated slot, so no kind is the sole populated kind.
6613/// - **Single-slot sweep** (swept on `ClosedSet::ALL × ALL`):
6614///   `single_slot(populated).has_only(kind) == (populated == kind)`
6615///   — the well-formed truth table.
6616/// - **Two-slot sweep** (swept on the off-diagonal `× ALL`):
6617///   `two_slot(a, b).has_only(k) == false` for every `k` — multi-
6618///   populated parents satisfy `has_only(k)` for NO kind.
6619///
6620/// A fifth sibling tagged-union parent picks up the kind-scoped-
6621/// strict-refinement check through ONE `impl TaggedUnion for X`
6622/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
6623/// `two_slot_X` factory plus ONE per-site `empty_X` factory plus ONE
6624/// call site — no re-authored `has_only` sweep at the test surface.
6625///
6626/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
6627/// primitives — the `T: TaggedUnion` bound doesn't reach it.
6628///
6629/// # Theory grounding
6630///
6631/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
6632///   kind-scoped strict-refinement projection binds through the SAME
6633///   shape the arg-less uniqueness peer binds through (a closed-set
6634///   walk under `Self::has`), differing only in the argument-scoped
6635///   short-circuit gate (first populated slot mismatched → `false`).
6636///   The kind-domain exhaustivity law
6637///   `count k where has_only(k) ≤ 1` lives at ONE substrate site
6638///   inside the testkit's per-arm sweep — pinned across every
6639///   production tagged union at compile time via the trait's default
6640///   body composition, not per-parent.
6641/// - THEORY.md §VI.1 — generation over composition. A new
6642///   [`Self::Kind`] variant added to `ALL` reaches this primitive
6643///   mechanically through the fused walk at the trait's default body.
6644#[track_caller]
6645pub fn assert_has_only_matches_unique_populated_kind<T, F, G, H>(
6646    single_slot: F,
6647    two_slot: G,
6648    empty_parent: H,
6649) where
6650    T: TaggedUnion,
6651    T::Kind: PartialEq + std::fmt::Debug,
6652    F: Fn(T::Kind) -> T,
6653    G: Fn(T::Kind, T::Kind) -> T,
6654    H: Fn() -> T,
6655{
6656    // Empty-parent baseline — every `has_only(k)` returns `false`
6657    // because no slot is populated.
6658    let empty = empty_parent();
6659    assert!(
6660        empty.is_empty(),
6661        "TaggedUnion::has_only() testkit: empty_parent() must satisfy is_empty() == true",
6662    );
6663    for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6664        .iter()
6665        .copied()
6666    {
6667        let via_has_only = empty.has_only(k);
6668        assert!(
6669            !via_has_only,
6670            "empty_parent().has_only({k:?}) must equal false",
6671        );
6672        // Widened uniqueness composition law on the empty arm.
6673        assert_eq!(
6674            via_has_only,
6675            empty.unique_populated_kind() == Some(k),
6676            "empty_parent().has_only({k:?}) drifted from (unique_populated_kind() == Some({k:?}))",
6677        );
6678        // Cardinality-refinement composition law on the empty arm.
6679        assert_eq!(
6680            via_has_only,
6681            empty.has(k) && empty.has_unique_populated_kind(),
6682            "empty_parent().has_only({k:?}) drifted from (has({k:?}) && has_unique_populated_kind())",
6683        );
6684    }
6685    // Kind-domain exhaustivity on the empty arm — no kind is the sole
6686    // populated kind, so the count is 0.
6687    let empty_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
6688        .iter()
6689        .copied()
6690        .filter(|k| empty.has_only(*k))
6691        .count();
6692    assert_eq!(
6693        empty_count, 0,
6694        "empty_parent(): exactly 0 kinds must satisfy has_only, got {empty_count}",
6695    );
6696
6697    // Single-slot sweep — the well-formed truth table across
6698    // `ClosedSet::ALL × ALL`.
6699    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6700        .iter()
6701        .copied()
6702    {
6703        let parent = single_slot(populated);
6704        for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6705            .iter()
6706            .copied()
6707        {
6708            let expected = probed == populated;
6709            let via_has_only = parent.has_only(probed);
6710            // Truth table on the well-formed diagonal — `true` iff the
6711            // probed kind equals the populated kind.
6712            assert_eq!(
6713                via_has_only, expected,
6714                "single_slot({populated:?}).has_only({probed:?}) must equal {expected}",
6715            );
6716            // Widened uniqueness composition law.
6717            assert_eq!(
6718                via_has_only,
6719                parent.unique_populated_kind() == Some(probed),
6720                "single_slot({populated:?}).has_only({probed:?}) drifted from (unique_populated_kind() == Some({probed:?}))",
6721            );
6722            // Cardinality-refinement composition law.
6723            assert_eq!(
6724                via_has_only,
6725                parent.has(probed) && parent.has_unique_populated_kind(),
6726                "single_slot({populated:?}).has_only({probed:?}) drifted from (has({probed:?}) && has_unique_populated_kind())",
6727            );
6728            // Kind-scoped implication law — has_only implies has.
6729            if via_has_only {
6730                assert!(
6731                    parent.has(probed),
6732                    "single_slot({populated:?}).has_only({probed:?}) == true but has({probed:?}) == false",
6733                );
6734            }
6735        }
6736        // Kind-domain exhaustivity on the well-formed arm — exactly 1
6737        // kind (the populated one) satisfies has_only.
6738        let well_formed_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
6739            .iter()
6740            .copied()
6741            .filter(|k| parent.has_only(*k))
6742            .count();
6743        assert_eq!(
6744            well_formed_count, 1,
6745            "single_slot({populated:?}): exactly 1 kind must satisfy has_only, got {well_formed_count}",
6746        );
6747    }
6748
6749    // Two-slot sweep — every off-diagonal pair populates two slots, so
6750    // has_only(k) == false for every k, and no kind satisfies has_only
6751    // on the multi-populated arm.
6752    for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6753        .iter()
6754        .copied()
6755    {
6756        for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6757            .iter()
6758            .copied()
6759        {
6760            if a == b {
6761                continue;
6762            }
6763            let parent = two_slot(a, b);
6764            for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6765                .iter()
6766                .copied()
6767            {
6768                let via_has_only = parent.has_only(k);
6769                assert!(
6770                    !via_has_only,
6771                    "two_slot({a:?}, {b:?}).has_only({k:?}) must equal false",
6772                );
6773                // Widened uniqueness composition law on the multi-
6774                // populated arm.
6775                assert_eq!(
6776                    via_has_only,
6777                    parent.unique_populated_kind() == Some(k),
6778                    "two_slot({a:?}, {b:?}).has_only({k:?}) drifted from (unique_populated_kind() == Some({k:?}))",
6779                );
6780                // Cardinality-refinement composition law.
6781                assert_eq!(
6782                    via_has_only,
6783                    parent.has(k) && parent.has_unique_populated_kind(),
6784                    "two_slot({a:?}, {b:?}).has_only({k:?}) drifted from (has({k:?}) && has_unique_populated_kind())",
6785                );
6786            }
6787            // Kind-domain exhaustivity on the multi-populated arm — no
6788            // kind is the sole populated kind.
6789            let multi_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
6790                .iter()
6791                .copied()
6792                .filter(|k| parent.has_only(*k))
6793                .count();
6794            assert_eq!(
6795                multi_count, 0,
6796                "two_slot({a:?}, {b:?}): exactly 0 kinds must satisfy has_only, got {multi_count}",
6797            );
6798        }
6799    }
6800}
6801
6802/// Generic kind-scoped strict-refinement testkit on the MISSING axis —
6803/// pins that [`TaggedUnion::lacks_only`] agrees with
6804/// [`TaggedUnion::unique_missing_kind`]'s
6805/// argument-scoped projection, [`TaggedUnion::has`]'s negated
6806/// cardinality-refinement, AND the kind-scoped implication
6807/// `lacks_only(kind) → !has(kind)` across every
6808/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
6809/// arrangement, every off-diagonal two-slot pair, AND the empty-parent
6810/// baseline.
6811///
6812/// Closed-set-complement mirror of
6813/// [`assert_has_only_matches_unique_populated_kind`] under the
6814/// (populated, missing) duality — where the populated-axis primitive
6815/// binds `has_only(kind)` to `unique_populated_kind()`, this primitive
6816/// binds `lacks_only(kind)` to `unique_missing_kind()` through the
6817/// same shape (a closed-set walk under `Self::has`, differing only in
6818/// the negation of the presence probe). The four sub-assertions swept
6819/// per single-slot arrangement + the two-slot sweep + the empty-parent
6820/// baseline:
6821///
6822/// 1. **Widened uniqueness composition law**:
6823///    `lacks_only(kind) == (unique_missing_kind() == Some(kind))` on
6824///    every arm — the fused walk's argument-scoped projection agrees
6825///    with the arg-less unique-missing primitive's `Option::eq` on
6826///    `Some(kind)`. Byte-for-byte peer of
6827///    [`assert_has_only_matches_unique_populated_kind`]'s widened
6828///    uniqueness law under complement.
6829/// 2. **Cardinality-refinement composition law**:
6830///    `lacks_only(kind) == (!has(kind) && has_unique_missing_kind())`
6831///    on every arm — the fused walk agrees with the two-step
6832///    composition of the negated presence probe and the arg-less
6833///    missing-cardinality Boolean. Closed-set-complement mirror of
6834///    the populated-axis cardinality-refinement law.
6835/// 3. **Kind-scoped implication law**:
6836///    `lacks_only(kind) → !has(kind)` on every arm — if `kind` is the
6837///    sole missing slot then `kind` cannot be populated. Complement
6838///    mirror of the `has_only(kind) → has(kind)` implication that
6839///    binds [`TaggedUnion::has_only`] to [`TaggedUnion::has`] on the
6840///    strict-refinement axis; here the implication binds `lacks_only`
6841///    to `!has` on the closed-set-complement axis.
6842/// 4. **Kind-domain exhaustivity law**: `<T::Kind as ClosedSet>::ALL
6843///    .iter().filter(|k| parent.lacks_only(*k)).count() ≤ 1` on every
6844///    arm — a parent satisfies `lacks_only(k)` for AT MOST one `k`,
6845///    since two distinct kinds cannot both be the sole missing slot.
6846///    On the near-saturation arm (exactly 1 missing) the count is 1;
6847///    on every other arm the count is 0. Closed-set-complement mirror
6848///    of the populated-axis exhaustivity law under complement.
6849/// 5. **Missing-diagonal well-formed law**:
6850///    `unique_missing_kind()` is the source of truth for which kind
6851///    (if any) is uniquely missing on each arm — the testkit reads it
6852///    directly and asserts `lacks_only(k) == (unique_missing_kind()
6853///    == Some(k))` for every `k`, so the testkit doesn't hard-code
6854///    `ALL.len()`-dependent arm expectations (an empty parent on
6855///    `ALL.len() == 1` is uniquely missing that one kind, whereas on
6856///    `ALL.len() >= 2` no kind is uniquely missing; a single-slot
6857///    parent on `ALL.len() == 2` has one missing kind, whereas on
6858///    `ALL.len() >= 3` it has ≥ 2 missing; a two-slot parent on
6859///    `ALL.len() == 3` has one missing kind, whereas on `ALL.len()
6860///    >= 4` it has ≥ 2 missing). The composition-law shape binds
6861///    every `ALL.len()` regime through the same substrate site.
6862///
6863/// The three arm expectations:
6864///
6865/// - **Empty-parent baseline** (swept `× ALL` outside the per-slot
6866///   loop): on any `ALL.len() >= 2` closed set every kind is missing,
6867///   so `lacks_only(k) == false` for every `k` — no kind is the sole
6868///   missing kind. Every production parent is `ALL.len() >= 3`.
6869/// - **Single-slot sweep** (swept on `ClosedSet::ALL × ALL`): the
6870///   composition-law shape reads `unique_missing_kind()` directly, so
6871///   the testkit binds every `ALL.len()` regime without a hard-coded
6872///   arm expectation. Assertion messages carry the (`populated`,
6873///   `probed`) pair verbatim.
6874/// - **Two-slot sweep** (swept on the off-diagonal `× ALL`): on
6875///   `ALL.len() == 3` every off-diagonal pair leaves exactly 1 slot
6876///   missing (the third kind) — the SOLE `ALL.len()` regime where
6877///   `lacks_only(third) == true` on the two-slot arm. On `ALL.len()
6878///   >= 4` the two-slot arm has ≥ 2 missing, so `lacks_only(k) ==
6879///   false` for every `k`. The composition-law shape binds every
6880///   regime.
6881///
6882/// A fifth sibling tagged-union parent picks up the kind-scoped-
6883/// strict-refinement check on the missing axis through ONE `impl
6884/// TaggedUnion for X` block plus ONE per-site `single_slot_X` factory
6885/// plus ONE per-site `two_slot_X` factory plus ONE per-site `empty_X`
6886/// factory plus ONE call site — no re-authored `lacks_only` sweep at
6887/// the test surface.
6888///
6889/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
6890/// primitives — the `T: TaggedUnion` bound doesn't reach it.
6891///
6892/// # Theory grounding
6893///
6894/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
6895///   kind-scoped strict-refinement projection on the MISSING axis
6896///   binds through the SAME shape the populated-axis peer binds
6897///   through (a closed-set walk under `Self::has`), differing only in
6898///   the negation of the presence probe. The composition laws
6899///   (widened uniqueness on the missing side, cardinality-refinement
6900///   under complement, kind-scoped implication under complement,
6901///   kind-domain exhaustivity on the missing side) live at ONE
6902///   substrate site inside the testkit's per-arm sweep — pinned
6903///   across every production tagged union at compile time via the
6904///   trait's default body composition, not per-parent.
6905/// - THEORY.md §VI.1 — generation over composition. A new
6906///   [`Self::Kind`] variant added to `ALL` reaches this primitive
6907///   mechanically through the fused walk at the trait's default body.
6908#[track_caller]
6909pub fn assert_lacks_only_matches_unique_missing_kind<T, F, G, H>(
6910    single_slot: F,
6911    two_slot: G,
6912    empty_parent: H,
6913) where
6914    T: TaggedUnion,
6915    T::Kind: PartialEq + std::fmt::Debug,
6916    F: Fn(T::Kind) -> T,
6917    G: Fn(T::Kind, T::Kind) -> T,
6918    H: Fn() -> T,
6919{
6920    // Empty-parent baseline — every `lacks_only(k)` returns `false` on
6921    // any `ALL.len() >= 2` closed set (every production union) because
6922    // every kind is missing so no kind is uniquely missing. The
6923    // composition-law shape below reads `unique_missing_kind()`
6924    // directly, so the testkit binds every `ALL.len()` regime without
6925    // a hard-coded arm expectation.
6926    let empty = empty_parent();
6927    assert!(
6928        empty.is_empty(),
6929        "TaggedUnion::lacks_only() testkit: empty_parent() must satisfy is_empty() == true",
6930    );
6931    for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6932        .iter()
6933        .copied()
6934    {
6935        let via_lacks_only = empty.lacks_only(k);
6936        // Widened uniqueness composition law on the empty arm.
6937        assert_eq!(
6938            via_lacks_only,
6939            empty.unique_missing_kind() == Some(k),
6940            "empty_parent().lacks_only({k:?}) drifted from (unique_missing_kind() == Some({k:?}))",
6941        );
6942        // Cardinality-refinement composition law on the empty arm
6943        // under complement.
6944        assert_eq!(
6945            via_lacks_only,
6946            !empty.has(k) && empty.has_unique_missing_kind(),
6947            "empty_parent().lacks_only({k:?}) drifted from (!has({k:?}) && has_unique_missing_kind())",
6948        );
6949        // Kind-scoped implication law on the empty arm — lacks_only
6950        // implies !has.
6951        if via_lacks_only {
6952            assert!(
6953                !empty.has(k),
6954                "empty_parent().lacks_only({k:?}) == true but has({k:?}) == true",
6955            );
6956        }
6957    }
6958    // Kind-domain exhaustivity on the empty arm — at most 1 kind is
6959    // the sole missing kind. On `ALL.len() >= 2` the count is 0; on
6960    // the degenerate `ALL.len() == 1` regime (no production parent)
6961    // the count is 1.
6962    let empty_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
6963        .iter()
6964        .copied()
6965        .filter(|k| empty.lacks_only(*k))
6966        .count();
6967    assert!(
6968        empty_count <= 1,
6969        "empty_parent(): at most 1 kind may satisfy lacks_only, got {empty_count}",
6970    );
6971
6972    let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
6973
6974    // Single-slot sweep — the composition-law shape across
6975    // `ClosedSet::ALL × ALL`, plus a factory-precondition truth-table
6976    // pin whose expected shape is derived from the abstract factory
6977    // contract (`single_slot(populated)` populates exactly `populated`
6978    // → the missing set is `ALL - {populated}`, size `all_len - 1`).
6979    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6980        .iter()
6981        .copied()
6982    {
6983        let parent = single_slot(populated);
6984        for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
6985            .iter()
6986            .copied()
6987        {
6988            let via_lacks_only = parent.lacks_only(probed);
6989            // Factory-precondition truth table on the well-formed
6990            // single-slot arm: the missing set is `ALL - {populated}`,
6991            // so lacks_only(probed) is `true` iff exactly one slot is
6992            // missing (`all_len == 2`) AND probed names that missing
6993            // slot (`probed != populated`). This hard-codes the well-
6994            // formed diagonal expectation so a factory drift that
6995            // populates the wrong kind — or an empty parent, or the
6996            // saturated parent — surfaces here BEFORE any composition
6997            // law reconciles two internally-drifted trait bodies.
6998            let expected_single = all_len == 2 && probed != populated;
6999            assert_eq!(
7000                via_lacks_only, expected_single,
7001                "single_slot({populated:?}).lacks_only({probed:?}) must equal {expected_single} on ALL.len() == {all_len}",
7002            );
7003            // Widened uniqueness composition law — the primary
7004            // pin-point on the missing axis.
7005            assert_eq!(
7006                via_lacks_only,
7007                parent.unique_missing_kind() == Some(probed),
7008                "single_slot({populated:?}).lacks_only({probed:?}) drifted from (unique_missing_kind() == Some({probed:?}))",
7009            );
7010            // Cardinality-refinement composition law under complement.
7011            assert_eq!(
7012                via_lacks_only,
7013                !parent.has(probed) && parent.has_unique_missing_kind(),
7014                "single_slot({populated:?}).lacks_only({probed:?}) drifted from (!has({probed:?}) && has_unique_missing_kind())",
7015            );
7016            // Kind-scoped implication law under complement —
7017            // lacks_only implies !has.
7018            if via_lacks_only {
7019                assert!(
7020                    !parent.has(probed),
7021                    "single_slot({populated:?}).lacks_only({probed:?}) == true but has({probed:?}) == true",
7022                );
7023            }
7024        }
7025        // Kind-domain exhaustivity on the well-formed arm — at most 1
7026        // kind satisfies lacks_only. On `ALL.len() == 2` the count is
7027        // exactly 1 (the non-populated kind); on `ALL.len() >= 3` the
7028        // count is 0.
7029        let well_formed_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
7030            .iter()
7031            .copied()
7032            .filter(|k| parent.lacks_only(*k))
7033            .count();
7034        let expected_well_formed_count = usize::from(all_len == 2);
7035        assert_eq!(
7036            well_formed_count, expected_well_formed_count,
7037            "single_slot({populated:?}): exactly {expected_well_formed_count} kinds must satisfy lacks_only on ALL.len() == {all_len}, got {well_formed_count}",
7038        );
7039    }
7040
7041    // Two-slot sweep — every off-diagonal pair populates two slots, so
7042    // the missing set is `ALL - {a, b}`, size `all_len - 2`. On
7043    // `ALL.len() == 3` exactly 1 slot is missing (the third kind), so
7044    // exactly 1 kind satisfies lacks_only. On `ALL.len() >= 4` ≥ 2
7045    // slots are missing, so no kind satisfies lacks_only. The
7046    // composition-law shape binds every regime; the factory-
7047    // precondition truth-table pin catches drift like a saturated /
7048    // empty / single-slot two_slot factory that would otherwise slip
7049    // past the internally-consistent composition laws.
7050    for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7051        .iter()
7052        .copied()
7053    {
7054        for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7055            .iter()
7056            .copied()
7057        {
7058            if a == b {
7059                continue;
7060            }
7061            let parent = two_slot(a, b);
7062            for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7063                .iter()
7064                .copied()
7065            {
7066                let via_lacks_only = parent.lacks_only(k);
7067                // Factory-precondition truth table on the two-slot
7068                // arm: the missing set is `ALL - {a, b}`, so
7069                // lacks_only(k) is `true` iff exactly one slot is
7070                // missing (`all_len == 3`) AND k names that missing
7071                // slot (`k != a && k != b`).
7072                let expected_two = all_len == 3 && k != a && k != b;
7073                assert_eq!(
7074                    via_lacks_only, expected_two,
7075                    "two_slot({a:?}, {b:?}).lacks_only({k:?}) must equal {expected_two} on ALL.len() == {all_len}",
7076                );
7077                // Widened uniqueness composition law on the multi-
7078                // populated arm.
7079                assert_eq!(
7080                    via_lacks_only,
7081                    parent.unique_missing_kind() == Some(k),
7082                    "two_slot({a:?}, {b:?}).lacks_only({k:?}) drifted from (unique_missing_kind() == Some({k:?}))",
7083                );
7084                // Cardinality-refinement composition law under
7085                // complement.
7086                assert_eq!(
7087                    via_lacks_only,
7088                    !parent.has(k) && parent.has_unique_missing_kind(),
7089                    "two_slot({a:?}, {b:?}).lacks_only({k:?}) drifted from (!has({k:?}) && has_unique_missing_kind())",
7090                );
7091                // Kind-scoped implication law under complement.
7092                if via_lacks_only {
7093                    assert!(
7094                        !parent.has(k),
7095                        "two_slot({a:?}, {b:?}).lacks_only({k:?}) == true but has({k:?}) == true",
7096                    );
7097                }
7098            }
7099            // Kind-domain exhaustivity on the multi-populated arm — at
7100            // most 1 kind is the sole missing kind. On `ALL.len() ==
7101            // 3` the count is exactly 1 (the third kind); on
7102            // `ALL.len() >= 4` the count is 0.
7103            let multi_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
7104                .iter()
7105                .copied()
7106                .filter(|k| parent.lacks_only(*k))
7107                .count();
7108            let expected_multi_count = usize::from(all_len == 3);
7109            assert_eq!(
7110                multi_count, expected_multi_count,
7111                "two_slot({a:?}, {b:?}): exactly {expected_multi_count} kinds must satisfy lacks_only on ALL.len() == {all_len}, got {multi_count}",
7112            );
7113        }
7114    }
7115}
7116
7117/// Generic closed-set-complement testkit on the kind-scoped SUBSET
7118/// axis — pins that [`TaggedUnion::lacks`] agrees with the negated
7119/// [`TaggedUnion::has`], the missing-set membership projection
7120/// [`TaggedUnion::missing_kinds`], the kind-scoped strict-refinement
7121/// peer [`TaggedUnion::lacks_only`], AND the missing-axis cardinality
7122/// scalar [`TaggedUnion::missing_kind_count`] across every
7123/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
7124/// arrangement, every off-diagonal two-slot pair, AND the empty-
7125/// parent baseline.
7126///
7127/// Closed-set-complement mirror of [`TaggedUnion::has`] under the
7128/// (populated, missing) duality — where `has(kind)` is the populated-
7129/// axis SUBSET primitive, `lacks(kind)` is the missing-axis SUBSET
7130/// primitive. Together with [`TaggedUnion::has_only`] (populated-axis
7131/// EQUAL) and [`TaggedUnion::lacks_only`] (missing-axis EQUAL) they
7132/// close the 2×2 kind-scoped (populated, missing) × (subset, equal)
7133/// grid. The five sub-assertions swept per arrangement + the empty-
7134/// parent baseline:
7135///
7136/// 1. **Definitional complement law**: `lacks(kind) == !has(kind)`
7137///    on every arm — the trait's default body composition is a
7138///    single bit-flip past [`TaggedUnion::has`], and no override
7139///    may drift the two primitives apart.
7140/// 2. **Missing-set membership composition law**:
7141///    `lacks(kind) == missing_kinds().contains(&kind)` on every
7142///    arm — closed-set-complement peer of the populated-axis law
7143///    `has(kind) == populated_kinds().contains(&kind)` swept by
7144///    [`assert_populated_kinds_matches_has`].
7145/// 3. **Kind-scoped implication law**: `lacks_only(kind) →
7146///    lacks(kind)` on every arm — if `kind` is the SOLE missing
7147///    slot then `kind` is missing. Byte-for-byte missing-axis peer
7148///    of the `has_only(kind) → has(kind)` implication that binds
7149///    [`TaggedUnion::has_only`] to [`TaggedUnion::has`] on the
7150///    strict-refinement axis.
7151/// 4. **Cardinality-partition law**: `<T::Kind as ClosedSet>::ALL
7152///    .iter().filter(|k| parent.lacks(*k)).count() ==
7153///    parent.missing_kind_count()` on every arm — the count of
7154///    kinds satisfying `lacks` equals the parent's missing-slot
7155///    count. Closed-set-complement peer of the populated-axis law
7156///    `count k where has(k) == populated_kind_count()`.
7157/// 5. **Factory-precondition truth table** whose expected shape is
7158///    derived from the abstract factory contract (`empty_parent()`
7159///    missing set is all of `ALL`, size `all_len`;
7160///    `single_slot(populated)` missing set is `ALL - {populated}`,
7161///    size `all_len - 1`; `two_slot(a, b)` missing set is `ALL -
7162///    {a, b}`, size `all_len - 2`) — hard-codes the arm expectation
7163///    across every `ALL.len()` regime so a factory drift that
7164///    yields a saturated / drifted parent surfaces BEFORE any
7165///    composition law reconciles two internally-drifted trait
7166///    bodies.
7167///
7168/// A fifth sibling tagged-union parent picks up the closed-set-
7169/// complement check on the kind-scoped SUBSET axis through ONE
7170/// `impl TaggedUnion for X` block plus ONE per-site `single_slot_X`
7171/// factory plus ONE per-site `two_slot_X` factory plus ONE per-site
7172/// `empty_X` factory plus ONE call site — no re-authored `lacks`
7173/// sweep at the test surface.
7174///
7175/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
7176/// primitives — the `T: TaggedUnion` bound doesn't reach it.
7177///
7178/// # Theory grounding
7179///
7180/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
7181///   The kind-scoped closed-set-complement projection lives at ONE
7182///   substrate site as a definitional negation of
7183///   [`TaggedUnion::has`]. The five composition laws (definitional
7184///   complement, missing-set membership, kind-scoped implication
7185///   from `lacks_only`, cardinality partition against
7186///   `missing_kind_count`, factory-precondition truth table) live at
7187///   ONE substrate site inside the testkit's per-arm sweep — pinned
7188///   across every production tagged union at compile time via the
7189///   trait's default body composition, not per-parent.
7190/// - THEORY.md §VI.1 — generation over composition. A new
7191///   [`Self::Kind`] variant added to `ALL` reaches this primitive
7192///   mechanically through the delegated [`Self::has`] — the five
7193///   laws hold on the widened kind set without further per-caller
7194///   edit.
7195#[track_caller]
7196pub fn assert_lacks_matches_has_complement<T, F, G, H>(single_slot: F, two_slot: G, empty_parent: H)
7197where
7198    T: TaggedUnion,
7199    T::Kind: PartialEq + std::fmt::Debug,
7200    F: Fn(T::Kind) -> T,
7201    G: Fn(T::Kind, T::Kind) -> T,
7202    H: Fn() -> T,
7203{
7204    let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
7205
7206    // Empty-parent baseline — every `lacks(k)` returns `true`
7207    // (empty parent has every slot missing). The factory-
7208    // precondition truth-table pin catches an `empty_parent` that
7209    // drifts from empty (a single-slot or saturated factory
7210    // masquerading as empty) BEFORE any composition law reconciles
7211    // two internally-drifted trait bodies.
7212    let empty = empty_parent();
7213    assert!(
7214        empty.is_empty(),
7215        "TaggedUnion::lacks() testkit: empty_parent() must satisfy is_empty() == true",
7216    );
7217    let empty_missing_count = empty.missing_kind_count();
7218    for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7219        .iter()
7220        .copied()
7221    {
7222        let via_lacks = empty.lacks(k);
7223        // Factory-precondition truth table on the empty arm: the
7224        // missing set is all of `ALL`, so `lacks(k) == true` for
7225        // every `k`.
7226        assert!(
7227            via_lacks,
7228            "empty_parent().lacks({k:?}) must equal true (empty parent has every slot missing)",
7229        );
7230        // Definitional complement law on the empty arm.
7231        assert_eq!(
7232            via_lacks,
7233            !empty.has(k),
7234            "empty_parent().lacks({k:?}) drifted from !has({k:?})",
7235        );
7236        // Missing-set membership composition law on the empty arm.
7237        assert_eq!(
7238            via_lacks,
7239            empty.missing_kinds().contains(&k),
7240            "empty_parent().lacks({k:?}) drifted from missing_kinds().contains(&{k:?})",
7241        );
7242        // Kind-scoped implication law on the empty arm — lacks_only
7243        // implies lacks. On any `ALL.len() >= 2` closed set the
7244        // empty parent has ≥ 2 missing so lacks_only(k) == false on
7245        // every k, and the implication is vacuously true; on the
7246        // degenerate `ALL.len() == 1` regime lacks_only(k) == true
7247        // on the sole k, and the implication holds because lacks(k)
7248        // == true too.
7249        if empty.lacks_only(k) {
7250            assert!(
7251                via_lacks,
7252                "empty_parent().lacks_only({k:?}) == true but lacks({k:?}) == false",
7253            );
7254        }
7255    }
7256    // Cardinality-partition law on the empty arm — every kind
7257    // satisfies lacks, so the count equals missing_kind_count()
7258    // which equals ALL.len().
7259    let empty_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
7260        .iter()
7261        .copied()
7262        .filter(|k| empty.lacks(*k))
7263        .count();
7264    assert_eq!(
7265        empty_count, empty_missing_count,
7266        "empty_parent(): count of kinds satisfying lacks ({empty_count}) drifted from missing_kind_count() ({empty_missing_count})",
7267    );
7268    assert_eq!(
7269        empty_count, all_len,
7270        "empty_parent(): count of kinds satisfying lacks must equal ALL.len() ({all_len}), got {empty_count}",
7271    );
7272
7273    // Single-slot sweep — the composition-law shape across
7274    // `ClosedSet::ALL × ALL`, plus a factory-precondition truth-
7275    // table pin whose expected shape is derived from the abstract
7276    // factory contract (`single_slot(populated)` populates exactly
7277    // `populated` → the missing set is `ALL - {populated}`, so
7278    // `lacks(probed) == true` iff `probed != populated`).
7279    for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7280        .iter()
7281        .copied()
7282    {
7283        let parent = single_slot(populated);
7284        let parent_missing_count = parent.missing_kind_count();
7285        for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7286            .iter()
7287            .copied()
7288        {
7289            let via_lacks = parent.lacks(probed);
7290            // Factory-precondition truth table on the well-formed
7291            // single-slot arm.
7292            let expected_single = probed != populated;
7293            assert_eq!(
7294                via_lacks, expected_single,
7295                "single_slot({populated:?}).lacks({probed:?}) must equal {expected_single}",
7296            );
7297            // Definitional complement law.
7298            assert_eq!(
7299                via_lacks,
7300                !parent.has(probed),
7301                "single_slot({populated:?}).lacks({probed:?}) drifted from !has({probed:?})",
7302            );
7303            // Missing-set membership composition law.
7304            assert_eq!(
7305                via_lacks,
7306                parent.missing_kinds().contains(&probed),
7307                "single_slot({populated:?}).lacks({probed:?}) drifted from missing_kinds().contains(&{probed:?})",
7308            );
7309            // Kind-scoped implication law — lacks_only implies
7310            // lacks.
7311            if parent.lacks_only(probed) {
7312                assert!(
7313                    via_lacks,
7314                    "single_slot({populated:?}).lacks_only({probed:?}) == true but lacks({probed:?}) == false",
7315                );
7316            }
7317        }
7318        // Cardinality-partition law on the well-formed arm — the
7319        // count of kinds satisfying lacks equals
7320        // missing_kind_count() which equals ALL.len() - 1.
7321        let well_formed_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
7322            .iter()
7323            .copied()
7324            .filter(|k| parent.lacks(*k))
7325            .count();
7326        assert_eq!(
7327            well_formed_count, parent_missing_count,
7328            "single_slot({populated:?}): count of kinds satisfying lacks ({well_formed_count}) drifted from missing_kind_count() ({parent_missing_count})",
7329        );
7330        let expected_single_missing = all_len - 1;
7331        assert_eq!(
7332            well_formed_count, expected_single_missing,
7333            "single_slot({populated:?}): count of kinds satisfying lacks must equal ALL.len() - 1 ({expected_single_missing}), got {well_formed_count}",
7334        );
7335    }
7336
7337    // Two-slot sweep — every off-diagonal pair populates two slots,
7338    // so the missing set is `ALL - {a, b}`, size `all_len - 2`, and
7339    // `lacks(k) == true` iff `k != a && k != b`. On `ALL.len() == 2`
7340    // `all_len - 2 == 0` (the two-slot arm saturates), so `lacks(k)
7341    // == false` on every k; the composition-law shape binds every
7342    // regime.
7343    for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7344        .iter()
7345        .copied()
7346    {
7347        for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7348            .iter()
7349            .copied()
7350        {
7351            if a == b {
7352                continue;
7353            }
7354            let parent = two_slot(a, b);
7355            let parent_missing_count = parent.missing_kind_count();
7356            for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7357                .iter()
7358                .copied()
7359            {
7360                let via_lacks = parent.lacks(k);
7361                // Factory-precondition truth table on the two-slot
7362                // arm.
7363                let expected_two = k != a && k != b;
7364                assert_eq!(
7365                    via_lacks, expected_two,
7366                    "two_slot({a:?}, {b:?}).lacks({k:?}) must equal {expected_two}",
7367                );
7368                // Definitional complement law.
7369                assert_eq!(
7370                    via_lacks,
7371                    !parent.has(k),
7372                    "two_slot({a:?}, {b:?}).lacks({k:?}) drifted from !has({k:?})",
7373                );
7374                // Missing-set membership composition law.
7375                assert_eq!(
7376                    via_lacks,
7377                    parent.missing_kinds().contains(&k),
7378                    "two_slot({a:?}, {b:?}).lacks({k:?}) drifted from missing_kinds().contains(&{k:?})",
7379                );
7380                // Kind-scoped implication law.
7381                if parent.lacks_only(k) {
7382                    assert!(
7383                        via_lacks,
7384                        "two_slot({a:?}, {b:?}).lacks_only({k:?}) == true but lacks({k:?}) == false",
7385                    );
7386                }
7387            }
7388            // Cardinality-partition law on the two-slot arm.
7389            let multi_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
7390                .iter()
7391                .copied()
7392                .filter(|k| parent.lacks(*k))
7393                .count();
7394            assert_eq!(
7395                multi_count, parent_missing_count,
7396                "two_slot({a:?}, {b:?}): count of kinds satisfying lacks ({multi_count}) drifted from missing_kind_count() ({parent_missing_count})",
7397            );
7398            let expected_two_missing = all_len - 2;
7399            assert_eq!(
7400                multi_count, expected_two_missing,
7401                "two_slot({a:?}, {b:?}): count of kinds satisfying lacks must equal ALL.len() - 2 ({expected_two_missing}), got {multi_count}",
7402            );
7403        }
7404    }
7405}
7406
7407/// Generic ambiguity testkit — pins that [`TaggedUnion::variant`]
7408/// resolves to [`TaggedUnionError::ambiguous`] on EVERY off-diagonal
7409/// `(a, b)` pair in [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
7410/// `× ALL`.
7411///
7412/// Substrate primitive for the sibling
7413/// `_two_slots_is_ambiguous_across_every_pair` tests on `ProcessSpec`
7414/// ([`crate::encapsulates::EncapsulationKind`],
7415/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
7416/// that pre-lift each restated the same nested-`for a in K::ALL { for
7417/// b in K::ALL { if a == b { continue; } … } }` sweep at their own
7418/// test bodies — byte-identical projections whose only per-carrier
7419/// knobs are the (Kind type + the `two_slot_X(a, b) -> Parent`
7420/// two-slot factory) pair. Post-lift each site collapses to ONE
7421/// `assert_two_slots_ambiguous::<Xxx, _>(two_slot_X)` invocation.
7422///
7423/// The `two_slot` closure stays per-site — every one of the three
7424/// production sites already owns a `two_slot_kind /
7425/// two_slot_source / two_slot_channel` helper that composes two
7426/// `single_slot_X`s per-field. The closure IS the "populate both
7427/// slots a and b" ground truth for the carrier's field structure;
7428/// lifting it into the primitive would collapse per-site field-
7429/// composition knowledge that stays deliberately local.
7430///
7431/// The pair sweep excludes the diagonal (`a == b`) — a single slot
7432/// populated is exactly-one, not many, and the round-trip primitive
7433/// [`assert_variant_round_trip`] already pins that populated slot's
7434/// resolution. This primitive is the peer contract for the Many arm.
7435///
7436/// A fifth sibling tagged-union parent picks up the ambiguity check
7437/// through ONE `impl TaggedUnion for X` block + ONE per-site
7438/// `two_slot_X` helper + ONE `assert_two_slots_ambiguous::<X, _>`
7439/// call site — no re-authored nested-for sweep at the test surface,
7440/// no re-authored `assert_eq!(..., X::Error::Ambiguous, ...)` arm.
7441///
7442/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
7443/// — `Lifetime` doesn't impl [`TaggedUnion`] (its error carrier has
7444/// no `Empty` arm; its `variant()` returns `Ok(Permanent)` on empty
7445/// rather than an `Empty` typed error), so the `<T: TaggedUnion>`
7446/// bound doesn't reach it. Its per-site ambiguity assertion binds
7447/// through the inherent `.variant()` + hand-authored two-slot
7448/// probe. Same reasoning as [`resolve_or_err`]'s and
7449/// [`assert_variant_round_trip`]'s exclusions.
7450#[track_caller]
7451pub fn assert_two_slots_ambiguous<T, F>(two_slot: F)
7452where
7453    T: TaggedUnion,
7454    T::Kind: PartialEq + std::fmt::Debug,
7455    T::Error: PartialEq + std::fmt::Debug,
7456    F: Fn(T::Kind, T::Kind) -> T,
7457{
7458    let expected = T::Error::ambiguous();
7459    for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7460        .iter()
7461        .copied()
7462    {
7463        for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
7464            .iter()
7465            .copied()
7466        {
7467            if a == b {
7468                continue;
7469            }
7470            let parent = two_slot(a, b);
7471            let err = parent.variant().err().unwrap_or_else(|| {
7472                panic!("({a:?}, {b:?}) two-slot parent must not resolve to a variant")
7473            });
7474            assert_eq!(err, expected, "({a:?}, {b:?}) should resolve Ambiguous");
7475        }
7476    }
7477}
7478
7479/// Generic wire-key / kind-label alignment testkit — pins that every
7480/// single-slot parent serializes to a JSON object with EXACTLY ONE key
7481/// whose name equals `<T::Kind as tatara_closed_set::ClosedSet>::label`
7482/// on the populated slot's kind.
7483///
7484/// Substrate primitive for the four sibling
7485/// `X_kind_as_str_matches_field_name` / `intent_kind_as_str_matches_intent_field_name`
7486/// tests on `ProcessSpec` ([`crate::intent::Intent`],
7487/// [`crate::encapsulates::EncapsulationKind`],
7488/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
7489/// that pre-lift each restated the same wire-format sweep at their own
7490/// test bodies:
7491///
7492/// 1. For each `k in K::ALL`, construct a single-slot parent via
7493///    the site-local `single_slot_X(k) -> Parent` factory.
7494/// 2. Serialize it to the wire format and assert that the emitted
7495///    key matches `k.as_str()`.
7496///
7497/// Post-lift each site's alignment test collapses to ONE
7498/// `assert_single_slot_key_matches_label::<T, _>(single_slot_X)`
7499/// invocation whose body IS the substrate primitive's own dispatch.
7500/// A fifth sibling picks up the alignment check through ONE call site.
7501///
7502/// The primitive projects through `serde_json::to_value` rather than
7503/// `serde_yaml::to_string` for two reasons: (1) the check is
7504/// structural (exactly-one-key + name equality), not textual (substring
7505/// against a `"{key}:"` YAML fragment), so a future site that gains
7506/// non-tagged-union metadata fields is caught HERE at the exactly-one
7507/// arm — the YAML-substring check the three encapsulates / export sites
7508/// carried pre-lift would silently pass on such drift. (2) serde's
7509/// field-rename projection (`rename_all = "camelCase"`) is format-
7510/// agnostic, so a JSON check pins the SAME invariant a YAML check
7511/// would pin, byte-identically. Every one of the four production
7512/// parents already emits exactly one key on a single-slot populate —
7513/// their `#[serde(default, skip_serializing_if = "Option::is_none")]`
7514/// annotations on every tagged-union slot guarantee it — so upgrading
7515/// the three YAML sites to the JSON exactly-one check is a strict
7516/// strengthening.
7517///
7518/// The `single_slot` closure stays per-site — every one of the four
7519/// production sites already owns a `single_slot_intent /
7520/// single_slot_kind / single_slot_source / single_slot_channel` helper
7521/// that constructs a minimally-valid parent with the addressed slot's
7522/// inner spec populated; the closure IS the "populate slot k" ground
7523/// truth for the carrier's field structure. Reused verbatim from the
7524/// [`assert_variant_round_trip`] primitive.
7525///
7526/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
7527/// from THIS trait-projected surface — `Lifetime` doesn't impl
7528/// [`TaggedUnion`] (its `variant()` returns `Ok(Permanent)` on empty
7529/// rather than an `Empty` typed error), so the `<T: TaggedUnion>`
7530/// bound doesn't reach it. The bound-relaxed peer
7531/// [`assert_wire_key_matches_label`] carries the SAME sweep body
7532/// under `<T: Serialize>` + `<K: ClosedSet>` alone — Lifetime binds
7533/// through it directly and this trait-projected surface becomes a
7534/// one-line delegation whose only load-bearing purpose is to name
7535/// the TaggedUnion parent's `T::Kind` associated type at the call
7536/// site (existing `assert_single_slot_key_matches_label::<T, _>(f)`
7537/// callers stay unchanged; the peer inflects the same body onto
7538/// non-TaggedUnion parents).
7539#[track_caller]
7540pub fn assert_single_slot_key_matches_label<T, F>(single_slot: F)
7541where
7542    T: TaggedUnion + serde::Serialize,
7543    T::Kind: PartialEq + std::fmt::Debug,
7544    F: Fn(T::Kind) -> T,
7545{
7546    assert_wire_key_matches_label::<T, T::Kind, F>(single_slot);
7547}
7548
7549/// Bound-relaxed peer of [`assert_single_slot_key_matches_label`] —
7550/// the SAME wire-key alignment sweep, but on any `(K, T)` pair where
7551/// `K: ClosedSet` addresses `T: Serialize` through a caller-supplied
7552/// `single_slot: Fn(K) -> T` factory. Drops the `T: TaggedUnion`
7553/// bound the sibling primitive carries so parents whose empty
7554/// resolution shape diverges from the tagged-union convention (the
7555/// canonical example: [`crate::lifetime::Lifetime`], whose empty
7556/// resolves to `Permanent(&DEFAULT_PERMANENT)` rather than to an
7557/// [`TaggedUnionError::empty`] carrier) still bind through ONE
7558/// substrate wire-key alignment site.
7559///
7560/// The two primitives share ONE sweep body; the trait-projected
7561/// [`assert_single_slot_key_matches_label`] is now a one-line
7562/// delegation to this bound-relaxed peer, so every drift-arm the
7563/// sibling `#[should_panic]` probe pins on the delegating surface
7564/// mechanically pins here too. The compounding gain: a fifth parent
7565/// whose closed-set kind K doesn't ride the TaggedUnion trait (a
7566/// future variant surface with a default-arm on empty; a wire-only
7567/// enum whose parent is a wrapper struct that never publishes a
7568/// resolver; a K-addressed `HashMap<K, Payload>` where the payload
7569/// isn't a tagged-union variant carrier at all) picks up wire-key
7570/// alignment through ONE call site — no re-authored serialize +
7571/// exactly-one-key + name-equality body at the test surface, no
7572/// per-parent drift risk where the trait-projected surface catches
7573/// it and the bespoke surface forgets.
7574///
7575/// The primitive binds `<K: ClosedSet + PartialEq + Debug>` (the
7576/// strict union of the sweep body's projection + the panic-message
7577/// substrate-wide shape) — every production `ClosedSet` implementor
7578/// across the crate carries `Debug + PartialEq` through the
7579/// substrate-wide `#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash,
7580/// DeriveClosedSet)]` shape, so no site pays a bound-widening cost
7581/// to bind through this peer.
7582#[track_caller]
7583pub fn assert_wire_key_matches_label<T, K, F>(single_slot: F)
7584where
7585    T: serde::Serialize,
7586    K: tatara_closed_set::ClosedSet + PartialEq + std::fmt::Debug,
7587    F: Fn(K) -> T,
7588{
7589    for k in <K as tatara_closed_set::ClosedSet>::ALL.iter().copied() {
7590        let parent = single_slot(k);
7591        let value = serde_json::to_value(&parent)
7592            .unwrap_or_else(|e| panic!("single_slot({k:?}) must serialize as JSON: {e}"));
7593        let obj = value.as_object().unwrap_or_else(|| {
7594            panic!("single_slot({k:?}) must serialize to a JSON object, got {value}")
7595        });
7596        let keys: Vec<&String> = obj.keys().collect();
7597        assert_eq!(
7598            keys.len(),
7599            1,
7600            "single_slot({k:?}) must serialize to exactly one populated field, got keys: {keys:?}",
7601        );
7602        let expected = <K as tatara_closed_set::ClosedSet>::label(k);
7603        assert_eq!(
7604            keys[0].as_str(),
7605            expected,
7606            "wire-key drift for {k:?}: single_slot's populated field '{}' must equal <K as ClosedSet>::label ({expected:?})",
7607            keys[0],
7608        );
7609    }
7610}
7611
7612/// Generic Display / [`ClosedSet::label`](tatara_closed_set::ClosedSet::label)
7613/// alignment testkit — pins that [`core::fmt::Display`] renders each variant
7614/// BYTE-IDENTICALLY to the trait-visible `ClosedSet::label` projection for
7615/// every implementor.
7616///
7617/// Substrate primitive for the 29 sibling
7618/// `X_display_matches_as_str` tests across `tatara-process`
7619/// (`AllocationPhase`, `IntentKind`, `WorkloadKind`, `EncapsulationMode`,
7620/// `EncapsulationTarget`, `ConditionKind`, `TerminateReasonKind`,
7621/// `AutoTerminateKind`, `SighupStrategy`, `ReplacementPolicy`,
7622/// `ReturnPolicy`, `MemberState`, `PoolPhase`, `VerificationPhase`,
7623/// `SelectStrategyKind`, `MustReachPhase`, `ExportTrigger`,
7624/// `ReportFormat`, `ReportPayloadShape`, `ArtifactKind`, `ChannelKind`,
7625/// `DataClassification`, `ConvergencePointType`, `Arity`,
7626/// `SubstrateType`, `CalmClassification`, `OptimizationDirection`,
7627/// `HorizonKind`, `TeardownPolicy`) that pre-lift each restated the
7628/// same
7629/// ```text
7630/// for v in K::ALL {
7631///     assert_eq!(v.to_string(), v.as_str());
7632/// }
7633/// ```
7634/// two-line probe verbatim at their own test bodies — byte-identical
7635/// projections whose only per-carrier knob is the closed-set type name.
7636/// Post-lift each site collapses to ONE
7637/// `assert_display_matches_label::<X>()` invocation whose body IS the
7638/// substrate primitive's own dispatch.
7639///
7640/// The primitive projects through the STABLE trait-visible name
7641/// [`ClosedSet::label`](tatara_closed_set::ClosedSet::label) rather
7642/// than the inherent `.as_str()` each site publishes locally. Every
7643/// production implementor here derives its `label` body from `as_str`
7644/// via `#[closed_set(via = "as_str", display)]` (the substrate-wide
7645/// derive shape), so the two are byte-identical by construction; the
7646/// primitive's projection through `label` therefore pins the SAME
7647/// invariant the pre-lift bodies pinned while binding to the
7648/// stable trait-visible surface. A future implementor whose inherent
7649/// canonical projection is named something other than `as_str` (e.g.
7650/// `.keyword()`, `.spelling()`) but still routes through
7651/// `#[closed_set(via = "...", display)]` picks up the alignment check
7652/// through ONE `assert_display_matches_label::<X>()` invocation with
7653/// no inherent-name coupling at the test site.
7654///
7655/// A fifth (or thirtieth, or hundredth) implementor picks up the
7656/// Display-alignment check through ONE
7657/// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `display`
7658/// attribute + ONE `assert_display_matches_label::<X>()` call site —
7659/// no re-authored two-line
7660/// `for v in K::ALL { assert_eq!(v.to_string(), v.as_str()) }` body
7661/// at the test surface, no per-site drift risk where 28 sibling
7662/// tests carry the assertion and the 29th forgets.
7663///
7664/// Sibling shape to [`assert_kind_list_matches_closed_set`] on the
7665/// (`T::KIND_LIST` slash-join, `Display` byte-identity) axis: both
7666/// project the closed-set's label surface onto ONE typed contract
7667/// and pin it against a per-implementor rendering; the former for
7668/// the tagged-union parent's [`TaggedUnion::KIND_LIST`] `&'static str`,
7669/// this one for the enum's `Display` byte stream. Together they close
7670/// the "label surface must round-trip verbatim" invariant every
7671/// closed-set-carrying implementor across the crate publishes.
7672#[track_caller]
7673pub fn assert_display_matches_label<T>()
7674where
7675    T: tatara_closed_set::ClosedSet + core::fmt::Display + PartialEq + core::fmt::Debug,
7676{
7677    let type_name = core::any::type_name::<T>();
7678    for &v in <T as tatara_closed_set::ClosedSet>::ALL {
7679        let rendered = v.to_string();
7680        let expected = <T as tatara_closed_set::ClosedSet>::label(v);
7681        assert_eq!(
7682            rendered.as_str(),
7683            expected,
7684            "{type_name}: Display drifted from ClosedSet::label for {v:?} — expected {expected:?}, got {rendered:?}",
7685        );
7686    }
7687}
7688
7689/// CANONICAL-KEY CONTRACT testkit — pins that each variant's serde
7690/// serialization (as a JSON string value, unquoted) matches its
7691/// canonical [`ClosedSet::label`](tatara_closed_set::ClosedSet::label)
7692/// projection BYTE-IDENTICALLY for every implementor.
7693///
7694/// Substrate primitive for the 20 sibling
7695/// `X_as_str_matches_serde` tests across `tatara-process`
7696/// (`TeardownPolicy`, `EncapsulationMode`, `ConditionKind`,
7697/// `SighupStrategy`, `ReplacementPolicy`, `ReturnPolicy`, `MemberState`,
7698/// `PoolPhase`, `VerificationPhase`, `MustReachPhase`, `WorkloadKind`,
7699/// `ExportTrigger`, `ReportFormat`, `DataClassification`,
7700/// `ConvergencePointType`, `SubstrateType`, `CalmClassification`,
7701/// `OptimizationDirection`, `HorizonKind`, `AllocationPhase`) that
7702/// pre-lift each restated the same
7703/// ```text
7704/// for v in K::ALL {
7705///     let serialized = serde_json::to_string(&v).expect("serialize");
7706///     let unquoted = serialized
7707///         .trim_start_matches('"')
7708///         .trim_end_matches('"')
7709///         .to_string();
7710///     assert_eq!(unquoted, v.as_str(), "as_str drift for {v:?}: ...");
7711/// }
7712/// ```
7713/// four-line probe verbatim at their own test bodies — byte-identical
7714/// projections whose only per-carrier knob is the closed-set type name.
7715/// Post-lift each site collapses to ONE
7716/// `assert_label_matches_serde_serialization::<X>()` invocation whose
7717/// body IS the substrate primitive's own dispatch.
7718///
7719/// The primitive projects through the STABLE trait-visible name
7720/// [`ClosedSet::label`](tatara_closed_set::ClosedSet::label) rather
7721/// than the inherent `.as_str()` each site publishes locally. Every
7722/// production implementor here derives its `label` body from `as_str`
7723/// via `#[closed_set(via = "as_str", display)]` + `#[serde(rename_all
7724/// = "PascalCase")]` (the substrate-wide derive shape), so the two are
7725/// byte-identical by construction; the primitive's projection through
7726/// `label` therefore pins the SAME invariant the pre-lift bodies
7727/// pinned while binding to the stable trait-visible surface. A future
7728/// implementor whose canonical inherent projection is named something
7729/// other than `as_str` (e.g. `.keyword()`, `.spelling()`) but still
7730/// routes through `#[closed_set(via = "...")]` picks up the wire-format
7731/// alignment check through ONE call with no inherent-name coupling at
7732/// the test site.
7733///
7734/// A twenty-first (or hundredth) implementor picks up the alignment
7735/// check through ONE `#[derive(tatara_closed_set::DeriveClosedSet)]` +
7736/// `#[derive(serde::Serialize)]` + `#[serde(rename_all = "...")]`
7737/// attribute + ONE `assert_label_matches_serde_serialization::<X>()`
7738/// call site — no re-authored four-line probe body at the test surface,
7739/// no per-site drift risk where 19 sibling tests carry the assertion
7740/// and the 20th forgets, no `serde_json::to_string`+`trim_matches`+
7741/// `assert_eq!` composition re-derived per implementor.
7742///
7743/// Sibling shape to [`assert_display_matches_label`] on the
7744/// (Display byte-identity, serde-wire-format byte-identity) axis: both
7745/// project the closed-set's label surface onto ONE typed contract and
7746/// pin it against a per-implementor rendering; the former for the
7747/// enum's [`Display`](core::fmt::Display) byte stream, this one for
7748/// the serde JSON-string wire format. Together they close the "label
7749/// surface renders verbatim across every projection consumers reach
7750/// for" invariant every closed-set-carrying implementor across the
7751/// crate publishes.
7752#[track_caller]
7753pub fn assert_label_matches_serde_serialization<T>()
7754where
7755    T: tatara_closed_set::ClosedSet + serde::Serialize + core::fmt::Debug,
7756{
7757    let type_name = core::any::type_name::<T>();
7758    for &v in <T as tatara_closed_set::ClosedSet>::ALL {
7759        let serialized = serde_json::to_string(&v).unwrap_or_else(|e| {
7760            panic!("{type_name}: closed-set variant {v:?} must serialize: {e}")
7761        });
7762        let unquoted = serialized.trim_start_matches('"').trim_end_matches('"');
7763        let expected = <T as tatara_closed_set::ClosedSet>::label(v);
7764        assert_eq!(
7765            unquoted,
7766            expected,
7767            "{type_name}: serde output drifted from ClosedSet::label for {v:?} — expected {expected:?}, got {unquoted:?} (full serialization {serialized:?})",
7768        );
7769    }
7770}
7771
7772/// CLOSED-SET CONVENTION PANEL testkit — pins the FULL three-axis
7773/// label-surface convention (parse round-trip, Display byte-identity,
7774/// serde-JSON-string byte-identity) at ONE substrate call site per
7775/// implementor.
7776///
7777/// Compound-lift of [`tatara_closed_set::assert_closed_set_well_formed`]
7778/// + [`assert_display_matches_label`] + [`assert_label_matches_serde_
7779/// serialization`] — every closed-set enum on `ProcessSpec` that
7780/// carries the substrate-wide `#[derive(DeriveClosedSet)] +
7781/// #[derive(Serialize)] + #[closed_set(via = "as_str", display)] +
7782/// #[serde(rename_all = "PascalCase")]` shape publishes ALL THREE
7783/// axes of the label surface, and pre-lift each production test
7784/// module hand-authored three sibling one-line tests
7785/// (`X_is_well_formed_closed_set`, `X_display_matches_as_str`,
7786/// `X_as_str_matches_serde`) that each restated the SAME
7787/// `crate::tagged_union::assert_<axis>::<X>()` invocation with only
7788/// the axis name varying between siblings. Post-lift each site
7789/// collapses to ONE `assert_closed_set_convention_panel::<X>()`
7790/// invocation whose body IS the three-axis composition dispatched
7791/// through the substrate primitive here.
7792///
7793/// The three sub-assertions stay independently callable — a future
7794/// implementor that publishes only two of the three axes (a
7795/// `Display`-less internal enum, e.g., or a `Serialize`-less
7796/// runtime-only enum) still binds through the two sibling primitives
7797/// individually. The compound is a strict superset: any implementor
7798/// that satisfies the compound's bounds already satisfies each
7799/// sub-assertion's bounds by construction, and the failure mode of
7800/// each sub-assertion still surfaces with the exact-message
7801/// granularity `#[track_caller]` gives the individual primitives
7802/// (the compound is `#[track_caller]` too, so a sub-assertion panic
7803/// surfaces at the compound's call site — a future promotion could
7804/// wrap each sub-assertion in a `std::panic::catch_unwind` to
7805/// aggregate all three axis failures into ONE panic message, but the
7806/// pre-lift discipline is that each axis's failure surfaces with its
7807/// own diagnostic).
7808///
7809/// The compound's bounds are the strict union of the three sub-
7810/// assertions' bounds:
7811///   - [`assert_closed_set_well_formed`] requires
7812///     `T: ClosedSet + PartialEq + Debug` + `T::Unknown: Display`;
7813///   - [`assert_display_matches_label`] requires
7814///     `T: ClosedSet + Display + PartialEq + Debug`;
7815///   - [`assert_label_matches_serde_serialization`] requires
7816///     `T: ClosedSet + Serialize + Debug`.
7817/// The union `T: ClosedSet + Serialize + Display + PartialEq + Debug`
7818/// + `T::Unknown: Display` is what every 3-axis production consumer
7819/// already satisfies through the substrate-wide derive shape — any
7820/// implementor that fails the compound's bounds would ALSO fail the
7821/// individual sub-assertions' bounds, so the compound doesn't shrink
7822/// the reachable set of implementors relative to hand-authoring the
7823/// three sibling calls.
7824///
7825/// A future FOURTH label-surface projection (e.g. a `serde_yaml`
7826/// byte-identity axis if the crate gains a YAML wire form on closed-
7827/// set enums, or a `kubectl_annotation` axis if the reconciler grows
7828/// an annotation-carried label surface) lands as ONE new
7829/// `assert_<axis>_matches_label::<T>()` substrate primitive + ONE
7830/// new line inside this compound's body. Every one of the ~20
7831/// production implementors of the panel picks up the fourth-axis
7832/// alignment check mechanically at their sole `assert_closed_set_
7833/// convention_panel::<X>()` call site — no per-implementor test-site
7834/// authoring, no per-crate test-site drop pathway where 19 sibling
7835/// call sites carry the check and the 20th forgets. The exact
7836/// promise `e4a4eba`'s future gain #2 named after
7837/// `assert_label_matches_serde_serialization` opened the wire-format
7838/// axis: a workspace-wide panel with byte-identical calling shapes
7839/// (`assert_X::<T>()`) that composes as freely as its sub-primitives.
7840///
7841/// Sibling shape to [`assert_variant_round_trip`] +
7842/// [`assert_kind_list_matches_closed_set`] +
7843/// [`assert_two_slots_ambiguous`] +
7844/// [`assert_single_slot_key_matches_label`] on the tagged-union
7845/// PARENT axis: the parent-side compound would compose the four
7846/// parent-side per-axis primitives, this one composes the three
7847/// child-side per-axis primitives on the child's [`ClosedSet`]
7848/// surface. Together the two compounds close the "closed-set
7849/// convention holds across every projection consumers reach for" at
7850/// two adjacent panels — one per closed-set-carrying enum, one per
7851/// tagged-union parent.
7852///
7853/// Theory anchor: THEORY.md §V.1 (knowable platform) — the
7854/// three-axis label-surface convention becomes ONE typed theorem
7855/// provable generically over any
7856/// `T: ClosedSet + Serialize + Display + PartialEq + Debug` bound
7857/// rather than THREE hand-authored per-implementor one-line probes
7858/// held coherent by test-module convention. THEORY.md §II.1
7859/// invariant 5 (composition preserves proofs) — the three sub-
7860/// assertions compose structurally through ONE primitive here, so a
7861/// regression at ONE axis surfaces at the sub-assertion's own
7862/// panic message rather than as silent drift at every consumer that
7863/// might otherwise forget to include the axis in its per-site
7864/// author-time enumeration.
7865#[track_caller]
7866pub fn assert_closed_set_convention_panel<T>()
7867where
7868    T: tatara_closed_set::ClosedSet
7869        + serde::Serialize
7870        + core::fmt::Display
7871        + PartialEq
7872        + core::fmt::Debug,
7873    T::Unknown: core::fmt::Display,
7874{
7875    tatara_closed_set::assert_closed_set_well_formed::<T>();
7876    assert_display_matches_label::<T>();
7877    assert_label_matches_serde_serialization::<T>();
7878}
7879
7880/// TAGGED-UNION CONVENTION PANEL testkit — pins the FULL four-axis
7881/// tagged-union parent convention (KIND_LIST diagnostic-stability,
7882/// variant round-trip on the single-slot side, ALL×ALL two-slot
7883/// ambiguity, wire-key alignment on the single-slot side) at ONE
7884/// substrate call site per parent.
7885///
7886/// Parent-side compound-lift, sibling to
7887/// [`assert_closed_set_convention_panel`] on the child's
7888/// [`tatara_closed_set::ClosedSet`] axis. Composes
7889/// [`assert_kind_list_matches_closed_set`] (no fixture) +
7890/// [`assert_variant_round_trip`] (`single_slot`) +
7891/// [`assert_two_slots_ambiguous`] (`two_slot`) +
7892/// [`assert_single_slot_key_matches_label`] (`single_slot`).
7893///
7894/// Every one of the four production `.variant()` parents on
7895/// `ProcessSpec` ([`crate::intent::Intent`],
7896/// [`crate::encapsulates::EncapsulationKind`],
7897/// [`crate::export::ArtifactSource`],
7898/// [`crate::export::VectorChannel`]) publishes the four-axis
7899/// convention through the shared substrate-wide attribute-set:
7900/// `#[derive(DeriveClosedSet)]` on the addressing `Kind`,
7901/// `declare_tagged_union_impls!` for the resolver+selector+trait
7902/// triple, `#[serde(rename_all = "camelCase")]` +
7903/// `#[serde(default, skip_serializing_if = "Option::is_none")]` on
7904/// every tagged-union slot. Pre-lift each production site
7905/// hand-authored FOUR sibling per-axis tests (`X_kind_round_trips_through_variant_kind`
7906/// / `X_kind_list_matches_ClosedSet_labels` /
7907/// `X_two_slots_are_ambiguous` /
7908/// `X_kind_as_str_matches_field_name`) that each restated the
7909/// SAME `crate::tagged_union::assert_<axis>::<T, _>(fixture)`
7910/// invocation with only the axis name + fixture arity varying
7911/// between siblings. Post-lift each site's four per-axis sibling
7912/// tests can collapse to ONE
7913/// `assert_tagged_union_convention_panel::<T, _, _>(
7914/// single_slot_X, two_slot_X)` invocation whose body IS the
7915/// four-axis composition dispatched through the substrate
7916/// primitive here.
7917///
7918/// The two closures stay per-site — every one of the four
7919/// production parents already owns a `single_slot_X(k) -> Parent`
7920/// / `two_slot_X(a, b) -> Parent` pair, and the substrate-local
7921/// `{single,two}_slot_*_probe` peers (siblings to the wire-key
7922/// sweep's substrate-local probes) let the substrate-wide sweep
7923/// below bind through the compound without reaching across the
7924/// per-crate test-module boundaries. Lifting the two closures
7925/// into the primitive would collapse the per-site construction
7926/// knowledge that stays deliberately local — the closure IS the
7927/// "populate slot k" / "populate the (a, b) pair" ground truth
7928/// for the parent's field structure.
7929///
7930/// Bounds are the strict union of the four sub-assertions' bounds:
7931/// [`assert_kind_list_matches_closed_set`] requires
7932/// `T: TaggedUnion`; [`assert_variant_round_trip`] requires
7933/// `T: TaggedUnion` + `T::Kind: PartialEq + Debug`
7934/// + `F: Fn(T::Kind) -> T`; [`assert_two_slots_ambiguous`] requires
7935/// `T: TaggedUnion` + `T::Kind: PartialEq + Debug`
7936/// + `T::Error: PartialEq + Debug` + `F: Fn(T::Kind, T::Kind) -> T`;
7937/// [`assert_single_slot_key_matches_label`] requires
7938/// `T: TaggedUnion + Serialize` + `T::Kind: PartialEq + Debug`
7939/// + `F: Fn(T::Kind) -> T`. The union
7940/// `T: TaggedUnion + Serialize` + `T::Kind: PartialEq + Debug`
7941/// + `T::Error: PartialEq + Debug` + `F1: Fn(T::Kind) -> T`
7942/// + `F2: Fn(T::Kind, T::Kind) -> T` is what every one of the four
7943/// production parents already satisfies through the shared
7944/// substrate-wide impls — any implementor that fails the compound's
7945/// bounds would ALSO fail the individual sub-assertions' bounds,
7946/// so the compound doesn't shrink the reachable set of
7947/// implementors relative to hand-authoring the four sibling calls.
7948/// The `single_slot` closure is dispatched to
7949/// [`assert_variant_round_trip`] by reference so the compound can
7950/// re-dispatch it to [`assert_single_slot_key_matches_label`] by
7951/// value on the final call — a caller passes ONE `Fn(T::Kind) -> T`
7952/// factory (not `FnOnce`) at the two axes that need it.
7953///
7954/// `#[track_caller]` on both the compound and each sub-primitive,
7955/// so a sub-assertion panic surfaces at the compound's caller site
7956/// with the failing axis's exact panic-message substring
7957/// (e.g. "TaggedUnion KIND_LIST drift", "select→variant_kind
7958/// round-trip failed", "should resolve Ambiguous", "wire-key
7959/// drift"). The four sub-assertions stay independently callable —
7960/// a future parent that publishes only three of the four axes (a
7961/// wire-format-less runtime parent, e.g., or an
7962/// ambiguity-less parent whose `.variant()` short-circuits on
7963/// the first populated slot) still binds through the sibling
7964/// primitives individually.
7965///
7966/// A future FIFTH parent-side projection (e.g. a
7967/// `two_slots_have_stable_diagnostic` axis if the ambiguity error
7968/// gains a per-parent operator-facing message, or a
7969/// `variant_kind_stays_stable_across_generation` axis if the
7970/// resolver's iteration order becomes load-bearing) lands as ONE
7971/// new `assert_<axis>::<T, _>(...)` substrate primitive + ONE new
7972/// line inside this compound's body. Every one of the four
7973/// production parents picks up the fifth-axis alignment check
7974/// mechanically at their sole
7975/// `assert_tagged_union_convention_panel::<T, _, _>(single_slot,
7976/// two_slot)` call site — no per-parent test-site authoring, no
7977/// per-crate test-site drop pathway where 3 sibling call sites
7978/// carry the check and the 4th forgets. The exact promise the
7979/// child-side [`assert_closed_set_convention_panel`] compound's
7980/// docstring named on the child axis, extended here to the parent
7981/// axis: a workspace-wide panel with byte-identical calling shapes
7982/// (`assert_<compound>::<T, _, _>(single_slot, two_slot)`) that
7983/// composes as freely as its sub-primitives.
7984///
7985/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
7986/// through the `T: TaggedUnion` bound — `Lifetime`'s `variant()`
7987/// returns `Ok(Permanent)` on empty rather than an `Empty` typed
7988/// error, so its projection shape diverges from the four
7989/// Empty-projecting parents. Same reasoning as [`resolve_or_err`]'s
7990/// / [`assert_variant_round_trip`]'s / [`assert_two_slots_ambiguous`]'s
7991/// / [`assert_single_slot_key_matches_label`]'s exclusions.
7992///
7993/// Theory anchor: THEORY.md §V.1 (knowable platform) — the
7994/// four-axis parent-side tagged-union convention becomes ONE typed
7995/// theorem provable generically over any
7996/// `T: TaggedUnion + Serialize` bound rather than FOUR
7997/// hand-authored per-parent tests held coherent by test-module
7998/// convention. THEORY.md §II.1 invariant 5 (composition preserves
7999/// proofs) — the four sub-assertions compose structurally through
8000/// ONE primitive here, so a regression at ONE axis surfaces at the
8001/// sub-assertion's own panic message rather than as silent drift
8002/// at every parent that might otherwise forget to include the
8003/// axis in its per-site author-time enumeration.
8004#[track_caller]
8005pub fn assert_tagged_union_convention_panel<T, F1, F2>(single_slot: F1, two_slot: F2)
8006where
8007    T: TaggedUnion + serde::Serialize,
8008    T::Kind: PartialEq + std::fmt::Debug,
8009    T::Error: PartialEq + std::fmt::Debug,
8010    F1: Fn(T::Kind) -> T,
8011    F2: Fn(T::Kind, T::Kind) -> T,
8012{
8013    assert_kind_list_matches_closed_set::<T>();
8014    assert_variant_round_trip::<T, _>(&single_slot);
8015    assert_two_slots_ambiguous::<T, _>(two_slot);
8016    assert_has_matches_select::<T, _>(&single_slot);
8017    assert_find_agrees_with_has::<T, _>(&single_slot);
8018    assert_single_slot_key_matches_label::<T, _>(single_slot);
8019}
8020
8021#[cfg(test)]
8022mod tests {
8023    use super::*;
8024
8025    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
8026    enum V {
8027        A,
8028        B,
8029        C,
8030    }
8031
8032    #[test]
8033    fn empty_candidate_list_is_none() {
8034        let r: Result<V, _> = resolve(std::iter::empty());
8035        assert_eq!(r.unwrap_err(), ResolveError::None);
8036    }
8037
8038    #[test]
8039    fn all_none_is_none() {
8040        let r: Result<V, _> = resolve([None, None, None]);
8041        assert_eq!(r.unwrap_err(), ResolveError::None);
8042    }
8043
8044    #[test]
8045    fn single_some_is_resolved_regardless_of_position() {
8046        assert_eq!(resolve([Some(V::A), None, None]).unwrap(), V::A);
8047        assert_eq!(resolve([None, Some(V::B), None]).unwrap(), V::B);
8048        assert_eq!(resolve([None, None, Some(V::C)]).unwrap(), V::C);
8049    }
8050
8051    #[test]
8052    fn two_or_more_some_is_many() {
8053        assert_eq!(
8054            resolve([Some(V::A), Some(V::B), None]).unwrap_err(),
8055            ResolveError::Many
8056        );
8057        assert_eq!(
8058            resolve([Some(V::A), None, Some(V::C)]).unwrap_err(),
8059            ResolveError::Many
8060        );
8061        assert_eq!(
8062            resolve([None, Some(V::B), Some(V::C)]).unwrap_err(),
8063            ResolveError::Many
8064        );
8065        assert_eq!(
8066            resolve([Some(V::A), Some(V::B), Some(V::C)]).unwrap_err(),
8067            ResolveError::Many
8068        );
8069    }
8070
8071    /// Short-circuit invariant: once `Many` is decided, the sweep does
8072    /// NOT inspect further candidates. Encode it as a side-effect probe.
8073    #[test]
8074    fn many_short_circuits_after_second_some() {
8075        let mut visited = 0usize;
8076        let candidates = (0..4).map(|i| {
8077            visited += 1;
8078            // first two are Some, the rest would be Some too if we got there.
8079            Some(i)
8080        });
8081        // We can't actually consume `visited` here because it's borrowed in
8082        // the closure — fold the count via the resolver's short-circuit.
8083        let _ = resolve(candidates);
8084        // The resolver evaluates the iterator lazily up to the second
8085        // Some — index 0 (found = Some(0)), index 1 (Many → return).
8086        assert_eq!(visited, 2);
8087    }
8088
8089    /// The helper is value-agnostic — works with borrowed enum-view
8090    /// types matching the actual on-the-typescape callsites.
8091    #[test]
8092    fn works_with_borrowed_enum_view() {
8093        #[derive(Debug, PartialEq)]
8094        enum View<'a> {
8095            X(&'a u32),
8096            Y(&'a String),
8097        }
8098        let x = 7u32;
8099        let r = resolve([Some(View::X(&x)), None]).unwrap();
8100        assert_eq!(r, View::X(&7));
8101    }
8102
8103    /// Local sibling-shaped carrier used to pin the trait +
8104    /// [`resolve_or_err`] dispatch without depending on the
8105    /// crate's real error types.
8106    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
8107    enum E {
8108        Empty(&'static str),
8109        Ambiguous,
8110    }
8111
8112    impl TaggedUnionError for E {
8113        fn empty(kinds: &'static str) -> Self {
8114            E::Empty(kinds)
8115        }
8116        fn ambiguous() -> Self {
8117            E::Ambiguous
8118        }
8119    }
8120
8121    /// Four-outcome truth table at the compound-lift boundary.
8122    /// Pins that the two failure arms of [`resolve`] project onto
8123    /// the trait's two typed constructors byte-identically, and
8124    /// that the Ok arm falls through untouched.
8125    #[test]
8126    fn resolve_or_err_dispatches_each_arm_through_the_trait() {
8127        const KINDS: &str = "a/b/c";
8128
8129        assert_eq!(
8130            resolve_or_err::<V, E>([Some(V::A), None, None], KINDS).unwrap(),
8131            V::A
8132        );
8133        assert_eq!(
8134            resolve_or_err::<V, E>([None, Some(V::B), None], KINDS).unwrap(),
8135            V::B
8136        );
8137
8138        assert_eq!(
8139            resolve_or_err::<V, E>([None, None, None], KINDS).unwrap_err(),
8140            E::Empty(KINDS)
8141        );
8142
8143        assert_eq!(
8144            resolve_or_err::<V, E>([Some(V::A), Some(V::B), None], KINDS).unwrap_err(),
8145            E::Ambiguous
8146        );
8147    }
8148
8149    /// The trait's Empty arm carries the &'static str the caller
8150    /// hands `resolve_or_err`, verbatim — a rename at the caller's
8151    /// `KINDS` constant reaches the diagnostic surface intact.
8152    #[test]
8153    fn resolve_or_err_empty_carries_the_caller_kinds_verbatim() {
8154        const KINDS_ALPHA: &str = "alpha/beta";
8155        const KINDS_GAMMA: &str = "gamma/delta/epsilon";
8156
8157        assert_eq!(
8158            resolve_or_err::<V, E>([None, None], KINDS_ALPHA).unwrap_err(),
8159            E::Empty(KINDS_ALPHA)
8160        );
8161        assert_eq!(
8162            resolve_or_err::<V, E>([None, None, None], KINDS_GAMMA).unwrap_err(),
8163            E::Empty(KINDS_GAMMA)
8164        );
8165    }
8166
8167    /// The compound-lift preserves [`resolve`]'s short-circuit at
8168    /// the Many arm — a third-and-later candidate is not
8169    /// inspected once the second populated entry is seen.
8170    #[test]
8171    fn resolve_or_err_short_circuits_on_many() {
8172        let mut visited = 0usize;
8173        let candidates = (0..4).map(|i| {
8174            visited += 1;
8175            Some(i)
8176        });
8177        let _ = resolve_or_err::<i32, E>(candidates, "irrelevant");
8178        assert_eq!(visited, 2);
8179    }
8180
8181    // -------------------------------------------------------------------
8182    // `declare_tagged_union_error!` macro-emitted carrier — pins the
8183    // shape a fifth sibling would land through the macro instead of
8184    // hand-rolling the enum + `impl TaggedUnionError` block.
8185    // -------------------------------------------------------------------
8186
8187    crate::declare_tagged_union_error! {
8188        pub(super) MacroEmittedError,
8189        empty = "test carrier has no variant set (one of {0} required)",
8190        ambiguous = "test carrier has multiple variants set; exactly one required",
8191    }
8192
8193    /// The macro-emitted carrier's [`TaggedUnionError`] impl dispatches
8194    /// the same four-outcome truth table [`resolve_or_err`] pins for a
8195    /// hand-rolled carrier — pins that swapping a hand-rolled carrier
8196    /// for a macro-emitted one preserves the compound-lift's projection
8197    /// byte-identically.
8198    #[test]
8199    fn macro_emitted_carrier_projects_through_resolve_or_err() {
8200        const KINDS: &str = "one/two/three";
8201
8202        assert_eq!(
8203            resolve_or_err::<V, MacroEmittedError>([Some(V::A), None, None], KINDS).unwrap(),
8204            V::A
8205        );
8206        assert_eq!(
8207            resolve_or_err::<V, MacroEmittedError>([None, None, None], KINDS).unwrap_err(),
8208            MacroEmittedError::Empty(KINDS)
8209        );
8210        assert_eq!(
8211            resolve_or_err::<V, MacroEmittedError>([Some(V::A), Some(V::B), None], KINDS)
8212                .unwrap_err(),
8213            MacroEmittedError::Ambiguous
8214        );
8215    }
8216
8217    /// The macro-emitted carrier's `#[error(...)]` messages render the
8218    /// two operator-facing diagnostic strings the caller handed the
8219    /// macro, verbatim — a rename at the caller's literal reaches the
8220    /// operator diagnostic surface intact.
8221    #[test]
8222    fn macro_emitted_carrier_display_renders_caller_literals_verbatim() {
8223        assert_eq!(
8224            MacroEmittedError::Empty("alpha/beta").to_string(),
8225            "test carrier has no variant set (one of alpha/beta required)",
8226        );
8227        assert_eq!(
8228            MacroEmittedError::Ambiguous.to_string(),
8229            "test carrier has multiple variants set; exactly one required",
8230        );
8231    }
8232
8233    /// The macro-emitted carrier is `Copy` — a substrate-wide promise
8234    /// pinned by the macro's `#[derive(..., Copy, ...)]` header so a
8235    /// consumer treating the carrier as a value type (memcpy-cheap
8236    /// return, `.copied()` on an `Option<&E>`) stays valid across every
8237    /// carrier the macro emits.
8238    #[test]
8239    fn macro_emitted_carrier_is_copy() {
8240        fn assert_copy<T: Copy>() {}
8241        assert_copy::<MacroEmittedError>();
8242    }
8243
8244    // -------------------------------------------------------------------
8245    // `TaggedUnion` trait — declarative surface pinning the
8246    // (Kind, Error, KIND_LIST) triple. `assert_kind_list_matches_closed_set`
8247    // is the generic diagnostic-stability testkit primitive shared by
8248    // every implementor's `_error_empty_lists_every_kind_in_canonical_order`
8249    // site.
8250    // -------------------------------------------------------------------
8251
8252    /// Local sibling-shaped Kind enum used to pin the trait's
8253    /// diagnostic-stability primitive without depending on the crate's
8254    /// four production tagged unions. Uses [`tatara_closed_set::DeriveClosedSet`]
8255    /// so `<Self as ClosedSet>::labels_joined("/")` reaches the same
8256    /// substrate composition the four production sites bind through.
8257    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
8258    #[closed_set(via = "as_str", generate_unknown, display)]
8259    enum LocalKind {
8260        Alpha,
8261        Beta,
8262        Gamma,
8263    }
8264
8265    impl LocalKind {
8266        const ALL: [Self; 3] = [Self::Alpha, Self::Beta, Self::Gamma];
8267        const fn as_str(self) -> &'static str {
8268            match self {
8269                Self::Alpha => "alpha",
8270                Self::Beta => "beta",
8271                Self::Gamma => "gamma",
8272            }
8273        }
8274    }
8275
8276    /// Local parent type — impls [`TaggedUnion`] with a `KIND_LIST`
8277    /// literal that matches the canonical `<LocalKind as
8278    /// ClosedSet>::labels_joined("/")` projection. Carries three
8279    /// `Option<u32>` slots so the substrate-primitive
8280    /// [`TaggedUnion::variant`] default method can be exercised
8281    /// directly on a sibling-shaped-but-crate-local parent, isolated
8282    /// from the four production tagged unions.
8283    ///
8284    /// Derives [`serde::Serialize`] with `skip_serializing_if =
8285    /// "Option::is_none"` on every slot so the wire-format primitive
8286    /// [`assert_single_slot_key_matches_label`] can be exercised
8287    /// directly against the sibling-shaped scaffold — mirrors the
8288    /// `#[serde(default, skip_serializing_if = "Option::is_none")]`
8289    /// annotation every one of the four production tagged unions
8290    /// carries on its own slots.
8291    #[derive(Default, serde::Serialize)]
8292    struct LocalParent {
8293        #[serde(skip_serializing_if = "Option::is_none")]
8294        alpha: Option<u32>,
8295        #[serde(skip_serializing_if = "Option::is_none")]
8296        beta: Option<u32>,
8297        #[serde(skip_serializing_if = "Option::is_none")]
8298        gamma: Option<u32>,
8299    }
8300
8301    /// Borrowed-view of a populated slot on [`LocalParent`] — the
8302    /// return type of [`LocalKind::select`] and the substrate-primitive
8303    /// [`TaggedUnion::variant`] default on `LocalParent`.
8304    #[derive(Debug, PartialEq)]
8305    enum LocalVariant<'a> {
8306        Alpha(&'a u32),
8307        Beta(&'a u32),
8308        Gamma(&'a u32),
8309    }
8310
8311    impl VariantSelector<LocalParent> for LocalKind {
8312        type Variant<'a> = LocalVariant<'a>;
8313        fn select<'a>(self, parent: &'a LocalParent) -> Option<LocalVariant<'a>>
8314        where
8315            Self: 'a,
8316        {
8317            match self {
8318                Self::Alpha => parent.alpha.as_ref().map(LocalVariant::Alpha),
8319                Self::Beta => parent.beta.as_ref().map(LocalVariant::Beta),
8320                Self::Gamma => parent.gamma.as_ref().map(LocalVariant::Gamma),
8321            }
8322        }
8323    }
8324
8325    impl VariantKind<LocalKind> for LocalVariant<'_> {
8326        fn variant_kind(&self) -> LocalKind {
8327            match self {
8328                Self::Alpha(_) => LocalKind::Alpha,
8329                Self::Beta(_) => LocalKind::Beta,
8330                Self::Gamma(_) => LocalKind::Gamma,
8331            }
8332        }
8333    }
8334
8335    crate::declare_tagged_union_error! {
8336        pub(super) LocalParentError,
8337        empty = "local carrier has no variant set (one of {0} required)",
8338        ambiguous = "local carrier has multiple variants set; exactly one required",
8339    }
8340
8341    impl TaggedUnion for LocalParent {
8342        type Kind = LocalKind;
8343        type Error = LocalParentError;
8344        const KIND_LIST: &'static str = "alpha/beta/gamma";
8345    }
8346
8347    /// The testkit primitive resolves the canonical join of every
8348    /// `LocalKind` variant's label against the trait's `KIND_LIST`
8349    /// constant byte-identically — the four production sites bind
8350    /// through this exact dispatch. The Ok arm is the "no drift"
8351    /// outcome; a divergence surfaces as a labeled assertion failure.
8352    #[test]
8353    fn assert_kind_list_matches_closed_set_accepts_coherent_impl() {
8354        assert_kind_list_matches_closed_set::<LocalParent>();
8355    }
8356
8357    /// The testkit primitive is a `#[track_caller]` compound-lift:
8358    /// a drift between `<T::Kind as ClosedSet>::labels_joined("/")`
8359    /// and `T::KIND_LIST` fails the assertion at the caller's site,
8360    /// not inside the primitive body. Pin the failing case with a
8361    /// local parent whose `KIND_LIST` is deliberately mis-authored
8362    /// (a variant reorder), so a regression that drops the drift
8363    /// detection fails-loudly here.
8364    #[test]
8365    #[should_panic(expected = "TaggedUnion KIND_LIST drift")]
8366    fn assert_kind_list_matches_closed_set_rejects_drifted_impl() {
8367        struct Drifted;
8368        // The `TaggedUnion` trait bounds `Kind: VariantSelector<Self>`
8369        // with `Variant<'a>: VariantKind<Self>`; the drift test only
8370        // exercises `assert_kind_list_matches_closed_set` (which reaches
8371        // the (Kind, KIND_LIST) pair, not the sweep body), so reusing
8372        // the sibling `LocalVariant<'a>` (with its already-load-bearing
8373        // `impl VariantKind<LocalKind>`) + always-`None` `select`
8374        // satisfies both bounds without wiring a real projection.
8375        impl VariantSelector<Drifted> for LocalKind {
8376            type Variant<'a> = LocalVariant<'a>;
8377            fn select<'a>(self, _: &'a Drifted) -> Option<LocalVariant<'a>>
8378            where
8379                Self: 'a,
8380            {
8381                None
8382            }
8383        }
8384        impl TaggedUnion for Drifted {
8385            type Kind = LocalKind;
8386            type Error = LocalParentError;
8387            // Deliberate drift — canonical join is "alpha/beta/gamma".
8388            const KIND_LIST: &'static str = "beta/alpha/gamma";
8389        }
8390        assert_kind_list_matches_closed_set::<Drifted>();
8391    }
8392
8393    /// Every one of the four production `.variant()` sites on
8394    /// `ProcessSpec` impls [`TaggedUnion`] with `KIND_LIST` reaching
8395    /// the substrate primitive `assert_kind_list_matches_closed_set`
8396    /// coherently. Sweep every production implementor at ONE
8397    /// substrate boundary so a regression that drifts a production
8398    /// site's `KIND_LIST` (or renames a `Kind` variant without
8399    /// updating the constant) fails BOTH at the per-crate test site
8400    /// AND at this substrate-wide sweep — no per-implementor test
8401    /// site can drop the check silently.
8402    #[test]
8403    fn every_production_tagged_union_binds_through_the_testkit_primitive() {
8404        assert_kind_list_matches_closed_set::<crate::intent::Intent>();
8405        assert_kind_list_matches_closed_set::<crate::encapsulates::EncapsulationKind>();
8406        assert_kind_list_matches_closed_set::<crate::export::ArtifactSource>();
8407        assert_kind_list_matches_closed_set::<crate::export::VectorChannel>();
8408    }
8409
8410    /// Every one of the four production `.variant()` sites on
8411    /// `ProcessSpec` binds through the wire-key primitive
8412    /// [`assert_single_slot_key_matches_label`] coherently — every
8413    /// per-site `single_slot_X(k)` factory serializes to a JSON object
8414    /// with EXACTLY ONE key whose name equals `k.label()` (delegating
8415    /// to each Kind's inherent `as_str`, matching the parent's serde
8416    /// `rename_all = "camelCase"` projection). Sweep every production
8417    /// implementor at ONE substrate boundary so a regression that
8418    /// drifts a production site's `single_slot_X` factory (populates
8419    /// the wrong slot; leaks residual slots between calls) OR the
8420    /// parent's field-to-kind alignment (`as_str` returns "receipts"
8421    /// but the field is named `receipt`) fails BOTH at the per-crate
8422    /// test site AND at this substrate-wide sweep — no per-implementor
8423    /// test site can drop the check silently.
8424    #[test]
8425    fn every_production_tagged_union_binds_through_the_wire_key_testkit_primitive() {
8426        assert_single_slot_key_matches_label::<crate::intent::Intent, _>(single_slot_intent_probe);
8427        assert_single_slot_key_matches_label::<crate::encapsulates::EncapsulationKind, _>(
8428            single_slot_encapsulation_kind_probe,
8429        );
8430        assert_single_slot_key_matches_label::<crate::export::ArtifactSource, _>(
8431            single_slot_artifact_source_probe,
8432        );
8433        assert_single_slot_key_matches_label::<crate::export::VectorChannel, _>(
8434            single_slot_vector_channel_probe,
8435        );
8436    }
8437
8438    /// The parent-side four-axis compound-lift dispatches Ok on a
8439    /// coherent implementor — the [`LocalParent`] scaffold publishes
8440    /// every axis (`TaggedUnion` via
8441    /// [`crate::declare_tagged_union_error`]-emitted `LocalParentError`
8442    /// + Serialize via `#[derive(serde::Serialize)]` +
8443    /// `LocalKind: PartialEq + Debug` +
8444    /// `LocalParentError: PartialEq + Debug`), matching the
8445    /// substrate-wide four-axis convention every one of the four
8446    /// production parents carries. The Ok arm is the "no drift"
8447    /// outcome; a divergence at ANY sub-assertion's composition
8448    /// inside the compound (accidentally dropped, silently reordered,
8449    /// or short-circuited) surfaces at the sub-primitive's own
8450    /// panic message (each sub-primitive is `#[track_caller]`), and
8451    /// the per-axis failing arms are pinned by the sibling
8452    /// `#[should_panic]` probes already at the per-axis primitive
8453    /// layer (`assert_kind_list_matches_closed_set_rejects_drifted_impl`,
8454    /// `assert_variant_round_trip_rejects_factory_that_leaves_slot_empty`,
8455    /// `assert_two_slots_ambiguous_rejects_factory_that_populates_only_one_slot`,
8456    /// `assert_single_slot_key_matches_label_rejects_factory_that_populates_wrong_slot`).
8457    /// Re-authoring per-axis drift probes at the compound layer
8458    /// would restate the SAME four axis-typed contracts through a
8459    /// compound wrapper without adding a new gate.
8460    #[test]
8461    fn assert_tagged_union_convention_panel_accepts_coherent_local_impl() {
8462        fn single_slot(k: LocalKind) -> LocalParent {
8463            match k {
8464                LocalKind::Alpha => LocalParent {
8465                    alpha: Some(11),
8466                    ..Default::default()
8467                },
8468                LocalKind::Beta => LocalParent {
8469                    beta: Some(22),
8470                    ..Default::default()
8471                },
8472                LocalKind::Gamma => LocalParent {
8473                    gamma: Some(33),
8474                    ..Default::default()
8475                },
8476            }
8477        }
8478        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
8479            let mut p = LocalParent::default();
8480            for k in [a, b] {
8481                match k {
8482                    LocalKind::Alpha => p.alpha = Some(11),
8483                    LocalKind::Beta => p.beta = Some(22),
8484                    LocalKind::Gamma => p.gamma = Some(33),
8485                }
8486            }
8487            p
8488        }
8489        assert_tagged_union_convention_panel::<LocalParent, _, _>(single_slot, two_slot);
8490    }
8491
8492    /// Every one of the four production `.variant()` parents on
8493    /// `ProcessSpec` binds through the four-axis convention-panel
8494    /// primitive [`assert_tagged_union_convention_panel`] coherently.
8495    /// Sweep every production parent at ONE substrate boundary so a
8496    /// regression that (a) drops ANY of the four sub-assertions from
8497    /// the compound's body, (b) reorders them in a way that skips
8498    /// one on Ok, (c) silently binds the compound against a
8499    /// hollowed-out sub-assertion body, or (d) drifts a substrate-
8500    /// local `{single,two}_slot_*_probe` fixture (populates the
8501    /// wrong slot; leaks residual slots between calls; the `.or()`
8502    /// composition drops a slot on the two-slot side) fails BOTH at
8503    /// the per-crate test site AND at this substrate-wide sweep.
8504    ///
8505    /// Pinned in lock-step with the sibling
8506    /// `every_production_tagged_union_binds_through_the_testkit_primitive`
8507    /// (KIND_LIST axis) and
8508    /// `every_production_tagged_union_binds_through_the_wire_key_testkit_primitive`
8509    /// (wire-key axis) sweeps — every parent enumerated below is a
8510    /// member of BOTH sibling sweeps (their bounds are strict
8511    /// subsets of the compound's `T: TaggedUnion + Serialize` +
8512    /// `T::Kind: PartialEq + Debug` + `T::Error: PartialEq + Debug`
8513    /// bound), and every parent additionally publishes both a
8514    /// substrate-local `single_slot_*_probe` and a
8515    /// substrate-local `two_slot_*_probe` peer above. Post-sweep the
8516    /// substrate-wide four-axis parent-side convention-panel
8517    /// discipline is a property of the workspace, not a per-file
8518    /// convention — even before any per-site test-body sweep
8519    /// collapses the four per-parent sibling tests into ONE compound
8520    /// call each.
8521    #[test]
8522    fn every_production_tagged_union_binds_through_the_convention_panel_testkit_primitive() {
8523        assert_tagged_union_convention_panel::<crate::intent::Intent, _, _>(
8524            single_slot_intent_probe,
8525            two_slot_intent_probe,
8526        );
8527        assert_tagged_union_convention_panel::<crate::encapsulates::EncapsulationKind, _, _>(
8528            single_slot_encapsulation_kind_probe,
8529            two_slot_encapsulation_kind_probe,
8530        );
8531        assert_tagged_union_convention_panel::<crate::export::ArtifactSource, _, _>(
8532            single_slot_artifact_source_probe,
8533            two_slot_artifact_source_probe,
8534        );
8535        assert_tagged_union_convention_panel::<crate::export::VectorChannel, _, _>(
8536            single_slot_vector_channel_probe,
8537            two_slot_vector_channel_probe,
8538        );
8539    }
8540
8541    /// The Display / label alignment primitive dispatches Ok on a
8542    /// coherent implementor — the [`LocalKind`] scaffold derives
8543    /// `Display` from `label` via `#[closed_set(via = "as_str",
8544    /// display)]`, matching the substrate-wide derive shape every
8545    /// production implementor across the crate carries. The Ok arm
8546    /// is the "no drift" outcome; a divergence surfaces as a labeled
8547    /// assertion failure at the caller site (this test's own line).
8548    #[test]
8549    fn assert_display_matches_label_accepts_coherent_impl() {
8550        assert_display_matches_label::<LocalKind>();
8551    }
8552
8553    /// A local closed-set scaffold whose `Display` deliberately
8554    /// diverges from `label` — pins the failing arm of the primitive.
8555    /// The `#[closed_set(via = "as_str")]` attribute WITHOUT `display`
8556    /// leaves the `Display` impl uncovered by the derive, and the
8557    /// hand-authored `impl Display` below emits a suffixed rendering
8558    /// that no `label` projection returns. A regression that drops
8559    /// the alignment assertion inside
8560    /// [`assert_display_matches_label`] fails-loudly at this
8561    /// `#[should_panic]` probe before it can silently thread through
8562    /// the 29 production `X_display_matches_as_str` sites.
8563    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
8564    #[closed_set(via = "as_str", generate_unknown)]
8565    enum DisplayDriftKind {
8566        Alpha,
8567        Beta,
8568    }
8569
8570    impl DisplayDriftKind {
8571        const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
8572        const fn as_str(self) -> &'static str {
8573            match self {
8574                Self::Alpha => "alpha",
8575                Self::Beta => "beta",
8576            }
8577        }
8578    }
8579
8580    impl std::fmt::Display for DisplayDriftKind {
8581        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8582            // Deliberate drift — Display suffixes the label with a
8583            // marker no `label` projection returns.
8584            write!(f, "{}!", self.as_str())
8585        }
8586    }
8587
8588    #[test]
8589    #[should_panic(expected = "Display drifted from ClosedSet::label")]
8590    fn assert_display_matches_label_rejects_drifted_impl() {
8591        assert_display_matches_label::<DisplayDriftKind>();
8592    }
8593
8594    /// Every closed-set enum across `tatara-process` that carried a
8595    /// hand-rolled `X_display_matches_as_str` test pre-lift now binds
8596    /// through the substrate primitive at ONE call site each.  This
8597    /// substrate-wide sweep pins every production Display-alignment
8598    /// consumer at ONE boundary so a per-crate test-site drop cannot
8599    /// silently disable the check — the sweep here catches the drift
8600    /// even when the per-site test body is removed. Mirrors the
8601    /// `every_production_tagged_union_binds_through_the_testkit_primitive`
8602    /// and `every_production_tagged_union_binds_through_the_wire_key_testkit_primitive`
8603    /// sibling sweeps on the (`KIND_LIST` slash-join, wire-key)
8604    /// axes; this one closes the (`Display` byte-identity) axis.
8605    #[test]
8606    fn every_production_display_impl_binds_through_the_testkit_primitive() {
8607        assert_display_matches_label::<crate::allocation::AllocationPhase>();
8608        assert_display_matches_label::<crate::boundary::ConditionKind>();
8609        assert_display_matches_label::<crate::classification::Arity>();
8610        assert_display_matches_label::<crate::classification::CalmClassification>();
8611        assert_display_matches_label::<crate::classification::ConvergencePointType>();
8612        assert_display_matches_label::<crate::classification::DataClassification>();
8613        assert_display_matches_label::<crate::classification::HorizonKind>();
8614        assert_display_matches_label::<crate::classification::OptimizationDirection>();
8615        assert_display_matches_label::<crate::classification::SubstrateType>();
8616        assert_display_matches_label::<crate::compliance::VerificationPhase>();
8617        assert_display_matches_label::<crate::encapsulates::EncapsulationMode>();
8618        assert_display_matches_label::<crate::encapsulates::EncapsulationTarget>();
8619        assert_display_matches_label::<crate::export::ArtifactKind>();
8620        assert_display_matches_label::<crate::export::ChannelKind>();
8621        assert_display_matches_label::<crate::export::ExportTrigger>();
8622        assert_display_matches_label::<crate::export::ReportFormat>();
8623        assert_display_matches_label::<crate::export::ReportPayloadShape>();
8624        assert_display_matches_label::<crate::intent::IntentKind>();
8625        assert_display_matches_label::<crate::intent::WorkloadKind>();
8626        assert_display_matches_label::<crate::lifetime::LifetimeKind>();
8627        assert_display_matches_label::<crate::lifetime::TeardownPolicy>();
8628        assert_display_matches_label::<crate::lifetime_clock::AutoTerminateKind>();
8629        assert_display_matches_label::<crate::lifetime_clock::TerminateReasonKind>();
8630        assert_display_matches_label::<crate::matrix::SelectStrategyKind>();
8631        assert_display_matches_label::<crate::pool::MemberState>();
8632        assert_display_matches_label::<crate::pool::PoolPhase>();
8633        assert_display_matches_label::<crate::pool::ReplacementPolicy>();
8634        assert_display_matches_label::<crate::pool::ReturnPolicy>();
8635        assert_display_matches_label::<crate::signal::SighupStrategy>();
8636        assert_display_matches_label::<crate::spec::MustReachPhase>();
8637    }
8638
8639    /// Local closed-set scaffold whose serde `rename_all = "lowercase"`
8640    /// projection matches its `via = "as_str"` label byte-identically —
8641    /// pins the Ok arm of the wire-format primitive. Every production
8642    /// implementor across the crate carries the substrate-wide
8643    /// `#[closed_set(via = "as_str")]` + `#[serde(rename_all = ...)]`
8644    /// pair whose alignment this scaffold pins on the sibling-shaped
8645    /// local surface.
8646    #[derive(
8647        Clone,
8648        Copy,
8649        Debug,
8650        PartialEq,
8651        Eq,
8652        Hash,
8653        serde::Serialize,
8654        tatara_closed_set::DeriveClosedSet,
8655    )]
8656    #[serde(rename_all = "lowercase")]
8657    #[closed_set(via = "as_str", generate_unknown)]
8658    enum SerdeAlignedKind {
8659        Alpha,
8660        Beta,
8661    }
8662
8663    impl SerdeAlignedKind {
8664        const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
8665        const fn as_str(self) -> &'static str {
8666            match self {
8667                Self::Alpha => "alpha",
8668                Self::Beta => "beta",
8669            }
8670        }
8671    }
8672
8673    #[test]
8674    fn assert_label_matches_serde_serialization_accepts_coherent_impl() {
8675        assert_label_matches_serde_serialization::<SerdeAlignedKind>();
8676    }
8677
8678    /// A local closed-set scaffold whose serde output deliberately
8679    /// diverges from `label` — pins the failing arm of the wire-format
8680    /// primitive. The `#[serde(rename_all = "UPPERCASE")]` projection
8681    /// emits uppercase JSON strings while the `via = "as_str"` label
8682    /// stays lowercase. A regression that drops the alignment assertion
8683    /// inside [`assert_label_matches_serde_serialization`] fails-loudly
8684    /// at this `#[should_panic]` probe before it can silently thread
8685    /// through the 20 production `X_as_str_matches_serde` sites.
8686    #[derive(
8687        Clone,
8688        Copy,
8689        Debug,
8690        PartialEq,
8691        Eq,
8692        Hash,
8693        serde::Serialize,
8694        tatara_closed_set::DeriveClosedSet,
8695    )]
8696    #[serde(rename_all = "UPPERCASE")]
8697    #[closed_set(via = "as_str", generate_unknown)]
8698    enum SerdeDriftKind {
8699        Alpha,
8700        Beta,
8701    }
8702
8703    impl SerdeDriftKind {
8704        const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
8705        const fn as_str(self) -> &'static str {
8706            match self {
8707                Self::Alpha => "alpha",
8708                Self::Beta => "beta",
8709            }
8710        }
8711    }
8712
8713    #[test]
8714    #[should_panic(expected = "serde output drifted from ClosedSet::label")]
8715    fn assert_label_matches_serde_serialization_rejects_drifted_impl() {
8716        assert_label_matches_serde_serialization::<SerdeDriftKind>();
8717    }
8718
8719    /// Local closed-set scaffold whose ALL THREE axes of the label-
8720    /// surface convention align by construction — pins the Ok arm of
8721    /// the compound-panel primitive.
8722    ///
8723    /// `#[serde(rename_all = "lowercase")]` matches the `via = "as_str"`
8724    /// labels byte-identically (the serde-alignment axis). The
8725    /// `display` sub-attribute on `#[closed_set(via = "as_str",
8726    /// display)]` derives `impl Display` from the same `as_str`
8727    /// projection (the Display-alignment axis). The `generate_unknown`
8728    /// sub-attribute emits the `T::Unknown` carrier the round-trip
8729    /// axis's `parse_label` returns on unknown input. Together these
8730    /// three attributes stamp the substrate-wide derive shape every
8731    /// production 3-axis-panel consumer carries; a caller that lands
8732    /// through this scaffold satisfies EVERY bound the compound's
8733    /// where-clause names.
8734    ///
8735    /// Peer to the sibling per-axis fixtures [`LocalKind`] (Display
8736    /// axis, no serde) and [`SerdeAlignedKind`] (serde axis, no
8737    /// Display) on the label-surface primitive family; this fixture
8738    /// closes the diagonal by carrying both attribute-sets at once,
8739    /// so a regression at ANY sub-assertion's composition inside the
8740    /// compound (the compound accidentally dropping the well-formed
8741    /// call, silently reordering the three calls, wrapping them in a
8742    /// short-circuit that skips the middle one on Ok, …) fails the
8743    /// compound's happy-path pin below rather than as silent drift at
8744    /// every 3-axis consumer.
8745    #[derive(
8746        Clone,
8747        Copy,
8748        Debug,
8749        PartialEq,
8750        Eq,
8751        Hash,
8752        serde::Serialize,
8753        tatara_closed_set::DeriveClosedSet,
8754    )]
8755    #[serde(rename_all = "lowercase")]
8756    #[closed_set(via = "as_str", generate_unknown, display)]
8757    enum PanelAlignedKind {
8758        Alpha,
8759        Beta,
8760    }
8761
8762    impl PanelAlignedKind {
8763        const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
8764        const fn as_str(self) -> &'static str {
8765            match self {
8766                Self::Alpha => "alpha",
8767                Self::Beta => "beta",
8768            }
8769        }
8770    }
8771
8772    /// The compound-panel primitive dispatches Ok on a coherent
8773    /// implementor — [`PanelAlignedKind`] carries every attribute the
8774    /// substrate-wide 3-axis derive shape publishes, so all three
8775    /// sub-assertions the compound composes (well-formed, Display /
8776    /// label, serde / label) pass by construction. The Ok arm is the
8777    /// "no drift on any axis" outcome; a divergence at any single
8778    /// sub-assertion surfaces as that sub-assertion's own labeled
8779    /// panic message (with the caller-attributed line via
8780    /// `#[track_caller]` on both the compound and its sub-
8781    /// primitives), NOT as a silent pass.
8782    ///
8783    /// The per-axis failing arms are pinned by the sibling per-axis
8784    /// #[should_panic] probes above:
8785    ///   - the round-trip axis's failing arm is pinned by
8786    ///     [`tatara_closed_set::assert_closed_set_well_formed`]'s own
8787    ///     `#[should_panic]` probe in the `tatara-closed-set` crate;
8788    ///   - the Display axis's failing arm is pinned by
8789    ///     [`assert_display_matches_label_rejects_drifted_impl`] on
8790    ///     [`DisplayDriftKind`];
8791    ///   - the serde axis's failing arm is pinned by
8792    ///     [`assert_label_matches_serde_serialization_rejects_drifted_impl`]
8793    ///     on [`SerdeDriftKind`].
8794    /// Each per-axis drift fixture already surfaces its axis's exact
8795    /// panic-message substring, so re-authoring per-axis
8796    /// `#[should_panic]` probes at the compound layer would restate
8797    /// the SAME three axis-typed contracts through a compound
8798    /// wrapper — one more copy of the same three pins, not a new
8799    /// gate. The compound's happy-path pin here suffices to verify
8800    /// the composition doesn't lose ANY sub-assertion (a regression
8801    /// that swallows one axis silently would still fail the sibling
8802    /// sub-assertion's own drift probe on the drift fixture).
8803    #[test]
8804    fn assert_closed_set_convention_panel_accepts_coherent_impl() {
8805        assert_closed_set_convention_panel::<PanelAlignedKind>();
8806    }
8807
8808    /// Every closed-set enum across `tatara-process` that publishes
8809    /// ALL THREE axes of the label-surface convention (well-formed +
8810    /// Display-alignment + serde-alignment) now binds through the
8811    /// substrate compound-panel primitive at ONE call site each in
8812    /// this sweep. Pinned in lock-step with the sibling
8813    /// `every_production_serde_serialization_binds_through_the_testkit_primitive`
8814    /// sweep — every enum enumerated below is a member of BOTH sweeps
8815    /// (the compound's `T: Serialize + Display + ClosedSet + ...`
8816    /// bound is a strict superset of `assert_label_matches_serde_
8817    /// serialization`'s `T: ClosedSet + Serialize + Debug` bound, and
8818    /// the 20 wire-format consumers all additionally impl Display via
8819    /// `#[closed_set(via = "as_str", display)]`).
8820    ///
8821    /// A regression that (a) drops the compound's `assert_closed_set_
8822    /// well_formed` dispatch, (b) reorders the three sub-assertions
8823    /// in a way that skips one on Ok, or (c) silently binds the
8824    /// compound against a hollowed-out sub-assertion body catches
8825    /// here at the substrate-wide boundary — the sweep pins every
8826    /// production 3-axis consumer's compound-panel discipline through
8827    /// ONE test even before any per-site test-body sweep collapses
8828    /// the three per-enum sibling tests into ONE compound call each.
8829    /// Post-sweep the substrate-wide compound-panel discipline is a
8830    /// property of the workspace, not a per-file convention.
8831    #[test]
8832    fn every_production_convention_panel_binds_through_the_testkit_primitive() {
8833        assert_closed_set_convention_panel::<crate::allocation::AllocationPhase>();
8834        assert_closed_set_convention_panel::<crate::boundary::ConditionKind>();
8835        assert_closed_set_convention_panel::<crate::classification::CalmClassification>();
8836        assert_closed_set_convention_panel::<crate::classification::ConvergencePointType>();
8837        assert_closed_set_convention_panel::<crate::classification::DataClassification>();
8838        assert_closed_set_convention_panel::<crate::classification::HorizonKind>();
8839        assert_closed_set_convention_panel::<crate::classification::OptimizationDirection>();
8840        assert_closed_set_convention_panel::<crate::classification::SubstrateType>();
8841        assert_closed_set_convention_panel::<crate::compliance::VerificationPhase>();
8842        assert_closed_set_convention_panel::<crate::encapsulates::EncapsulationMode>();
8843        assert_closed_set_convention_panel::<crate::export::ExportTrigger>();
8844        assert_closed_set_convention_panel::<crate::export::ReportFormat>();
8845        assert_closed_set_convention_panel::<crate::intent::WorkloadKind>();
8846        assert_closed_set_convention_panel::<crate::lifetime::TeardownPolicy>();
8847        assert_closed_set_convention_panel::<crate::pool::MemberState>();
8848        assert_closed_set_convention_panel::<crate::pool::PoolPhase>();
8849        assert_closed_set_convention_panel::<crate::pool::ReplacementPolicy>();
8850        assert_closed_set_convention_panel::<crate::pool::ReturnPolicy>();
8851        assert_closed_set_convention_panel::<crate::signal::SighupStrategy>();
8852        assert_closed_set_convention_panel::<crate::spec::MustReachPhase>();
8853    }
8854
8855    /// Every closed-set enum across `tatara-process` that carried a
8856    /// hand-rolled `X_as_str_matches_serde` test pre-lift now binds
8857    /// through the substrate primitive at ONE call site each. This
8858    /// substrate-wide sweep pins every production wire-format alignment
8859    /// consumer at ONE boundary so a per-crate test-site drop cannot
8860    /// silently disable the check — the sweep here catches the drift
8861    /// even when the per-site test body is removed. Mirrors the sibling
8862    /// `every_production_display_impl_binds_through_the_testkit_primitive`
8863    /// sweep on the (Display byte-identity) axis; this one closes the
8864    /// (serde JSON-string byte-identity) axis.
8865    #[test]
8866    fn every_production_serde_serialization_binds_through_the_testkit_primitive() {
8867        assert_label_matches_serde_serialization::<crate::allocation::AllocationPhase>();
8868        assert_label_matches_serde_serialization::<crate::boundary::ConditionKind>();
8869        assert_label_matches_serde_serialization::<crate::classification::CalmClassification>();
8870        assert_label_matches_serde_serialization::<crate::classification::ConvergencePointType>();
8871        assert_label_matches_serde_serialization::<crate::classification::DataClassification>();
8872        assert_label_matches_serde_serialization::<crate::classification::HorizonKind>();
8873        assert_label_matches_serde_serialization::<crate::classification::OptimizationDirection>();
8874        assert_label_matches_serde_serialization::<crate::classification::SubstrateType>();
8875        assert_label_matches_serde_serialization::<crate::compliance::VerificationPhase>();
8876        assert_label_matches_serde_serialization::<crate::encapsulates::EncapsulationMode>();
8877        assert_label_matches_serde_serialization::<crate::export::ExportTrigger>();
8878        assert_label_matches_serde_serialization::<crate::export::ReportFormat>();
8879        assert_label_matches_serde_serialization::<crate::intent::WorkloadKind>();
8880        assert_label_matches_serde_serialization::<crate::lifetime::TeardownPolicy>();
8881        assert_label_matches_serde_serialization::<crate::pool::MemberState>();
8882        assert_label_matches_serde_serialization::<crate::pool::PoolPhase>();
8883        assert_label_matches_serde_serialization::<crate::pool::ReplacementPolicy>();
8884        assert_label_matches_serde_serialization::<crate::pool::ReturnPolicy>();
8885        assert_label_matches_serde_serialization::<crate::signal::SighupStrategy>();
8886        assert_label_matches_serde_serialization::<crate::spec::MustReachPhase>();
8887    }
8888
8889    // Substrate-local single-slot factories — mirror the per-site
8890    // `single_slot_X` test helpers each production site owns, so the
8891    // substrate-wide sweep above binds through the wire-key primitive
8892    // without reaching across the per-crate test-module boundaries the
8893    // per-site helpers are scoped to. The primitive only requires that
8894    // the addressed slot on the parent is populated; the inner spec's
8895    // exact field values are irrelevant to the wire-key check.
8896
8897    fn single_slot_intent_probe(kind: crate::intent::IntentKind) -> crate::intent::Intent {
8898        use crate::intent::{
8899            AplicacaoIntent, ContainerIntent, FluxIntent, GuestIntent, Intent, IntentKind,
8900            LispIntent, NixIntent, WorkloadKind,
8901        };
8902        match kind {
8903            IntentKind::Nix => Intent {
8904                nix: Some(NixIntent {
8905                    flake_ref: "f".into(),
8906                    attribute: "a".into(),
8907                    system: None,
8908                    attic_cache: None,
8909                    extra_args: vec![],
8910                    delegate_to_nix_build: false,
8911                }),
8912                ..Intent::default()
8913            },
8914            IntentKind::Flux => Intent {
8915                flux: Some(FluxIntent {
8916                    git_repository: "g".into(),
8917                    path: "p".into(),
8918                    git_repository_namespace: None,
8919                    target_namespace: None,
8920                    decrypt_sops: true,
8921                    helm_chart: None,
8922                    helm_values: None,
8923                }),
8924                ..Intent::default()
8925            },
8926            IntentKind::Lisp => Intent {
8927                lisp: Some(LispIntent {
8928                    source: "()".into(),
8929                    reader: "tatara-lisp".into(),
8930                    version: "v1".into(),
8931                    bindings: std::collections::BTreeMap::new(),
8932                }),
8933                ..Intent::default()
8934            },
8935            IntentKind::Container => Intent {
8936                container: Some(ContainerIntent {
8937                    image: "x".into(),
8938                    replicas: None,
8939                    command: vec![],
8940                    args: vec![],
8941                    env: std::collections::BTreeMap::new(),
8942                    workload_kind: WorkloadKind::default(),
8943                }),
8944                ..Intent::default()
8945            },
8946            IntentKind::Aplicacao => Intent {
8947                aplicacao: Some(AplicacaoIntent::chart_only("x", "1")),
8948                ..Intent::default()
8949            },
8950            IntentKind::Guest => Intent {
8951                guest: Some(GuestIntent {
8952                    spec: serde_json::json!({"name": "x"}),
8953                    state_dir: None,
8954                    allow_remote_build: None,
8955                }),
8956                ..Intent::default()
8957            },
8958        }
8959    }
8960
8961    fn single_slot_encapsulation_kind_probe(
8962        target: crate::encapsulates::EncapsulationTarget,
8963    ) -> crate::encapsulates::EncapsulationKind {
8964        use crate::encapsulates::{
8965            BareWorkload, EncapsulationKind, EncapsulationTarget, ExistingHelmRelease,
8966            ExistingKustomization,
8967        };
8968        match target {
8969            EncapsulationTarget::ExistingHelmRelease => EncapsulationKind {
8970                existing_helm_release: Some(ExistingHelmRelease {
8971                    namespace: "ns".into(),
8972                    name: "hr".into(),
8973                    release_name: "rel".into(),
8974                }),
8975                ..EncapsulationKind::default()
8976            },
8977            EncapsulationTarget::ExistingKustomization => EncapsulationKind {
8978                existing_kustomization: Some(ExistingKustomization {
8979                    namespace: "ns".into(),
8980                    name: "ks".into(),
8981                }),
8982                ..EncapsulationKind::default()
8983            },
8984            EncapsulationTarget::BareWorkload => {
8985                let mut sel = std::collections::BTreeMap::new();
8986                sel.insert("app".into(), "x".into());
8987                EncapsulationKind {
8988                    bare_workload: Some(BareWorkload {
8989                        namespace: "ns".into(),
8990                        selector: sel,
8991                    }),
8992                    ..EncapsulationKind::default()
8993                }
8994            }
8995        }
8996    }
8997
8998    fn single_slot_artifact_source_probe(
8999        kind: crate::export::ArtifactKind,
9000    ) -> crate::export::ArtifactSource {
9001        use crate::export::{
9002            ArtifactKind, ArtifactSource, ProcessSnapshotSource, ReceiptsSource, ReportFormat,
9003            RunMarkerSource, TestReportSource,
9004        };
9005        match kind {
9006            ArtifactKind::Receipts => ArtifactSource {
9007                receipts: Some(ReceiptsSource::default()),
9008                ..ArtifactSource::default()
9009            },
9010            ArtifactKind::TestReport => ArtifactSource {
9011                test_report: Some(TestReportSource {
9012                    configmap: "cm".into(),
9013                    key: "k".into(),
9014                    format: ReportFormat::Junit,
9015                    namespace: None,
9016                }),
9017                ..ArtifactSource::default()
9018            },
9019            ArtifactKind::ProcessSnapshot => ArtifactSource {
9020                process_snapshot: Some(ProcessSnapshotSource::default()),
9021                ..ArtifactSource::default()
9022            },
9023            ArtifactKind::RunMarker => ArtifactSource {
9024                run_marker: Some(RunMarkerSource::default()),
9025                ..ArtifactSource::default()
9026            },
9027        }
9028    }
9029
9030    fn single_slot_vector_channel_probe(
9031        kind: crate::export::ChannelKind,
9032    ) -> crate::export::VectorChannel {
9033        use crate::export::{
9034            ChannelKind, HttpEventChannel, NatsSubjectChannel, StdoutChannel, VectorChannel,
9035        };
9036        match kind {
9037            ChannelKind::HttpEvent => VectorChannel {
9038                http_event: Some(HttpEventChannel::signal("x")),
9039                ..VectorChannel::default()
9040            },
9041            ChannelKind::NatsSubject => VectorChannel {
9042                nats_subject: Some(NatsSubjectChannel::publish("s", "S")),
9043                ..VectorChannel::default()
9044            },
9045            ChannelKind::Stdout => VectorChannel {
9046                stdout: Some(StdoutChannel::default()),
9047                ..VectorChannel::default()
9048            },
9049        }
9050    }
9051
9052    // Substrate-local two-slot factories — peers to the sibling
9053    // `single_slot_*_probe` block above. Each composes
9054    // `single_slot_*_probe(a)` with `single_slot_*_probe(b)`
9055    // through per-field `Option::or` on the parent's tagged-union
9056    // slots, matching the shape every per-site `two_slot_X(a, b)`
9057    // helper across the four production parents already carries.
9058    // The ambiguity-primitive only requires that BOTH addressed
9059    // slots on the parent are populated; the inner spec's exact
9060    // field values are irrelevant to the two-slot ambiguity check.
9061
9062    fn two_slot_intent_probe(
9063        a: crate::intent::IntentKind,
9064        b: crate::intent::IntentKind,
9065    ) -> crate::intent::Intent {
9066        let ia = single_slot_intent_probe(a);
9067        let ib = single_slot_intent_probe(b);
9068        crate::intent::Intent {
9069            nix: ia.nix.or(ib.nix),
9070            flux: ia.flux.or(ib.flux),
9071            lisp: ia.lisp.or(ib.lisp),
9072            container: ia.container.or(ib.container),
9073            aplicacao: ia.aplicacao.or(ib.aplicacao),
9074            guest: ia.guest.or(ib.guest),
9075        }
9076    }
9077
9078    fn two_slot_encapsulation_kind_probe(
9079        a: crate::encapsulates::EncapsulationTarget,
9080        b: crate::encapsulates::EncapsulationTarget,
9081    ) -> crate::encapsulates::EncapsulationKind {
9082        let ka = single_slot_encapsulation_kind_probe(a);
9083        let kb = single_slot_encapsulation_kind_probe(b);
9084        crate::encapsulates::EncapsulationKind {
9085            existing_helm_release: ka.existing_helm_release.or(kb.existing_helm_release),
9086            existing_kustomization: ka.existing_kustomization.or(kb.existing_kustomization),
9087            bare_workload: ka.bare_workload.or(kb.bare_workload),
9088        }
9089    }
9090
9091    fn two_slot_artifact_source_probe(
9092        a: crate::export::ArtifactKind,
9093        b: crate::export::ArtifactKind,
9094    ) -> crate::export::ArtifactSource {
9095        let sa = single_slot_artifact_source_probe(a);
9096        let sb = single_slot_artifact_source_probe(b);
9097        crate::export::ArtifactSource {
9098            receipts: sa.receipts.or(sb.receipts),
9099            test_report: sa.test_report.or(sb.test_report),
9100            process_snapshot: sa.process_snapshot.or(sb.process_snapshot),
9101            run_marker: sa.run_marker.or(sb.run_marker),
9102        }
9103    }
9104
9105    fn two_slot_vector_channel_probe(
9106        a: crate::export::ChannelKind,
9107        b: crate::export::ChannelKind,
9108    ) -> crate::export::VectorChannel {
9109        let ca = single_slot_vector_channel_probe(a);
9110        let cb = single_slot_vector_channel_probe(b);
9111        crate::export::VectorChannel {
9112            http_event: ca.http_event.or(cb.http_event),
9113            nats_subject: ca.nats_subject.or(cb.nats_subject),
9114            stdout: ca.stdout.or(cb.stdout),
9115        }
9116    }
9117
9118    /// The trait's `KIND_LIST` associated const IS the same
9119    /// `&'static str` the inherent `_LIST` constant publishes at
9120    /// each production site — pin identity via `std::ptr::eq` so a
9121    /// future silent copy (e.g. `const KIND_LIST: &'static str =
9122    /// "...literal...";` at the impl block) is caught here.
9123    #[test]
9124    fn production_tagged_union_kind_list_borrows_the_inherent_constant() {
9125        assert!(std::ptr::eq(
9126            <crate::intent::Intent as TaggedUnion>::KIND_LIST,
9127            crate::intent::INTENT_KIND_LIST,
9128        ));
9129        assert!(std::ptr::eq(
9130            <crate::encapsulates::EncapsulationKind as TaggedUnion>::KIND_LIST,
9131            crate::encapsulates::ENCAPSULATION_TARGET_LIST,
9132        ));
9133        assert!(std::ptr::eq(
9134            <crate::export::ArtifactSource as TaggedUnion>::KIND_LIST,
9135            crate::export::ARTIFACT_KIND_LIST,
9136        ));
9137        assert!(std::ptr::eq(
9138            <crate::export::VectorChannel as TaggedUnion>::KIND_LIST,
9139            crate::export::CHANNEL_KIND_LIST,
9140        ));
9141    }
9142
9143    // -------------------------------------------------------------------
9144    // `TaggedUnion::variant` default method — substrate primitive every
9145    // production `.variant()` inherent method delegates to. Pin the
9146    // four-outcome truth table (Empty on all-none, Ambiguous on many,
9147    // Ok on exactly-one at every position) directly on the sibling-
9148    // shaped local parent + local kind + local variant scaffold, so a
9149    // regression on the default body's short-circuit or
9150    // ClosedSet::ALL iteration shape fails here — before any per-parent
9151    // inherent test surfaces the drift.
9152    // -------------------------------------------------------------------
9153
9154    /// Every populated position across [`LocalKind::ALL`] resolves to
9155    /// its own [`LocalVariant`] arm through the default body's
9156    /// `resolve_or_err(<Kind as ClosedSet>::ALL.iter().copied()
9157    /// .map(|k| k.select(self)), KIND_LIST)` sweep. Pin every position
9158    /// so a regression that drifts the iteration order (or drops the
9159    /// `.iter().copied()` bridge to owned-`Copy` Kinds) fails at ONE
9160    /// substrate boundary rather than at four per-parent inherent test
9161    /// sites.
9162    #[test]
9163    fn tagged_union_default_variant_resolves_each_populated_slot() {
9164        let mut p = LocalParent {
9165            alpha: Some(11),
9166            ..Default::default()
9167        };
9168        assert_eq!(
9169            <LocalParent as TaggedUnion>::variant(&p).unwrap(),
9170            LocalVariant::Alpha(&11)
9171        );
9172        p = LocalParent {
9173            beta: Some(22),
9174            ..Default::default()
9175        };
9176        assert_eq!(
9177            <LocalParent as TaggedUnion>::variant(&p).unwrap(),
9178            LocalVariant::Beta(&22)
9179        );
9180        p = LocalParent {
9181            gamma: Some(33),
9182            ..Default::default()
9183        };
9184        assert_eq!(
9185            <LocalParent as TaggedUnion>::variant(&p).unwrap(),
9186            LocalVariant::Gamma(&33)
9187        );
9188    }
9189
9190    /// A [`LocalParent`] with no populated slot resolves through the
9191    /// default body to a [`TaggedUnionError::empty`] carrier whose
9192    /// payload IS the trait's [`TaggedUnion::KIND_LIST`] constant —
9193    /// pin identity via [`std::ptr::eq`] so a regression that
9194    /// composes a fresh `&'static str` at the empty arm (instead of
9195    /// carrying the trait's constant verbatim) is caught here. This
9196    /// is the substrate-wide guarantee the four production sites'
9197    /// operator diagnostics depend on: a rename at
9198    /// `<Parent as TaggedUnion>::KIND_LIST` reaches the error surface
9199    /// intact through ONE `&'static str` handoff.
9200    #[test]
9201    fn tagged_union_default_variant_empty_carries_kind_list_by_pointer() {
9202        let empty = LocalParent::default();
9203        let err = <LocalParent as TaggedUnion>::variant(&empty).unwrap_err();
9204        match err {
9205            LocalParentError::Empty(list) => {
9206                assert!(
9207                    std::ptr::eq(list, <LocalParent as TaggedUnion>::KIND_LIST),
9208                    "TaggedUnion::variant default must carry KIND_LIST by pointer, not by re-composition",
9209                );
9210            }
9211            LocalParentError::Ambiguous => {
9212                panic!("expected Empty carrier, got Ambiguous");
9213            }
9214        }
9215    }
9216
9217    /// A [`LocalParent`] with two populated slots resolves through
9218    /// the default body to a [`TaggedUnionError::ambiguous`] carrier —
9219    /// pin the Many arm at the substrate boundary so a regression
9220    /// that drops the short-circuit (or misroutes the Many arm to
9221    /// Empty) is caught here.
9222    #[test]
9223    fn tagged_union_default_variant_ambiguous_on_multiple_populated_slots() {
9224        let p = LocalParent {
9225            alpha: Some(1),
9226            beta: Some(2),
9227            gamma: None,
9228        };
9229        assert_eq!(
9230            <LocalParent as TaggedUnion>::variant(&p).unwrap_err(),
9231            LocalParentError::Ambiguous
9232        );
9233    }
9234
9235    /// Every one of the four production `.variant()` inherent methods
9236    /// dispatches through the trait's default body byte-identically —
9237    /// pin the delegation shape (inherent forwarder → trait default)
9238    /// on a probe per parent so a regression that copies the pre-lift
9239    /// hand-rolled `resolve_or_err(...)` body back into the inherent
9240    /// method (instead of the `<Self as TaggedUnion>::variant(self)`
9241    /// one-line delegation) reaches this substrate boundary before it
9242    /// reaches any operator diagnostic.
9243    #[test]
9244    fn every_production_inherent_variant_dispatches_through_trait_default() {
9245        use crate::encapsulates::{EncapsulationKind, EncapsulationKindError};
9246        use crate::export::{ArtifactError, ArtifactSource, ChannelError, VectorChannel};
9247        use crate::intent::{Intent, IntentError};
9248
9249        // Intent: default of all-None resolves to Empty via the delegation.
9250        let i = Intent::default();
9251        match (i.variant(), <Intent as TaggedUnion>::variant(&i)) {
9252            (Err(IntentError::Empty(a)), Err(IntentError::Empty(b))) => assert!(
9253                std::ptr::eq(a, b),
9254                "Intent inherent and trait dispatch must return the same &'static str",
9255            ),
9256            (a, b) => panic!("Intent inherent/trait mismatch: inherent={a:?}, trait={b:?}"),
9257        }
9258
9259        // EncapsulationKind: same Empty projection through both dispatch paths.
9260        let k = EncapsulationKind::default();
9261        match (k.variant(), <EncapsulationKind as TaggedUnion>::variant(&k)) {
9262            (Err(EncapsulationKindError::Empty(a)), Err(EncapsulationKindError::Empty(b))) => {
9263                assert!(
9264                std::ptr::eq(a, b),
9265                "EncapsulationKind inherent and trait dispatch must return the same &'static str",
9266            )
9267            }
9268            (a, b) => {
9269                panic!("EncapsulationKind inherent/trait mismatch: inherent={a:?}, trait={b:?}")
9270            }
9271        }
9272
9273        // ArtifactSource: same Empty projection through both dispatch paths.
9274        let s = ArtifactSource::default();
9275        match (s.variant(), <ArtifactSource as TaggedUnion>::variant(&s)) {
9276            (Err(ArtifactError::Empty(a)), Err(ArtifactError::Empty(b))) => assert!(
9277                std::ptr::eq(a, b),
9278                "ArtifactSource inherent and trait dispatch must return the same &'static str",
9279            ),
9280            (a, b) => panic!("ArtifactSource inherent/trait mismatch: inherent={a:?}, trait={b:?}"),
9281        }
9282
9283        // VectorChannel: same Empty projection through both dispatch paths.
9284        let c = VectorChannel::default();
9285        match (c.variant(), <VectorChannel as TaggedUnion>::variant(&c)) {
9286            (Err(ChannelError::Empty(a)), Err(ChannelError::Empty(b))) => assert!(
9287                std::ptr::eq(a, b),
9288                "VectorChannel inherent and trait dispatch must return the same &'static str",
9289            ),
9290            (a, b) => panic!("VectorChannel inherent/trait mismatch: inherent={a:?}, trait={b:?}"),
9291        }
9292    }
9293
9294    // -------------------------------------------------------------------
9295    // `declare_tagged_union_impls!` macro — the three-block impl stanza
9296    // (inherent `.variant()` forwarder + `VariantSelector<Parent>` on
9297    // the Kind + `TaggedUnion` on the parent) as ONE authoring surface.
9298    // Pin the macro's shape against a sibling-shaped local family so a
9299    // regression on any of the three emitted blocks fails here before
9300    // it reaches the four production sites.
9301    // -------------------------------------------------------------------
9302
9303    /// Local sibling-shaped Kind for the macro-emitted-impls test — a
9304    /// dedicated closed set so this test can't share substrate with the
9305    /// hand-rolled [`LocalKind`] block above. Uses
9306    /// [`tatara_closed_set::DeriveClosedSet`] so the macro's
9307    /// `TaggedUnion` bound (`Kind: ClosedSet + VariantSelector<Self>`)
9308    /// is satisfied through the derive.
9309    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
9310    #[closed_set(via = "as_str", generate_unknown)]
9311    enum MacroLocalKind {
9312        Foo,
9313        Bar,
9314    }
9315
9316    impl MacroLocalKind {
9317        const ALL: [Self; 2] = [Self::Foo, Self::Bar];
9318        const fn as_str(self) -> &'static str {
9319            match self {
9320                Self::Foo => "foo",
9321                Self::Bar => "bar",
9322            }
9323        }
9324        fn select<'a>(self, parent: &'a MacroLocalParent) -> Option<MacroLocalVariant<'a>> {
9325            match self {
9326                Self::Foo => parent.foo.as_ref().map(MacroLocalVariant::Foo),
9327                Self::Bar => parent.bar.as_ref().map(MacroLocalVariant::Bar),
9328            }
9329        }
9330    }
9331
9332    /// Local sibling-shaped parent for the macro-emitted-impls test —
9333    /// distinct from [`LocalParent`] so the macro's emitted impls
9334    /// don't collide with the hand-rolled trait impls above.
9335    ///
9336    /// Derives [`serde::Serialize`] with `skip_serializing_if =
9337    /// "Option::is_none"` on every slot so the wire-format primitive
9338    /// [`assert_single_slot_key_matches_label`] can be exercised
9339    /// through the macro-emitted `TaggedUnion` impl path — pins the
9340    /// substrate-wide guarantee that a fifth sibling landing through
9341    /// [`declare_tagged_union_impls!`] picks up the wire-alignment
9342    /// check for free.
9343    #[derive(Default, serde::Serialize)]
9344    struct MacroLocalParent {
9345        #[serde(skip_serializing_if = "Option::is_none")]
9346        foo: Option<u32>,
9347        #[serde(skip_serializing_if = "Option::is_none")]
9348        bar: Option<u32>,
9349    }
9350
9351    /// Borrowed-view of a populated slot on [`MacroLocalParent`] — the
9352    /// return type of the macro-emitted inherent `.variant()`.
9353    #[derive(Debug, PartialEq)]
9354    enum MacroLocalVariant<'a> {
9355        Foo(&'a u32),
9356        Bar(&'a u32),
9357    }
9358
9359    impl VariantKind<MacroLocalKind> for MacroLocalVariant<'_> {
9360        fn variant_kind(&self) -> MacroLocalKind {
9361            match self {
9362                Self::Foo(_) => MacroLocalKind::Foo,
9363                Self::Bar(_) => MacroLocalKind::Bar,
9364            }
9365        }
9366    }
9367
9368    crate::declare_tagged_union_error! {
9369        pub(super) MacroLocalError,
9370        empty = "macro-local parent has no variant set (one of {0} required)",
9371        ambiguous = "macro-local parent has multiple variants set; exactly one required",
9372    }
9373
9374    /// Slash-joined kind list — literal peer of
9375    /// [`crate::intent::INTENT_KIND_LIST`] etc. that the macro's
9376    /// `KIND_LIST` associated const borrows verbatim.
9377    const MACRO_LOCAL_KIND_LIST: &str = "foo/bar";
9378
9379    // ONE macro call emits: inherent `MacroLocalParent::variant`,
9380    // `impl VariantSelector<MacroLocalParent> for MacroLocalKind`, and
9381    // `impl TaggedUnion for MacroLocalParent`. The four production
9382    // sites bind through this exact same call shape.
9383    crate::declare_tagged_union_impls! {
9384        parent = MacroLocalParent,
9385        kind = MacroLocalKind,
9386        variant = MacroLocalVariant,
9387        error = MacroLocalError,
9388        kind_list = MACRO_LOCAL_KIND_LIST,
9389    }
9390
9391    /// The macro-emitted `impl TaggedUnion` binds the (Kind, Error,
9392    /// KIND_LIST) triple exactly as a hand-rolled block would — pin
9393    /// the diagnostic-stability testkit primitive through the macro's
9394    /// output so a regression on any of the three associated items
9395    /// (say the macro pulling `KIND_LIST` from the wrong argument
9396    /// slot) fails here.
9397    #[test]
9398    fn macro_emitted_tagged_union_impl_binds_kind_list_coherently() {
9399        assert_kind_list_matches_closed_set::<MacroLocalParent>();
9400        assert!(std::ptr::eq(
9401            <MacroLocalParent as TaggedUnion>::KIND_LIST,
9402            MACRO_LOCAL_KIND_LIST,
9403        ));
9404    }
9405
9406    /// The macro-emitted inherent `.variant()` forwarder dispatches
9407    /// through the trait default body — every populated slot resolves
9408    /// to its own [`MacroLocalVariant`] arm, all-none resolves to
9409    /// [`TaggedUnionError::empty`] carrying the trait's `KIND_LIST`
9410    /// by pointer, two-populated resolves to
9411    /// [`TaggedUnionError::ambiguous`]. The four production sites
9412    /// exercise the same four-outcome truth table through the same
9413    /// macro-emitted delegation shape.
9414    #[test]
9415    fn macro_emitted_inherent_variant_dispatches_the_four_outcome_truth_table() {
9416        // Foo populated.
9417        let p = MacroLocalParent {
9418            foo: Some(11),
9419            bar: None,
9420        };
9421        assert_eq!(p.variant().unwrap(), MacroLocalVariant::Foo(&11));
9422
9423        // Bar populated.
9424        let p = MacroLocalParent {
9425            foo: None,
9426            bar: Some(22),
9427        };
9428        assert_eq!(p.variant().unwrap(), MacroLocalVariant::Bar(&22));
9429
9430        // All none — Empty arm carries the trait's KIND_LIST value.
9431        // The by-pointer preservation across the trait default body is
9432        // pinned substrate-wide by
9433        // `tagged_union_default_variant_empty_carries_kind_list_by_pointer`
9434        // on the sibling hand-rolled `LocalParent`; this test only pins
9435        // that the macro-emitted `KIND_LIST = MACRO_LOCAL_KIND_LIST`
9436        // assignment reaches the operator diagnostic value-identically.
9437        let p = MacroLocalParent::default();
9438        match p.variant().unwrap_err() {
9439            MacroLocalError::Empty(list) => assert_eq!(list, MACRO_LOCAL_KIND_LIST),
9440            MacroLocalError::Ambiguous => panic!("expected Empty, got Ambiguous"),
9441        }
9442
9443        // Two populated — Ambiguous.
9444        let p = MacroLocalParent {
9445            foo: Some(1),
9446            bar: Some(2),
9447        };
9448        assert_eq!(p.variant().unwrap_err(), MacroLocalError::Ambiguous);
9449    }
9450
9451    /// The macro-emitted inherent `.has()` forwarder dispatches
9452    /// through the trait default body — the presence probe agrees
9453    /// with `Kind::select(&parent).is_some()` on the diagonal
9454    /// (populated slot AND matching Kind → `true`) and off the
9455    /// diagonal (populated slot BUT other Kind → `false`) for the
9456    /// same four-outcome truth table the macro-emitted `.variant()`
9457    /// covers. The four production sites bind through this exact
9458    /// same macro-emitted delegation shape; the substrate testkit
9459    /// primitive [`assert_has_matches_select`] sweeps this contract
9460    /// generically once each production Kind picks up the macro's
9461    /// output.
9462    #[test]
9463    fn macro_emitted_inherent_has_dispatches_the_presence_probe_diagonal() {
9464        // Foo populated → has(Foo) is true, has(Bar) is false.
9465        let p = MacroLocalParent {
9466            foo: Some(11),
9467            bar: None,
9468        };
9469        assert!(p.has(MacroLocalKind::Foo));
9470        assert!(!p.has(MacroLocalKind::Bar));
9471
9472        // Bar populated → has(Bar) is true, has(Foo) is false.
9473        let p = MacroLocalParent {
9474            foo: None,
9475            bar: Some(22),
9476        };
9477        assert!(!p.has(MacroLocalKind::Foo));
9478        assert!(p.has(MacroLocalKind::Bar));
9479
9480        // All none — every probe is false; no Empty carrier
9481        // allocation on this path (the presence-probe half of the
9482        // resolve contract deliberately elides diagnostic composition
9483        // when the caller only needs yes/no).
9484        let p = MacroLocalParent::default();
9485        assert!(!p.has(MacroLocalKind::Foo));
9486        assert!(!p.has(MacroLocalKind::Bar));
9487
9488        // Two populated — has(k) is true for BOTH populated slots
9489        // (the probe is a per-slot projection, not the parent-wide
9490        // resolver — Ambiguous is a resolve outcome, not a presence
9491        // outcome).
9492        let p = MacroLocalParent {
9493            foo: Some(1),
9494            bar: Some(2),
9495        };
9496        assert!(p.has(MacroLocalKind::Foo));
9497        assert!(p.has(MacroLocalKind::Bar));
9498    }
9499
9500    /// The macro-emitted inherent `.find()` forwarder dispatches
9501    /// through the trait default body — every populated slot resolves
9502    /// to `Some(matching-borrow)`, empty slots to `None`, and the
9503    /// composition law `parent.has(k) == parent.find(k).is_some()`
9504    /// holds at every arm of the four-outcome truth table. Additional
9505    /// pointer-identity pin: the borrowed reference returned by
9506    /// `p.find(k)` on a populated slot IS the same reference that
9507    /// `<Kind>::select(k, &p)` returns — a regression that inlines a
9508    /// divergent projection body at the macro's emitted forwarder
9509    /// (rather than reaching the trait's `<Self as
9510    /// TaggedUnion>::find(self, kind)` one-line delegation) is caught
9511    /// here.
9512    #[test]
9513    fn macro_emitted_inherent_find_dispatches_the_presence_probe_diagonal() {
9514        // Foo populated → find(Foo) borrows the inner ref, find(Bar)
9515        // is None, and `has` agrees with `find(...).is_some()` on
9516        // both arms.
9517        let p = MacroLocalParent {
9518            foo: Some(77),
9519            bar: None,
9520        };
9521        match p.find(MacroLocalKind::Foo) {
9522            Some(MacroLocalVariant::Foo(v)) => {
9523                assert_eq!(*v, 77, "find must borrow the populated inner");
9524                assert_eq!(
9525                    p.has(MacroLocalKind::Foo),
9526                    true,
9527                    "composition law: has must agree with find(...).is_some() on populated slot",
9528                );
9529                // Pointer-identity check: `find` delegates to
9530                // `kind.select(self)` byte-identically. The returned
9531                // borrow IS the borrow `select` returns.
9532                let via_select = MacroLocalKind::Foo.select(&p).unwrap();
9533                match via_select {
9534                    MacroLocalVariant::Foo(w) => assert!(
9535                        std::ptr::eq(v, w),
9536                        "macro-emitted find must return the SAME borrow as VariantSelector::select",
9537                    ),
9538                    MacroLocalVariant::Bar(_) => {
9539                        panic!(
9540                            "VariantSelector::select disagreed with find on the populated Foo slot"
9541                        )
9542                    }
9543                }
9544            }
9545            other => panic!("expected Foo populated, got {other:?}"),
9546        }
9547        assert!(p.find(MacroLocalKind::Bar).is_none());
9548        assert_eq!(
9549            p.has(MacroLocalKind::Bar),
9550            false,
9551            "composition law: has must agree with find(...).is_some() on empty slot",
9552        );
9553
9554        // All none — find returns None for every kind; has agrees.
9555        let p = MacroLocalParent::default();
9556        for kind in MacroLocalKind::ALL {
9557            assert!(p.find(kind).is_none());
9558            assert_eq!(
9559                p.has(kind),
9560                false,
9561                "composition law on empty parent: has must equal find(...).is_some()",
9562            );
9563        }
9564
9565        // Two populated — find(k) is Some for BOTH populated slots
9566        // (the widened primitive is a per-slot projection, not the
9567        // parent-wide resolver — Ambiguous is a resolve outcome, not
9568        // a find outcome).
9569        let p = MacroLocalParent {
9570            foo: Some(1),
9571            bar: Some(2),
9572        };
9573        assert!(p.find(MacroLocalKind::Foo).is_some());
9574        assert!(p.find(MacroLocalKind::Bar).is_some());
9575    }
9576
9577    /// The macro-emitted `VariantSelector` impl's `select` body
9578    /// delegates to the Kind's inherent `<Kind>::select(self, parent)`
9579    /// — pin the delegation via `std::ptr::eq` on the returned
9580    /// borrowed view so a regression that inlines a divergent select
9581    /// body (rather than reaching the inherent method) is caught here.
9582    #[test]
9583    fn macro_emitted_variant_selector_delegates_to_inherent_select() {
9584        let p = MacroLocalParent {
9585            foo: Some(7),
9586            bar: None,
9587        };
9588        // Trait-dispatched select projects through the macro-emitted body.
9589        let via_trait =
9590            <MacroLocalKind as VariantSelector<MacroLocalParent>>::select(MacroLocalKind::Foo, &p)
9591                .unwrap();
9592        // Inherent select projects through the direct impl.
9593        let via_inherent = MacroLocalKind::Foo.select(&p).unwrap();
9594        match (via_trait, via_inherent) {
9595            (MacroLocalVariant::Foo(a), MacroLocalVariant::Foo(b)) => {
9596                assert!(
9597                    std::ptr::eq(a, b),
9598                    "macro-emitted VariantSelector::select must delegate to <Kind>::select — same borrow, not a copy",
9599                );
9600            }
9601            _ => panic!("expected Foo arm on both dispatch paths"),
9602        }
9603    }
9604
9605    /// The trait's default body sweeps `<Kind as ClosedSet>::ALL` in
9606    /// declaration order — pin the iteration order against the
9607    /// production `Kind::ALL` inherent const on every implementor so
9608    /// a regression on `DeriveClosedSet`'s ALL-projection (or a
9609    /// silent reorder of the enum's variant declarations that drifts
9610    /// only ONE of the two arrays) fails at ONE substrate boundary.
9611    #[test]
9612    fn every_production_kind_closedset_all_matches_inherent_all() {
9613        use crate::encapsulates::EncapsulationTarget;
9614        use crate::export::{ArtifactKind, ChannelKind};
9615        use crate::intent::IntentKind;
9616
9617        assert_eq!(
9618            <IntentKind as tatara_closed_set::ClosedSet>::ALL,
9619            IntentKind::ALL.as_slice(),
9620        );
9621        assert_eq!(
9622            <EncapsulationTarget as tatara_closed_set::ClosedSet>::ALL,
9623            EncapsulationTarget::ALL.as_slice(),
9624        );
9625        assert_eq!(
9626            <ArtifactKind as tatara_closed_set::ClosedSet>::ALL,
9627            ArtifactKind::ALL.as_slice(),
9628        );
9629        assert_eq!(
9630            <ChannelKind as tatara_closed_set::ClosedSet>::ALL,
9631            ChannelKind::ALL.as_slice(),
9632        );
9633    }
9634
9635    // -------------------------------------------------------------------
9636    // `VariantKind<K>` trait — reverse projection from a borrowed-variant
9637    // view back into its addressing Kind, and `assert_variant_round_trip`
9638    // as the substrate testkit primitive that composes it with
9639    // `VariantSelector::select` on the populated side. Pin the four-arm
9640    // truth table (every position round-trips through select→variant_kind
9641    // AND through variant()→variant_kind) directly on the sibling-shaped
9642    // local scaffold, so a regression on either projection or on the
9643    // resolver default body fails here — before any per-parent inherent
9644    // test surfaces the drift.
9645    // -------------------------------------------------------------------
9646
9647    /// Every populated position across [`LocalKind::ALL`] round-trips
9648    /// through both `select→variant_kind` AND `variant()→variant_kind`
9649    /// on the sibling-shaped local scaffold. Pins the substrate
9650    /// primitive's four-arm truth table at ONE boundary — a regression
9651    /// on either projection direction (or on the resolver default
9652    /// short-circuit / iteration order) fails here before any per-parent
9653    /// inherent test surfaces the drift.
9654    #[test]
9655    fn assert_variant_round_trip_accepts_coherent_local_impl() {
9656        fn make_local(k: LocalKind) -> LocalParent {
9657            match k {
9658                LocalKind::Alpha => LocalParent {
9659                    alpha: Some(11),
9660                    ..Default::default()
9661                },
9662                LocalKind::Beta => LocalParent {
9663                    beta: Some(22),
9664                    ..Default::default()
9665                },
9666                LocalKind::Gamma => LocalParent {
9667                    gamma: Some(33),
9668                    ..Default::default()
9669                },
9670            }
9671        }
9672        assert_variant_round_trip::<LocalParent, _>(make_local);
9673    }
9674
9675    /// The testkit primitive is a `#[track_caller]` compound-lift: a
9676    /// factory that fails to populate the addressed slot fails at the
9677    /// caller's site with a labeled panic message, not silently. Pin
9678    /// the failing case with a deliberately empty parent factory so a
9679    /// regression that drops the "select must return Some" check
9680    /// fails-loudly here — the missing-slot arm is the substrate
9681    /// primitive's first failure mode.
9682    #[test]
9683    #[should_panic(expected = "VariantSelector::select must return Some for populated slot")]
9684    fn assert_variant_round_trip_rejects_factory_that_leaves_slot_empty() {
9685        // Factory that returns an all-empty parent regardless of k —
9686        // every `k.select(&parent)` returns None, so the primitive
9687        // panics at the "must return Some" arm.
9688        fn empty_factory(_: LocalKind) -> LocalParent {
9689            LocalParent::default()
9690        }
9691        assert_variant_round_trip::<LocalParent, _>(empty_factory);
9692    }
9693
9694    // -------------------------------------------------------------------
9695    // `TaggedUnion::find` — the widened peer of `TaggedUnion::has` on the
9696    // presence-probe algebra. Pin every arm of the four-outcome truth
9697    // table (empty parent → None, populated-diagonal → Some(matching
9698    // borrow), populated-off-diagonal → None, two-populated → Some for
9699    // BOTH populated slots) directly on the sibling-shaped local scaffold
9700    // AND on the macro-emitted inherent surface. A regression on the
9701    // default body's `kind.select(self)` delegation (or on the emitted
9702    // inherent forwarder's `<Self as TaggedUnion>::find(self, kind)`
9703    // one-line body) fails here before it reaches any of the four
9704    // production sites.
9705    // -------------------------------------------------------------------
9706
9707    /// EMPTY-PARENT pin — a default [`LocalParent`] returns `None` at
9708    /// `find` for EVERY [`LocalKind`], sweeping `ClosedSet::ALL` so a
9709    /// new variant added without a matching arm in the primitive
9710    /// surfaces at rustc's exhaustiveness gate on the ALL literal
9711    /// rather than as a silent false-positive at every downstream
9712    /// consumer composing this primitive.
9713    #[test]
9714    fn tagged_union_default_find_returns_none_on_empty_parent_for_every_kind() {
9715        let empty = LocalParent::default();
9716        for kind in <LocalKind as tatara_closed_set::ClosedSet>::ALL
9717            .iter()
9718            .copied()
9719        {
9720            assert!(
9721                <LocalParent as TaggedUnion>::find(&empty, kind).is_none(),
9722                "empty parent must return None at find for {kind:?}",
9723            );
9724        }
9725    }
9726
9727    /// DELEGATION pin — every populated position across
9728    /// [`LocalKind::ALL`] returns `Some(matching-borrow)` at `find`,
9729    /// AND the returned borrowed view carries the SAME reference as
9730    /// `probed.select(&parent).unwrap()` (byte-identical delegation:
9731    /// `find` IS `kind.select(self)`, not a re-projection).
9732    /// Composition-law pin: `has(k) == find(k).is_some()` on both
9733    /// diagonal (populated slot AND matching Kind → true) and
9734    /// off-diagonal (populated slot BUT other Kind → false).
9735    #[test]
9736    fn tagged_union_default_find_delegates_to_select_across_every_kind() {
9737        for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
9738            .iter()
9739            .copied()
9740        {
9741            let parent = match populated {
9742                LocalKind::Alpha => LocalParent {
9743                    alpha: Some(101),
9744                    ..Default::default()
9745                },
9746                LocalKind::Beta => LocalParent {
9747                    beta: Some(202),
9748                    ..Default::default()
9749                },
9750                LocalKind::Gamma => LocalParent {
9751                    gamma: Some(303),
9752                    ..Default::default()
9753                },
9754            };
9755            for probed in <LocalKind as tatara_closed_set::ClosedSet>::ALL
9756                .iter()
9757                .copied()
9758            {
9759                let via_find = <LocalParent as TaggedUnion>::find(&parent, probed);
9760                let via_select = probed.select(&parent);
9761                assert_eq!(
9762                    via_find.is_some(),
9763                    via_select.is_some(),
9764                    "find drifted from select — populated={populated:?} probed={probed:?}",
9765                );
9766                assert_eq!(
9767                    parent.has(probed),
9768                    via_find.is_some(),
9769                    "has drifted from find(k).is_some() — populated={populated:?} probed={probed:?}",
9770                );
9771                if let Some(v) = via_find {
9772                    assert_eq!(
9773                        <LocalVariant<'_> as VariantKind<LocalKind>>::variant_kind(&v),
9774                        probed,
9775                        "find→variant_kind round-trip failed — populated={populated:?} probed={probed:?}",
9776                    );
9777                    // Populated iff probed == populated (single-slot
9778                    // parent) — off-diagonal arms return None above
9779                    // and never reach this Some-branch.
9780                    assert_eq!(
9781                        probed, populated,
9782                        "off-diagonal probe should have returned None at find",
9783                    );
9784                }
9785            }
9786        }
9787    }
9788
9789    /// TWO-POPULATED pin — a parent with two populated slots returns
9790    /// `Some(matching-borrow)` at `find` for BOTH populated Kinds
9791    /// (unlike `variant()` which resolves to `Ambiguous`), and `None`
9792    /// for the empty third Kind. Locks the presence-probe axis of the
9793    /// widened primitive against a regression that inlined the
9794    /// resolver's short-circuit body into `find` (silently narrowing
9795    /// two populated to Ambiguous instead of a per-slot borrow).
9796    #[test]
9797    fn tagged_union_default_find_projects_per_slot_on_multi_populated_parent() {
9798        let parent = LocalParent {
9799            alpha: Some(1),
9800            beta: Some(2),
9801            gamma: None,
9802        };
9803        assert!(
9804            <LocalParent as TaggedUnion>::find(&parent, LocalKind::Alpha).is_some(),
9805            "find must project Alpha slot in a two-populated parent",
9806        );
9807        assert!(
9808            <LocalParent as TaggedUnion>::find(&parent, LocalKind::Beta).is_some(),
9809            "find must project Beta slot in a two-populated parent",
9810        );
9811        assert!(
9812            <LocalParent as TaggedUnion>::find(&parent, LocalKind::Gamma).is_none(),
9813            "find must return None for the empty Gamma slot",
9814        );
9815    }
9816
9817    /// `assert_find_agrees_with_has` testkit accepts the coherent
9818    /// local scaffold — sweeping every `(populated, probed)` pair
9819    /// through the three sub-assertions (find↔has, find↔select,
9820    /// diagonal round-trip). A regression on any of the three
9821    /// composition laws fails at the substrate primitive's
9822    /// `#[track_caller]` boundary here rather than at four per-parent
9823    /// production sites downstream.
9824    #[test]
9825    fn assert_find_agrees_with_has_accepts_coherent_local_impl() {
9826        fn make_local(k: LocalKind) -> LocalParent {
9827            match k {
9828                LocalKind::Alpha => LocalParent {
9829                    alpha: Some(11),
9830                    ..Default::default()
9831                },
9832                LocalKind::Beta => LocalParent {
9833                    beta: Some(22),
9834                    ..Default::default()
9835                },
9836                LocalKind::Gamma => LocalParent {
9837                    gamma: Some(33),
9838                    ..Default::default()
9839                },
9840            }
9841        }
9842        assert_find_agrees_with_has::<LocalParent, _>(make_local);
9843    }
9844
9845    // -------------------------------------------------------------------
9846    // `TaggedUnion::populated_kinds` default method + the
9847    // closed-set-inversion refinement's per-parent semantics — pin the
9848    // three arms (empty parent → empty vec, single-slot → vec![k],
9849    // multi-populated → vec[a..b] in ClosedSet::ALL order) directly on
9850    // the sibling-shaped `LocalParent` scaffold. Peer of the boundary-
9851    // side `ConditionSliceExt::distinct_kinds` primitive's three-arm
9852    // pin on the slice-level presence-probe axis.
9853    // -------------------------------------------------------------------
9854
9855    /// EMPTY parent — the default body's `ALL.filter(has).collect()`
9856    /// sweep yields an empty vec when no slot is populated. Pins the
9857    /// zero-cardinality arm: a regression that mis-composed the
9858    /// `ALL.iter()` bridge (short-circuiting past the empty case),
9859    /// returned a non-empty sentinel on empty input, or leaked stale
9860    /// closed-set entries as false-positive members fails HERE at the
9861    /// substrate boundary.
9862    #[test]
9863    fn tagged_union_default_populated_kinds_returns_empty_vec_on_empty_parent() {
9864        let empty = LocalParent::default();
9865        assert!(
9866            <LocalParent as TaggedUnion>::populated_kinds(&empty).is_empty(),
9867            "populated_kinds() must return empty Vec when no slot is populated",
9868        );
9869    }
9870
9871    /// SINGLE-SLOT parent — the default body sweeps `ClosedSet::ALL`
9872    /// with `has(k)` and collects the singleton `[k]` for each
9873    /// single-populated arrangement. Pins the length-1 arm's
9874    /// cardinality (must be exactly 1) AND ordering (the addressed
9875    /// kind's own position in `ClosedSet::ALL`) at ONE `assert_eq!`
9876    /// per kind — a regression that projected the wrong Kind, drifted
9877    /// the walk from `has` to a divergent projection, or paired two
9878    /// kinds together on a single-slot input fails HERE per addressed
9879    /// kind. Sweeps every `LocalKind::ALL` entry so no per-variant
9880    /// specialization can silently drop the check.
9881    #[test]
9882    fn tagged_union_default_populated_kinds_returns_single_element_vec_per_variant() {
9883        for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
9884            .iter()
9885            .copied()
9886        {
9887            let parent = match populated {
9888                LocalKind::Alpha => LocalParent {
9889                    alpha: Some(11),
9890                    ..Default::default()
9891                },
9892                LocalKind::Beta => LocalParent {
9893                    beta: Some(22),
9894                    ..Default::default()
9895                },
9896                LocalKind::Gamma => LocalParent {
9897                    gamma: Some(33),
9898                    ..Default::default()
9899                },
9900            };
9901            assert_eq!(
9902                <LocalParent as TaggedUnion>::populated_kinds(&parent),
9903                vec![populated],
9904                "single-slot parent must return exactly [{populated:?}] on populated_kinds",
9905            );
9906        }
9907    }
9908
9909    /// MULTI-POPULATED parent — the default body yields the canonical
9910    /// `ClosedSet::ALL`-ordered pair `[Alpha, Beta]` for a two-slot
9911    /// arrangement populated in the CONSTRUCTION order `(Beta, Alpha)`.
9912    /// Pins the walk order arm: a regression that yielded slot-
9913    /// construction-order (`[Beta, Alpha]`) instead of canonical
9914    /// `ALL`-order fails HERE at the equality assert. Also pins the
9915    /// non-short-circuiting arm — a regression that inlined the
9916    /// resolver's short-circuit body into `populated_kinds` (silently
9917    /// narrowing two populated to a length-1 vec containing the first
9918    /// slot) fails at the length side of the equality.
9919    #[test]
9920    fn tagged_union_default_populated_kinds_walks_canonical_all_order_on_multi_populated_parent() {
9921        let parent = LocalParent {
9922            alpha: Some(1),
9923            beta: Some(2),
9924            gamma: None,
9925        };
9926        assert_eq!(
9927            <LocalParent as TaggedUnion>::populated_kinds(&parent),
9928            vec![LocalKind::Alpha, LocalKind::Beta],
9929            "multi-populated parent must return canonical ClosedSet::ALL-ordered kinds",
9930        );
9931    }
9932
9933    /// SATURATED parent — every slot populated returns
9934    /// `LocalKind::ALL.to_vec()` exactly. Pins the full-closed-set-
9935    /// coverage arm: a `[1..]` or `[..ALL.len() - 1]` walk bug that
9936    /// silently truncated the swept range at either end surfaces at
9937    /// the equality assert here.
9938    #[test]
9939    fn tagged_union_default_populated_kinds_covers_full_closed_set_on_saturated_parent() {
9940        let saturated = LocalParent {
9941            alpha: Some(1),
9942            beta: Some(2),
9943            gamma: Some(3),
9944        };
9945        assert_eq!(
9946            <LocalParent as TaggedUnion>::populated_kinds(&saturated),
9947            <LocalKind as tatara_closed_set::ClosedSet>::ALL.to_vec(),
9948            "saturated parent must return ClosedSet::ALL.to_vec() on populated_kinds",
9949        );
9950    }
9951
9952    /// `assert_populated_kinds_matches_has` testkit accepts the
9953    /// coherent local scaffold — sweeping every `(populated, probed)`
9954    /// pair through the three sub-assertions (per-kind membership,
9955    /// canonical `ALL`-filter equality, single-slot diagonal). A
9956    /// regression on any of the three composition laws fails at the
9957    /// substrate primitive's `#[track_caller]` boundary here rather
9958    /// than at four per-parent production sites downstream.
9959    #[test]
9960    fn assert_populated_kinds_matches_has_accepts_coherent_local_impl() {
9961        fn make_local(k: LocalKind) -> LocalParent {
9962            match k {
9963                LocalKind::Alpha => LocalParent {
9964                    alpha: Some(11),
9965                    ..Default::default()
9966                },
9967                LocalKind::Beta => LocalParent {
9968                    beta: Some(22),
9969                    ..Default::default()
9970                },
9971                LocalKind::Gamma => LocalParent {
9972                    gamma: Some(33),
9973                    ..Default::default()
9974                },
9975            }
9976        }
9977        assert_populated_kinds_matches_has::<LocalParent, _>(make_local);
9978    }
9979
9980    /// A factory that yields an all-empty parent (so
9981    /// `populated_kinds()` returns `[]`) MUST fail-loudly at the
9982    /// caller's site through the primitive's single-slot diagonal
9983    /// arm — the empty vec does not equal `vec![populated]` for the
9984    /// swept `populated` kind. Pin the diagonal-arm failure mode so
9985    /// a regression that silently succeeded on an all-empty factory
9986    /// (e.g. the primitive was refactored to skip the diagonal
9987    /// assert on `kinds.is_empty()`) is caught here.
9988    #[test]
9989    #[should_panic(expected = "must return vec![Alpha] exactly")]
9990    fn assert_populated_kinds_matches_has_rejects_factory_that_populates_no_slots() {
9991        fn empty_factory(_: LocalKind) -> LocalParent {
9992            LocalParent::default()
9993        }
9994        assert_populated_kinds_matches_has::<LocalParent, _>(empty_factory);
9995    }
9996
9997    /// A factory that yields a two-slot parent (so
9998    /// `populated_kinds()` returns `[k1, k2]` for TWO populated
9999    /// slots on a supposedly single-slot factory) MUST fail-loudly at
10000    /// the caller's site through the primitive's single-slot diagonal
10001    /// arm — the length-2 vec does not equal `vec![populated]`. Pin
10002    /// the diagonal-arm cardinality failure mode so a regression that
10003    /// silently succeeded on a broken factory (populating both the
10004    /// addressed slot AND an extra one) is caught here.
10005    #[test]
10006    #[should_panic(expected = "must return vec![Alpha] exactly")]
10007    fn assert_populated_kinds_matches_has_rejects_factory_that_populates_extra_slot() {
10008        fn always_pair(k: LocalKind) -> LocalParent {
10009            let mut p = LocalParent {
10010                gamma: Some(99),
10011                ..Default::default()
10012            };
10013            match k {
10014                LocalKind::Alpha => p.alpha = Some(11),
10015                LocalKind::Beta => p.beta = Some(22),
10016                LocalKind::Gamma => p.gamma = Some(33),
10017            }
10018            p
10019        }
10020        assert_populated_kinds_matches_has::<LocalParent, _>(always_pair);
10021    }
10022
10023    /// `assert_populated_kinds_across_pairs` testkit accepts the
10024    /// coherent local scaffold — sweeping every off-diagonal `(a, b)`
10025    /// pair through the three sub-assertions (cardinality-2,
10026    /// per-kind membership, canonical `ALL`-filter equality). A
10027    /// regression on any of the three composition laws (or on the
10028    /// diagonal-skip) fails at the substrate primitive's
10029    /// `#[track_caller]` boundary here rather than at four per-parent
10030    /// production sites downstream.
10031    #[test]
10032    fn assert_populated_kinds_across_pairs_accepts_coherent_local_impl() {
10033        fn two_local(a: LocalKind, b: LocalKind) -> LocalParent {
10034            let mut p = LocalParent::default();
10035            for k in [a, b] {
10036                match k {
10037                    LocalKind::Alpha => p.alpha = Some(11),
10038                    LocalKind::Beta => p.beta = Some(22),
10039                    LocalKind::Gamma => p.gamma = Some(33),
10040                }
10041            }
10042            p
10043        }
10044        assert_populated_kinds_across_pairs::<LocalParent, _>(two_local);
10045    }
10046
10047    /// A two-slot factory that yields a single-populated parent (so
10048    /// `populated_kinds()` returns `[k1]` for a two-slot input) MUST
10049    /// fail-loudly at the caller's site through the primitive's
10050    /// cardinality-2 arm — the length-1 vec does not satisfy
10051    /// `kinds.len() == 2`. Pin the cardinality-arm failure mode so a
10052    /// regression that silently succeeded on a broken factory
10053    /// (populating only the first of the two addressed slots) is
10054    /// caught here.
10055    #[test]
10056    #[should_panic(expected = "must return exactly two populated kinds")]
10057    fn assert_populated_kinds_across_pairs_rejects_factory_that_populates_only_one_slot() {
10058        fn single_only(a: LocalKind, _: LocalKind) -> LocalParent {
10059            let mut p = LocalParent::default();
10060            match a {
10061                LocalKind::Alpha => p.alpha = Some(11),
10062                LocalKind::Beta => p.beta = Some(22),
10063                LocalKind::Gamma => p.gamma = Some(33),
10064            }
10065            p
10066        }
10067        assert_populated_kinds_across_pairs::<LocalParent, _>(single_only);
10068    }
10069
10070    /// Every one of the four production `.variant()` sites on
10071    /// `ProcessSpec` binds through the single-slot closed-set-inversion
10072    /// primitive `assert_populated_kinds_matches_has` coherently — every
10073    /// per-site `single_slot_X(k)` factory produces a parent whose
10074    /// `populated_kinds()` equals `vec![k]` and whose per-kind
10075    /// composition law `populated_kinds().contains(&k) == has(k)` holds
10076    /// for every `k ∈ ClosedSet::ALL`. Sweep every production
10077    /// implementor at ONE substrate boundary so a regression that
10078    /// drifts a production site's `single_slot_X` factory OR the
10079    /// default `populated_kinds` body (a specialization that
10080    /// short-circuited, drifted the walk order, or returned duplicates)
10081    /// fails BOTH at any future per-crate test site AND at this
10082    /// substrate-wide sweep.
10083    #[test]
10084    fn every_production_tagged_union_binds_through_the_populated_kinds_testkit_primitive() {
10085        assert_populated_kinds_matches_has::<crate::intent::Intent, _>(single_slot_intent_probe);
10086        assert_populated_kinds_matches_has::<crate::encapsulates::EncapsulationKind, _>(
10087            single_slot_encapsulation_kind_probe,
10088        );
10089        assert_populated_kinds_matches_has::<crate::export::ArtifactSource, _>(
10090            single_slot_artifact_source_probe,
10091        );
10092        assert_populated_kinds_matches_has::<crate::export::VectorChannel, _>(
10093            single_slot_vector_channel_probe,
10094        );
10095    }
10096
10097    /// Peer of
10098    /// `every_production_tagged_union_binds_through_the_populated_kinds_testkit_primitive`
10099    /// on the two-slot ambiguous-parent side — every production
10100    /// `.variant()` parent binds through the pair primitive
10101    /// `assert_populated_kinds_across_pairs` coherently, so a
10102    /// regression that inlined the resolver's short-circuit body into
10103    /// `populated_kinds` on any production site (silently narrowing
10104    /// two populated slots to a length-1 vec) fails at ONE substrate
10105    /// boundary across all four parents.
10106    #[test]
10107    fn every_production_tagged_union_binds_through_the_populated_kinds_pair_testkit_primitive() {
10108        assert_populated_kinds_across_pairs::<crate::intent::Intent, _>(two_slot_intent_probe);
10109        assert_populated_kinds_across_pairs::<crate::encapsulates::EncapsulationKind, _>(
10110            two_slot_encapsulation_kind_probe,
10111        );
10112        assert_populated_kinds_across_pairs::<crate::export::ArtifactSource, _>(
10113            two_slot_artifact_source_probe,
10114        );
10115        assert_populated_kinds_across_pairs::<crate::export::VectorChannel, _>(
10116            two_slot_vector_channel_probe,
10117        );
10118    }
10119
10120    // -------------------------------------------------------------------
10121    // `TaggedUnion::populated_kind_count` — scalar cardinality refinement
10122    // on the closed-set-inversion axis. Pin the three arms (empty parent
10123    // → 0, single-slot → 1, multi-populated → N) directly on the sibling-
10124    // shaped `LocalParent` scaffold and the composition law
10125    // `populated_kind_count() == populated_kinds().len()` at the substrate
10126    // testkit `assert_populated_kind_count_matches_populated_kinds`. Peer
10127    // of the widened primitive `populated_kinds` (see the block above);
10128    // the scalar projection collapses the widened Vec to its length
10129    // without allocating.
10130    // -------------------------------------------------------------------
10131
10132    /// EMPTY parent — the default body's `ALL.filter(has).count()`
10133    /// sweep yields `0` when no slot is populated. Pins the zero-
10134    /// cardinality arm: a regression that mis-composed the
10135    /// `ALL.iter()` bridge (short-circuiting past the empty case),
10136    /// returned a non-zero sentinel on empty input, or leaked stale
10137    /// closed-set entries as false-positive members fails HERE at the
10138    /// substrate boundary.
10139    #[test]
10140    fn tagged_union_default_populated_kind_count_returns_zero_on_empty_parent() {
10141        let empty = LocalParent::default();
10142        assert_eq!(
10143            <LocalParent as TaggedUnion>::populated_kind_count(&empty),
10144            0,
10145            "populated_kind_count() must return 0 when no slot is populated",
10146        );
10147    }
10148
10149    /// SINGLE-SLOT parent — the default body sweeps `ClosedSet::ALL`
10150    /// with `has(k)` and counts the singleton `1` for each single-
10151    /// populated arrangement. Pins the length-1 arm's cardinality at
10152    /// ONE `assert_eq!` per kind — a regression that projected the
10153    /// wrong Kind, drifted the walk from `has` to a divergent
10154    /// projection, or paired two kinds together on a single-slot input
10155    /// fails HERE per addressed kind. Sweeps every `LocalKind::ALL`
10156    /// entry so no per-variant specialization can silently drop the
10157    /// check.
10158    #[test]
10159    fn tagged_union_default_populated_kind_count_returns_one_per_single_slot_variant() {
10160        for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
10161            .iter()
10162            .copied()
10163        {
10164            let parent = match populated {
10165                LocalKind::Alpha => LocalParent {
10166                    alpha: Some(11),
10167                    ..Default::default()
10168                },
10169                LocalKind::Beta => LocalParent {
10170                    beta: Some(22),
10171                    ..Default::default()
10172                },
10173                LocalKind::Gamma => LocalParent {
10174                    gamma: Some(33),
10175                    ..Default::default()
10176                },
10177            };
10178            assert_eq!(
10179                <LocalParent as TaggedUnion>::populated_kind_count(&parent),
10180                1,
10181                "single-slot parent must return 1 on populated_kind_count for {populated:?}",
10182            );
10183        }
10184    }
10185
10186    /// MULTI-POPULATED parent — the default body yields `2` for a two-
10187    /// slot arrangement, `3` for a fully-saturated three-slot parent.
10188    /// Pins the non-short-circuiting arm — a regression that inlined
10189    /// the resolver's short-circuit body into `populated_kind_count`
10190    /// (silently narrowing two populated to `1`) fails HERE at the
10191    /// equality assert.
10192    #[test]
10193    fn tagged_union_default_populated_kind_count_walks_full_closed_set_on_multi_populated_parent() {
10194        let two = LocalParent {
10195            alpha: Some(1),
10196            beta: Some(2),
10197            gamma: None,
10198        };
10199        assert_eq!(
10200            <LocalParent as TaggedUnion>::populated_kind_count(&two),
10201            2,
10202            "two-populated parent must return 2 on populated_kind_count",
10203        );
10204        let saturated = LocalParent {
10205            alpha: Some(1),
10206            beta: Some(2),
10207            gamma: Some(3),
10208        };
10209        assert_eq!(
10210            <LocalParent as TaggedUnion>::populated_kind_count(&saturated),
10211            3,
10212            "saturated parent must return LocalKind::ALL.len() on populated_kind_count",
10213        );
10214    }
10215
10216    /// Composition law `populated_kind_count() == populated_kinds().len()`
10217    /// binds the scalar cardinality projection to the widened primitive
10218    /// across every `ClosedSet::ALL × {empty, single_slot, two_slot,
10219    /// saturated}` combination. Pins the byte-identity of the two
10220    /// projections on the empty / single / multi / saturated arms — a
10221    /// regression that overrode `populated_kind_count` with an
10222    /// off-by-one walk, a `find(k).is_none()`-inverted body (returning
10223    /// the ABSENT count), or a divergent short-circuit fails HERE at
10224    /// the equality assert.
10225    #[test]
10226    fn tagged_union_default_populated_kind_count_matches_populated_kinds_len() {
10227        let arrangements: [LocalParent; 4] = [
10228            LocalParent::default(),
10229            LocalParent {
10230                alpha: Some(1),
10231                ..Default::default()
10232            },
10233            LocalParent {
10234                alpha: Some(1),
10235                beta: Some(2),
10236                gamma: None,
10237            },
10238            LocalParent {
10239                alpha: Some(1),
10240                beta: Some(2),
10241                gamma: Some(3),
10242            },
10243        ];
10244        for (idx, parent) in arrangements.iter().enumerate() {
10245            assert_eq!(
10246                <LocalParent as TaggedUnion>::populated_kind_count(parent),
10247                <LocalParent as TaggedUnion>::populated_kinds(parent).len(),
10248                "populated_kind_count() must equal populated_kinds().len() for arrangement idx {idx}",
10249            );
10250        }
10251    }
10252
10253    /// `assert_populated_kind_count_matches_populated_kinds` testkit
10254    /// accepts the coherent local scaffold — sweeping every populated
10255    /// kind through the two sub-assertions (composition law
10256    /// `count == kinds.len()` + single-slot diagonal `count == 1`). A
10257    /// regression on either composition law fails at the substrate
10258    /// primitive's `#[track_caller]` boundary here rather than at four
10259    /// per-parent production sites downstream.
10260    #[test]
10261    fn assert_populated_kind_count_matches_populated_kinds_accepts_coherent_local_impl() {
10262        fn make_local(k: LocalKind) -> LocalParent {
10263            match k {
10264                LocalKind::Alpha => LocalParent {
10265                    alpha: Some(11),
10266                    ..Default::default()
10267                },
10268                LocalKind::Beta => LocalParent {
10269                    beta: Some(22),
10270                    ..Default::default()
10271                },
10272                LocalKind::Gamma => LocalParent {
10273                    gamma: Some(33),
10274                    ..Default::default()
10275                },
10276            }
10277        }
10278        assert_populated_kind_count_matches_populated_kinds::<LocalParent, _>(make_local);
10279    }
10280
10281    /// A factory that yields an all-empty parent (so
10282    /// `populated_kind_count()` returns `0`) MUST fail-loudly at the
10283    /// caller's site through the primitive's single-slot diagonal arm
10284    /// — the `0` cardinality does not satisfy `count == 1` on the
10285    /// swept `populated` kind. Pin the diagonal-arm failure mode so a
10286    /// regression that silently succeeded on an all-empty factory
10287    /// (e.g. the primitive was refactored to skip the diagonal assert
10288    /// on `count == 0`) is caught here.
10289    #[test]
10290    #[should_panic(expected = "must equal 1 exactly (well-formed arm cardinality)")]
10291    fn assert_populated_kind_count_matches_populated_kinds_rejects_empty_factory() {
10292        fn empty_factory(_: LocalKind) -> LocalParent {
10293            LocalParent::default()
10294        }
10295        assert_populated_kind_count_matches_populated_kinds::<LocalParent, _>(empty_factory);
10296    }
10297
10298    /// A factory that yields a two-slot parent (so
10299    /// `populated_kind_count()` returns `2` on a supposedly single-slot
10300    /// factory) MUST fail-loudly at the caller's site through the
10301    /// primitive's single-slot diagonal arm — the `2` cardinality does
10302    /// not satisfy `count == 1`. Pin the diagonal-arm cardinality
10303    /// failure mode so a regression that silently succeeded on a
10304    /// broken factory (populating both the addressed slot AND an extra
10305    /// one) is caught here.
10306    #[test]
10307    #[should_panic(expected = "must equal 1 exactly (well-formed arm cardinality)")]
10308    fn assert_populated_kind_count_matches_populated_kinds_rejects_two_slot_factory() {
10309        fn always_pair(k: LocalKind) -> LocalParent {
10310            let mut p = LocalParent {
10311                gamma: Some(99),
10312                ..Default::default()
10313            };
10314            match k {
10315                LocalKind::Alpha => p.alpha = Some(11),
10316                LocalKind::Beta => p.beta = Some(22),
10317                LocalKind::Gamma => p.gamma = Some(33),
10318            }
10319            p
10320        }
10321        assert_populated_kind_count_matches_populated_kinds::<LocalParent, _>(always_pair);
10322    }
10323
10324    /// Every one of the four production `.variant()` sites on
10325    /// `ProcessSpec` binds through the scalar-cardinality primitive
10326    /// `assert_populated_kind_count_matches_populated_kinds` coherently
10327    /// — every per-site `single_slot_X(k)` factory produces a parent
10328    /// whose `populated_kind_count()` equals `1` AND whose composition
10329    /// law `count == populated_kinds().len()` holds. Sweep every
10330    /// production implementor at ONE substrate boundary so a regression
10331    /// that drifts a production site's `single_slot_X` factory OR the
10332    /// default `populated_kind_count` body (a specialization that
10333    /// short-circuited, drifted the walk order, or double-counted a
10334    /// slot) fails BOTH at any future per-crate test site AND at this
10335    /// substrate-wide sweep.
10336    #[test]
10337    fn every_production_tagged_union_binds_through_the_populated_kind_count_testkit_primitive() {
10338        assert_populated_kind_count_matches_populated_kinds::<crate::intent::Intent, _>(
10339            single_slot_intent_probe,
10340        );
10341        assert_populated_kind_count_matches_populated_kinds::<
10342            crate::encapsulates::EncapsulationKind,
10343            _,
10344        >(single_slot_encapsulation_kind_probe);
10345        assert_populated_kind_count_matches_populated_kinds::<crate::export::ArtifactSource, _>(
10346            single_slot_artifact_source_probe,
10347        );
10348        assert_populated_kind_count_matches_populated_kinds::<crate::export::VectorChannel, _>(
10349            single_slot_vector_channel_probe,
10350        );
10351    }
10352
10353    // -------------------------------------------------------------------
10354    // `TaggedUnion::missing_kinds` default method + the
10355    // closed-set-COMPLEMENT refinement's per-parent semantics — pin the
10356    // three arms (empty parent → full closed set, single-slot → ALL \
10357    // {k} in canonical order, saturated → empty vec) directly on the
10358    // sibling-shaped `LocalParent` scaffold. Peer of the boundary-side
10359    // `ConditionSliceExt::missing_kinds` primitive's three-arm pin on
10360    // the slice-level presence-probe axis; closed-set-COMPLEMENT peer
10361    // of the parent-level `populated_kinds` primitive above.
10362    // -------------------------------------------------------------------
10363
10364    /// EMPTY parent — the default body's `ALL.filter(!has).collect()`
10365    /// sweep yields the FULL `ClosedSet::ALL` vec when no slot is
10366    /// populated (every kind is missing). Pins the full-cardinality
10367    /// arm: a regression that mis-composed the `ALL.iter()` bridge
10368    /// (short-circuiting past the empty case), inverted the negation
10369    /// (returning `populated_kinds`), or dropped closed-set entries as
10370    /// false-negative absences fails HERE at the substrate boundary.
10371    #[test]
10372    fn tagged_union_default_missing_kinds_returns_full_closed_set_on_empty_parent() {
10373        let empty = LocalParent::default();
10374        assert_eq!(
10375            <LocalParent as TaggedUnion>::missing_kinds(&empty),
10376            <LocalKind as tatara_closed_set::ClosedSet>::ALL.to_vec(),
10377            "missing_kinds() must return ClosedSet::ALL when no slot is populated",
10378        );
10379    }
10380
10381    /// SINGLE-SLOT parent — the default body sweeps `ClosedSet::ALL`
10382    /// with `!has(k)` and collects `ALL \ {populated}` for each
10383    /// single-populated arrangement. Pins the length-(ALL.len()-1)
10384    /// arm's cardinality AND ordering (canonical `ClosedSet::ALL`
10385    /// order, `populated` absent) at ONE `assert_eq!` per kind — a
10386    /// regression that inverted the negation (returning `vec![populated]`
10387    /// instead of `ALL \ {populated}`) fails HERE per addressed kind.
10388    #[test]
10389    fn tagged_union_default_missing_kinds_returns_complement_per_variant() {
10390        for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
10391            .iter()
10392            .copied()
10393        {
10394            let parent = match populated {
10395                LocalKind::Alpha => LocalParent {
10396                    alpha: Some(11),
10397                    ..Default::default()
10398                },
10399                LocalKind::Beta => LocalParent {
10400                    beta: Some(22),
10401                    ..Default::default()
10402                },
10403                LocalKind::Gamma => LocalParent {
10404                    gamma: Some(33),
10405                    ..Default::default()
10406                },
10407            };
10408            let expected: Vec<LocalKind> = <LocalKind as tatara_closed_set::ClosedSet>::ALL
10409                .iter()
10410                .copied()
10411                .filter(|k| *k != populated)
10412                .collect();
10413            assert_eq!(
10414                <LocalParent as TaggedUnion>::missing_kinds(&parent),
10415                expected,
10416                "single-slot parent must return ClosedSet::ALL \\ {{{populated:?}}} on missing_kinds",
10417            );
10418        }
10419    }
10420
10421    /// SATURATED parent — every slot populated returns an empty vec on
10422    /// `missing_kinds`. Pins the zero-cardinality arm on the complement
10423    /// side (mirror of `populated_kinds` returning `ALL.to_vec()` on
10424    /// the saturated arm).
10425    #[test]
10426    fn tagged_union_default_missing_kinds_returns_empty_vec_on_saturated_parent() {
10427        let saturated = LocalParent {
10428            alpha: Some(1),
10429            beta: Some(2),
10430            gamma: Some(3),
10431        };
10432        assert!(
10433            <LocalParent as TaggedUnion>::missing_kinds(&saturated).is_empty(),
10434            "saturated parent must return empty Vec on missing_kinds",
10435        );
10436    }
10437
10438    /// Partition law binding `populated_kinds` and `missing_kinds` on
10439    /// every `LocalParent` arrangement: every `k ∈ ClosedSet::ALL`
10440    /// lives on EXACTLY ONE side of the partition (populated OR
10441    /// missing, never both, never neither). Pins the compound-lift's
10442    /// most-load-bearing invariant at ONE `assert!` per (arrangement,
10443    /// kind) pair — a regression that returned overlapping or
10444    /// disjoint-but-incomplete sets fails HERE at the XOR arm.
10445    #[test]
10446    fn tagged_union_default_populated_kinds_and_missing_kinds_partition_the_closed_set() {
10447        let arrangements: [LocalParent; 4] = [
10448            LocalParent::default(),
10449            LocalParent {
10450                alpha: Some(1),
10451                ..Default::default()
10452            },
10453            LocalParent {
10454                alpha: Some(1),
10455                beta: Some(2),
10456                gamma: None,
10457            },
10458            LocalParent {
10459                alpha: Some(1),
10460                beta: Some(2),
10461                gamma: Some(3),
10462            },
10463        ];
10464        for (idx, parent) in arrangements.iter().enumerate() {
10465            let populated = <LocalParent as TaggedUnion>::populated_kinds(parent);
10466            let missing = <LocalParent as TaggedUnion>::missing_kinds(parent);
10467            for &k in <LocalKind as tatara_closed_set::ClosedSet>::ALL.iter() {
10468                let in_populated = populated.contains(&k);
10469                let in_missing = missing.contains(&k);
10470                assert!(
10471                    in_populated ^ in_missing,
10472                    "arrangement idx {idx} — {k:?} must live on exactly one side of (populated, missing), got in_populated={in_populated} in_missing={in_missing}",
10473                );
10474            }
10475        }
10476    }
10477
10478    /// `assert_missing_kinds_matches_has` testkit accepts the coherent
10479    /// local scaffold — sweeping every populated slot through the
10480    /// per-kind negation + canonical `ALL`-filter + single-slot
10481    /// diagonal + XOR partition arms. A regression on any of the four
10482    /// composition laws fails at the substrate primitive's
10483    /// `#[track_caller]` boundary here rather than at four per-parent
10484    /// production sites downstream.
10485    #[test]
10486    fn assert_missing_kinds_matches_has_accepts_coherent_local_impl() {
10487        fn make_local(k: LocalKind) -> LocalParent {
10488            match k {
10489                LocalKind::Alpha => LocalParent {
10490                    alpha: Some(11),
10491                    ..Default::default()
10492                },
10493                LocalKind::Beta => LocalParent {
10494                    beta: Some(22),
10495                    ..Default::default()
10496                },
10497                LocalKind::Gamma => LocalParent {
10498                    gamma: Some(33),
10499                    ..Default::default()
10500                },
10501            }
10502        }
10503        assert_missing_kinds_matches_has::<LocalParent, _>(make_local);
10504    }
10505
10506    /// A factory that yields an all-empty parent MUST fail-loudly at
10507    /// the caller's site through the primitive's single-slot diagonal
10508    /// arm — the full `ALL` vec (every kind missing) does not equal
10509    /// `ALL \ {populated}` (which excludes `populated`). Pin the
10510    /// diagonal-arm failure mode so a regression that silently
10511    /// succeeded on an all-empty factory is caught here.
10512    #[test]
10513    #[should_panic(expected = "must return ClosedSet::ALL with Alpha removed")]
10514    fn assert_missing_kinds_matches_has_rejects_factory_that_populates_no_slots() {
10515        fn empty_factory(_: LocalKind) -> LocalParent {
10516            LocalParent::default()
10517        }
10518        assert_missing_kinds_matches_has::<LocalParent, _>(empty_factory);
10519    }
10520
10521    /// Every one of the four production `.variant()` sites on
10522    /// `ProcessSpec` binds through the single-slot closed-set-complement
10523    /// primitive `assert_missing_kinds_matches_has` coherently — every
10524    /// per-site `single_slot_X(k)` factory produces a parent whose
10525    /// `missing_kinds()` equals `ALL \ {k}` and whose per-kind
10526    /// negation composition law `missing_kinds().contains(&k) == !has(k)`
10527    /// holds for every `k ∈ ClosedSet::ALL`, AND the XOR partition law
10528    /// with `populated_kinds` binds byte-identically at every closed-
10529    /// set entry. Sweep every production implementor at ONE substrate
10530    /// boundary so a regression that drifts a production site's
10531    /// `single_slot_X` factory OR the default `missing_kinds` body (a
10532    /// specialization that inverted the negation, short-circuited, or
10533    /// drifted the walk order) fails BOTH at any future per-crate test
10534    /// site AND at this substrate-wide sweep.
10535    #[test]
10536    fn every_production_tagged_union_binds_through_the_missing_kinds_testkit_primitive() {
10537        assert_missing_kinds_matches_has::<crate::intent::Intent, _>(single_slot_intent_probe);
10538        assert_missing_kinds_matches_has::<crate::encapsulates::EncapsulationKind, _>(
10539            single_slot_encapsulation_kind_probe,
10540        );
10541        assert_missing_kinds_matches_has::<crate::export::ArtifactSource, _>(
10542            single_slot_artifact_source_probe,
10543        );
10544        assert_missing_kinds_matches_has::<crate::export::VectorChannel, _>(
10545            single_slot_vector_channel_probe,
10546        );
10547    }
10548
10549    // -------------------------------------------------------------------
10550    // `TaggedUnion::missing_kind_count` — scalar cardinality refinement
10551    // on the closed-set-COMPLEMENT axis. Pin the three arms (empty parent
10552    // → ALL.len(), single-slot → ALL.len() - 1, saturated → 0) directly
10553    // on the sibling-shaped `LocalParent` scaffold and the composition
10554    // law `missing_kind_count() == missing_kinds().len()` + the scalar
10555    // partition law `populated_kind_count + missing_kind_count ==
10556    // ALL.len()` at the substrate testkit
10557    // `assert_missing_kind_count_matches_missing_kinds`.
10558    // -------------------------------------------------------------------
10559
10560    /// EMPTY parent — the default body's `ALL.filter(!has).count()`
10561    /// sweep yields `ALL.len()` when no slot is populated. Pins the
10562    /// full-cardinality complement arm.
10563    #[test]
10564    fn tagged_union_default_missing_kind_count_returns_all_len_on_empty_parent() {
10565        let empty = LocalParent::default();
10566        assert_eq!(
10567            <LocalParent as TaggedUnion>::missing_kind_count(&empty),
10568            <LocalKind as tatara_closed_set::ClosedSet>::ALL.len(),
10569            "missing_kind_count() must return ALL.len() when no slot is populated",
10570        );
10571    }
10572
10573    /// SINGLE-SLOT parent — the default body sweeps `ClosedSet::ALL`
10574    /// with `!has(k)` and counts `ALL.len() - 1` for each single-
10575    /// populated arrangement. Pins the well-formed arm's complement
10576    /// cardinality per addressed kind.
10577    #[test]
10578    fn tagged_union_default_missing_kind_count_returns_all_len_minus_one_per_single_slot_variant() {
10579        let expected = <LocalKind as tatara_closed_set::ClosedSet>::ALL.len() - 1;
10580        for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
10581            .iter()
10582            .copied()
10583        {
10584            let parent = match populated {
10585                LocalKind::Alpha => LocalParent {
10586                    alpha: Some(11),
10587                    ..Default::default()
10588                },
10589                LocalKind::Beta => LocalParent {
10590                    beta: Some(22),
10591                    ..Default::default()
10592                },
10593                LocalKind::Gamma => LocalParent {
10594                    gamma: Some(33),
10595                    ..Default::default()
10596                },
10597            };
10598            assert_eq!(
10599                <LocalParent as TaggedUnion>::missing_kind_count(&parent),
10600                expected,
10601                "single-slot parent must return ALL.len() - 1 on missing_kind_count for {populated:?}",
10602            );
10603        }
10604    }
10605
10606    /// SATURATED parent — every slot populated returns `0` on
10607    /// `missing_kind_count`. Pins the zero-cardinality complement arm
10608    /// (mirror of `populated_kind_count` returning `ALL.len()` on the
10609    /// saturated arm).
10610    #[test]
10611    fn tagged_union_default_missing_kind_count_returns_zero_on_saturated_parent() {
10612        let saturated = LocalParent {
10613            alpha: Some(1),
10614            beta: Some(2),
10615            gamma: Some(3),
10616        };
10617        assert_eq!(
10618            <LocalParent as TaggedUnion>::missing_kind_count(&saturated),
10619            0,
10620            "saturated parent must return 0 on missing_kind_count",
10621        );
10622    }
10623
10624    /// Composition law `missing_kind_count() == missing_kinds().len()`
10625    /// binds the scalar cardinality projection to the widened primitive
10626    /// across every `ClosedSet::ALL × {empty, single_slot, two_slot,
10627    /// saturated}` combination. AND the scalar partition law
10628    /// `populated_kind_count() + missing_kind_count() == ALL.len()`
10629    /// binds the two axes byte-identically. Pins BOTH invariants at
10630    /// ONE test.
10631    #[test]
10632    fn tagged_union_default_missing_kind_count_matches_missing_kinds_len_and_partitions() {
10633        let all_len = <LocalKind as tatara_closed_set::ClosedSet>::ALL.len();
10634        let arrangements: [LocalParent; 4] = [
10635            LocalParent::default(),
10636            LocalParent {
10637                alpha: Some(1),
10638                ..Default::default()
10639            },
10640            LocalParent {
10641                alpha: Some(1),
10642                beta: Some(2),
10643                gamma: None,
10644            },
10645            LocalParent {
10646                alpha: Some(1),
10647                beta: Some(2),
10648                gamma: Some(3),
10649            },
10650        ];
10651        for (idx, parent) in arrangements.iter().enumerate() {
10652            let count = <LocalParent as TaggedUnion>::missing_kind_count(parent);
10653            let missing_len = <LocalParent as TaggedUnion>::missing_kinds(parent).len();
10654            assert_eq!(
10655                count, missing_len,
10656                "missing_kind_count() must equal missing_kinds().len() for arrangement idx {idx}",
10657            );
10658            let populated_count = <LocalParent as TaggedUnion>::populated_kind_count(parent);
10659            assert_eq!(
10660                populated_count + count,
10661                all_len,
10662                "scalar partition law violated at arrangement idx {idx} — populated_kind_count + missing_kind_count must equal ALL.len()",
10663            );
10664        }
10665    }
10666
10667    /// `assert_missing_kind_count_matches_missing_kinds` testkit
10668    /// accepts the coherent local scaffold — sweeping every populated
10669    /// kind through the three sub-assertions (composition law
10670    /// `count == missing_kinds.len()` + single-slot diagonal `count ==
10671    /// ALL.len() - 1` + scalar partition law
10672    /// `populated_kind_count + missing_kind_count == ALL.len()`). A
10673    /// regression on any of the three fails at the substrate
10674    /// primitive's `#[track_caller]` boundary.
10675    #[test]
10676    fn assert_missing_kind_count_matches_missing_kinds_accepts_coherent_local_impl() {
10677        fn make_local(k: LocalKind) -> LocalParent {
10678            match k {
10679                LocalKind::Alpha => LocalParent {
10680                    alpha: Some(11),
10681                    ..Default::default()
10682                },
10683                LocalKind::Beta => LocalParent {
10684                    beta: Some(22),
10685                    ..Default::default()
10686                },
10687                LocalKind::Gamma => LocalParent {
10688                    gamma: Some(33),
10689                    ..Default::default()
10690                },
10691            }
10692        }
10693        assert_missing_kind_count_matches_missing_kinds::<LocalParent, _>(make_local);
10694    }
10695
10696    /// A factory that yields an all-empty parent (so
10697    /// `missing_kind_count()` returns `ALL.len()`) MUST fail-loudly at
10698    /// the caller's site through the primitive's single-slot diagonal
10699    /// arm — the `ALL.len()` cardinality does not equal `ALL.len() - 1`.
10700    #[test]
10701    #[should_panic(expected = "must equal ALL.len() - 1 exactly")]
10702    fn assert_missing_kind_count_matches_missing_kinds_rejects_empty_factory() {
10703        fn empty_factory(_: LocalKind) -> LocalParent {
10704            LocalParent::default()
10705        }
10706        assert_missing_kind_count_matches_missing_kinds::<LocalParent, _>(empty_factory);
10707    }
10708
10709    /// Every one of the four production `.variant()` sites on
10710    /// `ProcessSpec` binds through the scalar-cardinality complement
10711    /// primitive `assert_missing_kind_count_matches_missing_kinds`
10712    /// coherently — every per-site `single_slot_X(k)` factory produces
10713    /// a parent whose `missing_kind_count()` equals `ALL.len() - 1`
10714    /// AND whose composition law `count == missing_kinds().len()` AND
10715    /// scalar partition law `populated_kind_count + missing_kind_count
10716    /// == ALL.len()` all hold. Sweep every production implementor at
10717    /// ONE substrate boundary.
10718    #[test]
10719    fn every_production_tagged_union_binds_through_the_missing_kind_count_testkit_primitive() {
10720        assert_missing_kind_count_matches_missing_kinds::<crate::intent::Intent, _>(
10721            single_slot_intent_probe,
10722        );
10723        assert_missing_kind_count_matches_missing_kinds::<crate::encapsulates::EncapsulationKind, _>(
10724            single_slot_encapsulation_kind_probe,
10725        );
10726        assert_missing_kind_count_matches_missing_kinds::<crate::export::ArtifactSource, _>(
10727            single_slot_artifact_source_probe,
10728        );
10729        assert_missing_kind_count_matches_missing_kinds::<crate::export::VectorChannel, _>(
10730            single_slot_vector_channel_probe,
10731        );
10732    }
10733
10734    // -------------------------------------------------------------------
10735    // `TaggedUnion::first_populated_kind` / `first_missing_kind` — the
10736    // short-circuiting `Option<Kind>` peers of `populated_kinds` /
10737    // `missing_kinds`. Pin the four-outcome truth table (empty parent
10738    // → `first_populated_kind` is `None`, `first_missing_kind` is
10739    // `Some(ALL[0])`; populated diagonal → `first_populated_kind` is
10740    // `Some(k)`, `first_missing_kind` is the earliest `ALL` entry
10741    // != `k`; multi-populated → `first_populated_kind` names the
10742    // EARLIEST populated slot in canonical `ALL` order) directly on
10743    // the `LocalParent` scaffold AND via the substrate testkit
10744    // primitives, so a regression on the default body's short-circuit
10745    // or negation composition fails here before any per-parent
10746    // inherent test surfaces the drift.
10747    // -------------------------------------------------------------------
10748
10749    /// EMPTY-PARENT pin — a default [`LocalParent`] returns `None` at
10750    /// `first_populated_kind` (no slot populated) and `Some(ALL[0])` at
10751    /// `first_missing_kind` (every slot missing, earliest hit is
10752    /// index 0 of the canonical closed-set walk). Composition-law pin:
10753    /// `first_populated_kind().is_none() == (populated_kind_count() ==
10754    /// 0)` and `first_missing_kind() == Some(ALL[0])` on the empty
10755    /// boundary.
10756    #[test]
10757    fn tagged_union_default_first_kinds_on_empty_parent() {
10758        let empty = LocalParent::default();
10759        assert_eq!(
10760            <LocalParent as TaggedUnion>::first_populated_kind(&empty),
10761            None,
10762        );
10763        assert_eq!(
10764            <LocalParent as TaggedUnion>::first_missing_kind(&empty),
10765            Some(<LocalKind as tatara_closed_set::ClosedSet>::ALL[0]),
10766        );
10767    }
10768
10769    /// SINGLE-SLOT DIAGONAL pin — every populated position across
10770    /// [`LocalKind::ALL`] returns `Some(k)` at `first_populated_kind`
10771    /// (the sole populated slot IS the earliest one) AND the earliest
10772    /// `ALL` entry != `k` at `first_missing_kind`. Both projections
10773    /// agree with the widened primitives via
10774    /// `first_populated_kind() == populated_kinds().first().copied()`
10775    /// and `first_missing_kind() == missing_kinds().first().copied()`.
10776    #[test]
10777    fn tagged_union_default_first_kinds_on_single_slot_diagonal() {
10778        for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
10779            .iter()
10780            .copied()
10781        {
10782            let parent = match populated {
10783                LocalKind::Alpha => LocalParent {
10784                    alpha: Some(11),
10785                    ..Default::default()
10786                },
10787                LocalKind::Beta => LocalParent {
10788                    beta: Some(22),
10789                    ..Default::default()
10790                },
10791                LocalKind::Gamma => LocalParent {
10792                    gamma: Some(33),
10793                    ..Default::default()
10794                },
10795            };
10796            assert_eq!(
10797                <LocalParent as TaggedUnion>::first_populated_kind(&parent),
10798                Some(populated),
10799            );
10800            let expected_first_missing = <LocalKind as tatara_closed_set::ClosedSet>::ALL
10801                .iter()
10802                .copied()
10803                .find(|k| *k != populated);
10804            assert_eq!(
10805                <LocalParent as TaggedUnion>::first_missing_kind(&parent),
10806                expected_first_missing,
10807            );
10808            // Composition laws vs. widened primitives.
10809            assert_eq!(
10810                parent.first_populated_kind(),
10811                parent.populated_kinds().first().copied(),
10812            );
10813            assert_eq!(
10814                parent.first_missing_kind(),
10815                parent.missing_kinds().first().copied(),
10816            );
10817        }
10818    }
10819
10820    /// TWO-POPULATED pin — a `LocalParent` with two populated slots
10821    /// returns `first_populated_kind() == Some(min_all(a, b))` (the
10822    /// EARLIEST populated slot in canonical `ClosedSet::ALL` order —
10823    /// strictly more informative than the payload-free
10824    /// [`LocalParentError::Ambiguous`] carrier `variant()` returns on
10825    /// the same input). Pins the walk order on the Ambiguous arm at
10826    /// ONE substrate boundary — a regression that iterates `ALL` in
10827    /// reverse or in construction order fails here.
10828    #[test]
10829    fn tagged_union_default_first_populated_kind_names_earliest_of_two_populated_slots() {
10830        // Alpha + Beta populated → earliest is Alpha (ALL[0]).
10831        let p = LocalParent {
10832            alpha: Some(1),
10833            beta: Some(2),
10834            gamma: None,
10835        };
10836        assert_eq!(p.first_populated_kind(), Some(LocalKind::Alpha));
10837        // Missing set is [Gamma]; earliest missing is Gamma.
10838        assert_eq!(p.first_missing_kind(), Some(LocalKind::Gamma));
10839
10840        // Beta + Gamma populated → earliest is Beta.
10841        let p = LocalParent {
10842            alpha: None,
10843            beta: Some(1),
10844            gamma: Some(2),
10845        };
10846        assert_eq!(p.first_populated_kind(), Some(LocalKind::Beta));
10847        assert_eq!(p.first_missing_kind(), Some(LocalKind::Alpha));
10848
10849        // Alpha + Gamma populated → earliest is Alpha.
10850        let p = LocalParent {
10851            alpha: Some(1),
10852            beta: None,
10853            gamma: Some(2),
10854        };
10855        assert_eq!(p.first_populated_kind(), Some(LocalKind::Alpha));
10856        assert_eq!(p.first_missing_kind(), Some(LocalKind::Beta));
10857    }
10858
10859    /// SATURATED-PARENT pin — a `LocalParent` with EVERY slot
10860    /// populated returns `Some(ALL[0])` at `first_populated_kind`
10861    /// (earliest hit on the all-`true` predicate is index 0) and
10862    /// `None` at `first_missing_kind` (no missing slot exists). Pins
10863    /// the earliest-missing projection's `None` arm at ONE substrate
10864    /// boundary — a regression that returned `Some(ALL[0])` (dropping
10865    /// the negation) or `Some(ALL[ALL.len()-1])` (walking in reverse)
10866    /// fails here.
10867    #[test]
10868    fn tagged_union_default_first_missing_kind_returns_none_on_saturated_parent() {
10869        let p = LocalParent {
10870            alpha: Some(1),
10871            beta: Some(2),
10872            gamma: Some(3),
10873        };
10874        assert_eq!(p.first_populated_kind(), Some(LocalKind::Alpha));
10875        assert_eq!(p.first_missing_kind(), None);
10876    }
10877
10878    /// The `assert_first_populated_kind_matches_populated_kinds`
10879    /// primitive accepts the [`LocalParent`] scaffold coherently — the
10880    /// Ok arm is the "no drift" outcome.
10881    #[test]
10882    fn assert_first_populated_kind_matches_populated_kinds_accepts_coherent_local_impl() {
10883        fn make_local(k: LocalKind) -> LocalParent {
10884            match k {
10885                LocalKind::Alpha => LocalParent {
10886                    alpha: Some(11),
10887                    ..Default::default()
10888                },
10889                LocalKind::Beta => LocalParent {
10890                    beta: Some(22),
10891                    ..Default::default()
10892                },
10893                LocalKind::Gamma => LocalParent {
10894                    gamma: Some(33),
10895                    ..Default::default()
10896                },
10897            }
10898        }
10899        assert_first_populated_kind_matches_populated_kinds::<LocalParent, _>(make_local);
10900    }
10901
10902    /// A factory that yields an all-empty parent (so
10903    /// `first_populated_kind()` returns `None`) MUST fail-loudly at
10904    /// the caller's site through the primitive's single-slot diagonal
10905    /// arm — `None` does not equal `Some(populated)`.
10906    #[test]
10907    #[should_panic(expected = "must equal Some(")]
10908    fn assert_first_populated_kind_matches_populated_kinds_rejects_empty_factory() {
10909        fn empty_factory(_: LocalKind) -> LocalParent {
10910            LocalParent::default()
10911        }
10912        assert_first_populated_kind_matches_populated_kinds::<LocalParent, _>(empty_factory);
10913    }
10914
10915    /// The `assert_first_missing_kind_matches_missing_kinds` primitive
10916    /// accepts the [`LocalParent`] scaffold coherently.
10917    #[test]
10918    fn assert_first_missing_kind_matches_missing_kinds_accepts_coherent_local_impl() {
10919        fn make_local(k: LocalKind) -> LocalParent {
10920            match k {
10921                LocalKind::Alpha => LocalParent {
10922                    alpha: Some(11),
10923                    ..Default::default()
10924                },
10925                LocalKind::Beta => LocalParent {
10926                    beta: Some(22),
10927                    ..Default::default()
10928                },
10929                LocalKind::Gamma => LocalParent {
10930                    gamma: Some(33),
10931                    ..Default::default()
10932                },
10933            }
10934        }
10935        assert_first_missing_kind_matches_missing_kinds::<LocalParent, _>(make_local);
10936    }
10937
10938    /// Every one of the four production `.variant()` sites on
10939    /// `ProcessSpec` binds through the earliest-populated primitive
10940    /// coherently — every per-site `single_slot_X(k)` factory produces
10941    /// a parent whose `first_populated_kind()` equals `Some(k)`.
10942    #[test]
10943    fn every_production_tagged_union_binds_through_the_first_populated_kind_testkit_primitive() {
10944        assert_first_populated_kind_matches_populated_kinds::<crate::intent::Intent, _>(
10945            single_slot_intent_probe,
10946        );
10947        assert_first_populated_kind_matches_populated_kinds::<
10948            crate::encapsulates::EncapsulationKind,
10949            _,
10950        >(single_slot_encapsulation_kind_probe);
10951        assert_first_populated_kind_matches_populated_kinds::<crate::export::ArtifactSource, _>(
10952            single_slot_artifact_source_probe,
10953        );
10954        assert_first_populated_kind_matches_populated_kinds::<crate::export::VectorChannel, _>(
10955            single_slot_vector_channel_probe,
10956        );
10957    }
10958
10959    /// Every one of the four production `.variant()` sites on
10960    /// `ProcessSpec` binds through the earliest-missing primitive
10961    /// coherently.
10962    #[test]
10963    fn every_production_tagged_union_binds_through_the_first_missing_kind_testkit_primitive() {
10964        assert_first_missing_kind_matches_missing_kinds::<crate::intent::Intent, _>(
10965            single_slot_intent_probe,
10966        );
10967        assert_first_missing_kind_matches_missing_kinds::<crate::encapsulates::EncapsulationKind, _>(
10968            single_slot_encapsulation_kind_probe,
10969        );
10970        assert_first_missing_kind_matches_missing_kinds::<crate::export::ArtifactSource, _>(
10971            single_slot_artifact_source_probe,
10972        );
10973        assert_first_missing_kind_matches_missing_kinds::<crate::export::VectorChannel, _>(
10974            single_slot_vector_channel_probe,
10975        );
10976    }
10977
10978    // -------------------------------------------------------------------
10979    // `TaggedUnion::last_populated_kind` / `last_missing_kind` — the
10980    // short-circuiting REVERSED-walk `Option<Kind>` peers of
10981    // `first_populated_kind` / `first_missing_kind`. Pin the four-outcome
10982    // truth table (empty parent → `last_populated_kind` is `None`,
10983    // `last_missing_kind` is `Some(ALL[ALL.len()-1])`; populated diagonal
10984    // → `last_populated_kind` is `Some(k)`, `last_missing_kind` is the
10985    // latest `ALL` entry != `k`; multi-populated → `last_populated_kind`
10986    // names the LATEST populated slot in canonical `ALL` order;
10987    // saturated → `last_missing_kind` is `None`) directly on the
10988    // `LocalParent` scaffold AND via the substrate testkit primitives,
10989    // so a regression on the reversed default body's short-circuit or
10990    // negation composition fails here before any per-parent inherent
10991    // test surfaces the drift.
10992    // -------------------------------------------------------------------
10993
10994    /// EMPTY-PARENT pin — a default [`LocalParent`] returns `None` at
10995    /// `last_populated_kind` (no slot populated) and
10996    /// `Some(ALL[ALL.len()-1])` at `last_missing_kind` (every slot
10997    /// missing, latest hit is the last index of the canonical closed-
10998    /// set walk under REVERSED iteration). Composition-law pin:
10999    /// `last_populated_kind().is_none() == (populated_kind_count() ==
11000    /// 0)` and `last_missing_kind() == Some(ALL[ALL.len()-1])` on the
11001    /// empty boundary.
11002    #[test]
11003    fn tagged_union_default_last_kinds_on_empty_parent() {
11004        let empty = LocalParent::default();
11005        assert_eq!(
11006            <LocalParent as TaggedUnion>::last_populated_kind(&empty),
11007            None,
11008        );
11009        let all_len = <LocalKind as tatara_closed_set::ClosedSet>::ALL.len();
11010        assert_eq!(
11011            <LocalParent as TaggedUnion>::last_missing_kind(&empty),
11012            Some(<LocalKind as tatara_closed_set::ClosedSet>::ALL[all_len - 1]),
11013        );
11014    }
11015
11016    /// SINGLE-SLOT DIAGONAL pin — every populated position across
11017    /// [`LocalKind::ALL`] returns `Some(k)` at `last_populated_kind`
11018    /// (the sole populated slot IS both the earliest AND the latest)
11019    /// AND the LATEST `ALL` entry != `k` at `last_missing_kind`. Both
11020    /// projections agree with the widened primitives via
11021    /// `last_populated_kind() == populated_kinds().last().copied()`
11022    /// and `last_missing_kind() == missing_kinds().last().copied()`.
11023    #[test]
11024    fn tagged_union_default_last_kinds_on_single_slot_diagonal() {
11025        for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
11026            .iter()
11027            .copied()
11028        {
11029            let parent = match populated {
11030                LocalKind::Alpha => LocalParent {
11031                    alpha: Some(11),
11032                    ..Default::default()
11033                },
11034                LocalKind::Beta => LocalParent {
11035                    beta: Some(22),
11036                    ..Default::default()
11037                },
11038                LocalKind::Gamma => LocalParent {
11039                    gamma: Some(33),
11040                    ..Default::default()
11041                },
11042            };
11043            assert_eq!(
11044                <LocalParent as TaggedUnion>::last_populated_kind(&parent),
11045                Some(populated),
11046            );
11047            let expected_last_missing = <LocalKind as tatara_closed_set::ClosedSet>::ALL
11048                .iter()
11049                .rev()
11050                .copied()
11051                .find(|k| *k != populated);
11052            assert_eq!(
11053                <LocalParent as TaggedUnion>::last_missing_kind(&parent),
11054                expected_last_missing,
11055            );
11056            // Composition laws vs. widened primitives.
11057            assert_eq!(
11058                parent.last_populated_kind(),
11059                parent.populated_kinds().last().copied(),
11060            );
11061            assert_eq!(
11062                parent.last_missing_kind(),
11063                parent.missing_kinds().last().copied(),
11064            );
11065        }
11066    }
11067
11068    /// TWO-POPULATED pin — a `LocalParent` with two populated slots
11069    /// returns `last_populated_kind() == Some(max_all(a, b))` (the
11070    /// LATEST populated slot in canonical `ClosedSet::ALL` order —
11071    /// byte-for-byte time-reversed peer of the earliest-populated
11072    /// projection). Pins the walk order on the Ambiguous arm at ONE
11073    /// substrate boundary — a regression that iterates `ALL` forward
11074    /// (defeating the time-reversal) fails here.
11075    #[test]
11076    fn tagged_union_default_last_populated_kind_names_latest_of_two_populated_slots() {
11077        // Alpha + Beta populated → latest is Beta (ALL[1]).
11078        let p = LocalParent {
11079            alpha: Some(1),
11080            beta: Some(2),
11081            gamma: None,
11082        };
11083        assert_eq!(p.last_populated_kind(), Some(LocalKind::Beta));
11084        // Missing set is [Gamma]; latest missing is Gamma.
11085        assert_eq!(p.last_missing_kind(), Some(LocalKind::Gamma));
11086
11087        // Beta + Gamma populated → latest is Gamma.
11088        let p = LocalParent {
11089            alpha: None,
11090            beta: Some(1),
11091            gamma: Some(2),
11092        };
11093        assert_eq!(p.last_populated_kind(), Some(LocalKind::Gamma));
11094        assert_eq!(p.last_missing_kind(), Some(LocalKind::Alpha));
11095
11096        // Alpha + Gamma populated → latest is Gamma.
11097        let p = LocalParent {
11098            alpha: Some(1),
11099            beta: None,
11100            gamma: Some(2),
11101        };
11102        assert_eq!(p.last_populated_kind(), Some(LocalKind::Gamma));
11103        assert_eq!(p.last_missing_kind(), Some(LocalKind::Beta));
11104    }
11105
11106    /// SATURATED-PARENT pin — a `LocalParent` with EVERY slot
11107    /// populated returns `Some(ALL[ALL.len()-1])` at
11108    /// `last_populated_kind` (latest hit on the all-`true` predicate
11109    /// under REVERSED iteration is the last index) and `None` at
11110    /// `last_missing_kind` (no missing slot exists). Pins the latest-
11111    /// missing projection's `None` arm at ONE substrate boundary — a
11112    /// regression that returned `Some(ALL[ALL.len()-1])` (dropping the
11113    /// negation) or `Some(ALL[0])` (defeating the time-reversal)
11114    /// fails here.
11115    #[test]
11116    fn tagged_union_default_last_missing_kind_returns_none_on_saturated_parent() {
11117        let p = LocalParent {
11118            alpha: Some(1),
11119            beta: Some(2),
11120            gamma: Some(3),
11121        };
11122        let all_len = <LocalKind as tatara_closed_set::ClosedSet>::ALL.len();
11123        assert_eq!(
11124            p.last_populated_kind(),
11125            Some(<LocalKind as tatara_closed_set::ClosedSet>::ALL[all_len - 1]),
11126        );
11127        assert_eq!(p.last_missing_kind(), None);
11128    }
11129
11130    /// The `assert_last_populated_kind_matches_populated_kinds`
11131    /// primitive accepts the [`LocalParent`] scaffold coherently — the
11132    /// Ok arm is the "no drift" outcome.
11133    #[test]
11134    fn assert_last_populated_kind_matches_populated_kinds_accepts_coherent_local_impl() {
11135        fn make_local(k: LocalKind) -> LocalParent {
11136            match k {
11137                LocalKind::Alpha => LocalParent {
11138                    alpha: Some(11),
11139                    ..Default::default()
11140                },
11141                LocalKind::Beta => LocalParent {
11142                    beta: Some(22),
11143                    ..Default::default()
11144                },
11145                LocalKind::Gamma => LocalParent {
11146                    gamma: Some(33),
11147                    ..Default::default()
11148                },
11149            }
11150        }
11151        assert_last_populated_kind_matches_populated_kinds::<LocalParent, _>(make_local);
11152    }
11153
11154    /// A factory that yields an all-empty parent (so
11155    /// `last_populated_kind()` returns `None`) MUST fail-loudly at the
11156    /// caller's site through the primitive's single-slot diagonal arm
11157    /// — `None` does not equal `Some(populated)`.
11158    #[test]
11159    #[should_panic(expected = "must equal Some(")]
11160    fn assert_last_populated_kind_matches_populated_kinds_rejects_empty_factory() {
11161        fn empty_factory(_: LocalKind) -> LocalParent {
11162            LocalParent::default()
11163        }
11164        assert_last_populated_kind_matches_populated_kinds::<LocalParent, _>(empty_factory);
11165    }
11166
11167    /// The `assert_last_missing_kind_matches_missing_kinds` primitive
11168    /// accepts the [`LocalParent`] scaffold coherently.
11169    #[test]
11170    fn assert_last_missing_kind_matches_missing_kinds_accepts_coherent_local_impl() {
11171        fn make_local(k: LocalKind) -> LocalParent {
11172            match k {
11173                LocalKind::Alpha => LocalParent {
11174                    alpha: Some(11),
11175                    ..Default::default()
11176                },
11177                LocalKind::Beta => LocalParent {
11178                    beta: Some(22),
11179                    ..Default::default()
11180                },
11181                LocalKind::Gamma => LocalParent {
11182                    gamma: Some(33),
11183                    ..Default::default()
11184                },
11185            }
11186        }
11187        assert_last_missing_kind_matches_missing_kinds::<LocalParent, _>(make_local);
11188    }
11189
11190    /// Every one of the four production `.variant()` sites on
11191    /// `ProcessSpec` binds through the latest-populated primitive
11192    /// coherently — every per-site `single_slot_X(k)` factory produces
11193    /// a parent whose `last_populated_kind()` equals `Some(k)`.
11194    #[test]
11195    fn every_production_tagged_union_binds_through_the_last_populated_kind_testkit_primitive() {
11196        assert_last_populated_kind_matches_populated_kinds::<crate::intent::Intent, _>(
11197            single_slot_intent_probe,
11198        );
11199        assert_last_populated_kind_matches_populated_kinds::<
11200            crate::encapsulates::EncapsulationKind,
11201            _,
11202        >(single_slot_encapsulation_kind_probe);
11203        assert_last_populated_kind_matches_populated_kinds::<crate::export::ArtifactSource, _>(
11204            single_slot_artifact_source_probe,
11205        );
11206        assert_last_populated_kind_matches_populated_kinds::<crate::export::VectorChannel, _>(
11207            single_slot_vector_channel_probe,
11208        );
11209    }
11210
11211    /// Every one of the four production `.variant()` sites on
11212    /// `ProcessSpec` binds through the latest-missing primitive
11213    /// coherently.
11214    #[test]
11215    fn every_production_tagged_union_binds_through_the_last_missing_kind_testkit_primitive() {
11216        assert_last_missing_kind_matches_missing_kinds::<crate::intent::Intent, _>(
11217            single_slot_intent_probe,
11218        );
11219        assert_last_missing_kind_matches_missing_kinds::<crate::encapsulates::EncapsulationKind, _>(
11220            single_slot_encapsulation_kind_probe,
11221        );
11222        assert_last_missing_kind_matches_missing_kinds::<crate::export::ArtifactSource, _>(
11223            single_slot_artifact_source_probe,
11224        );
11225        assert_last_missing_kind_matches_missing_kinds::<crate::export::VectorChannel, _>(
11226            single_slot_vector_channel_probe,
11227        );
11228    }
11229
11230    // -------------------------------------------------------------------
11231    // `TaggedUnion::unique_populated_kind` / `unique_missing_kind` — the
11232    // short-circuiting `Option<Kind>` peers on the exactly-one-hit axis.
11233    // Pin the four-outcome truth table (empty parent → both `None`;
11234    // single-slot diagonal → `unique_populated_kind` is `Some(k)`,
11235    // `unique_missing_kind` is `None` on `ALL.len() > 2`; two-populated
11236    // parent → `unique_populated_kind` is `None`, `unique_missing_kind`
11237    // is `Some(the-one-missing)`; saturated → both `None`) directly on
11238    // the `LocalParent` scaffold AND via the substrate testkit
11239    // primitives, so a regression on the two-step short-circuit's
11240    // second-hit truncation or the negation composition fails here
11241    // before any per-parent inherent test surfaces the drift.
11242    // -------------------------------------------------------------------
11243
11244    /// EMPTY-PARENT pin — a default [`LocalParent`] returns `None` at
11245    /// BOTH `unique_populated_kind` (zero populated, not exactly-one)
11246    /// and `unique_missing_kind` (three missing on a `ALL.len() == 3`
11247    /// closed set, not exactly-one). Pins the empty-arm collapse — the
11248    /// two primitives agree on `None` when the closed-set cardinality
11249    /// is ≥ 3, distinguishing the exactly-one primitive from the
11250    /// endpoint primitives (`first_missing_kind` on an empty parent
11251    /// returns `Some(ALL[0])`, not `None`).
11252    #[test]
11253    fn tagged_union_default_unique_kinds_on_empty_parent() {
11254        let empty = LocalParent::default();
11255        assert_eq!(
11256            <LocalParent as TaggedUnion>::unique_populated_kind(&empty),
11257            None,
11258        );
11259        assert_eq!(
11260            <LocalParent as TaggedUnion>::unique_missing_kind(&empty),
11261            None,
11262        );
11263    }
11264
11265    /// SINGLE-SLOT DIAGONAL pin — every populated position across
11266    /// [`LocalKind::ALL`] returns `Some(k)` at `unique_populated_kind`
11267    /// (the sole populated slot IS the exactly-one hit) AND `None` at
11268    /// `unique_missing_kind` (two missing slots on the `ALL.len() == 3`
11269    /// closed set, not exactly-one). The `Some` arm's endpoint
11270    /// agreement composes with `first_populated_kind` /
11271    /// `last_populated_kind` at the trait defaults (`unique == first
11272    /// == last` on exactly-one).
11273    #[test]
11274    fn tagged_union_default_unique_kinds_on_single_slot_diagonal() {
11275        for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
11276            .iter()
11277            .copied()
11278        {
11279            let parent = match populated {
11280                LocalKind::Alpha => LocalParent {
11281                    alpha: Some(11),
11282                    ..Default::default()
11283                },
11284                LocalKind::Beta => LocalParent {
11285                    beta: Some(22),
11286                    ..Default::default()
11287                },
11288                LocalKind::Gamma => LocalParent {
11289                    gamma: Some(33),
11290                    ..Default::default()
11291                },
11292            };
11293            assert_eq!(
11294                <LocalParent as TaggedUnion>::unique_populated_kind(&parent),
11295                Some(populated),
11296            );
11297            assert_eq!(
11298                <LocalParent as TaggedUnion>::unique_missing_kind(&parent),
11299                None,
11300            );
11301            // Endpoint-agreement composition — on Some, the three
11302            // endpoint-projection primitives agree.
11303            assert_eq!(
11304                parent.unique_populated_kind(),
11305                parent.first_populated_kind()
11306            );
11307            assert_eq!(parent.unique_populated_kind(), parent.last_populated_kind());
11308        }
11309    }
11310
11311    /// TWO-POPULATED pin — a `LocalParent` with two populated slots
11312    /// returns `unique_populated_kind() == None` (two populated, not
11313    /// exactly-one) and `unique_missing_kind() == Some(the-one-missing)`
11314    /// (one missing, exactly-one — the ONLY arm where the missing-side
11315    /// primitive returns `Some` on a `ALL.len() == 3` closed set). Pins
11316    /// the two-step short-circuit's second-hit collapse at ONE
11317    /// substrate boundary — a regression that returned `Some(first)`
11318    /// after seeing two populated slots (defeating the exactly-one
11319    /// contract) fails here.
11320    #[test]
11321    fn tagged_union_default_unique_kinds_on_two_populated_parent() {
11322        // Alpha + Beta populated → 2 populated (unique_populated=None),
11323        // 1 missing = Gamma (unique_missing=Some(Gamma)).
11324        let p = LocalParent {
11325            alpha: Some(1),
11326            beta: Some(2),
11327            gamma: None,
11328        };
11329        assert_eq!(p.unique_populated_kind(), None);
11330        assert_eq!(p.unique_missing_kind(), Some(LocalKind::Gamma));
11331        // Endpoint-agreement composition on the missing-side Some arm.
11332        assert_eq!(p.unique_missing_kind(), p.first_missing_kind());
11333        assert_eq!(p.unique_missing_kind(), p.last_missing_kind());
11334
11335        // Beta + Gamma populated → unique_missing=Some(Alpha).
11336        let p = LocalParent {
11337            alpha: None,
11338            beta: Some(1),
11339            gamma: Some(2),
11340        };
11341        assert_eq!(p.unique_populated_kind(), None);
11342        assert_eq!(p.unique_missing_kind(), Some(LocalKind::Alpha));
11343
11344        // Alpha + Gamma populated → unique_missing=Some(Beta).
11345        let p = LocalParent {
11346            alpha: Some(1),
11347            beta: None,
11348            gamma: Some(2),
11349        };
11350        assert_eq!(p.unique_populated_kind(), None);
11351        assert_eq!(p.unique_missing_kind(), Some(LocalKind::Beta));
11352    }
11353
11354    /// SATURATED-PARENT pin — a `LocalParent` with EVERY slot
11355    /// populated returns `None` at BOTH `unique_populated_kind` (three
11356    /// populated, not exactly-one) AND `unique_missing_kind` (zero
11357    /// missing, not exactly-one). Pins the saturated-arm collapse — the
11358    /// two primitives agree on `None` when the closed-set cardinality
11359    /// is ≥ 3, distinguishing the exactly-one primitive from the
11360    /// endpoint primitives (`last_populated_kind` on a saturated
11361    /// parent returns `Some(ALL[ALL.len()-1])`, not `None`).
11362    #[test]
11363    fn tagged_union_default_unique_kinds_on_saturated_parent() {
11364        let p = LocalParent {
11365            alpha: Some(1),
11366            beta: Some(2),
11367            gamma: Some(3),
11368        };
11369        assert_eq!(p.unique_populated_kind(), None);
11370        assert_eq!(p.unique_missing_kind(), None);
11371    }
11372
11373    /// The `assert_unique_populated_kind_matches_populated_kinds`
11374    /// primitive accepts the [`LocalParent`] scaffold coherently — the
11375    /// Ok arm is the "no drift" outcome.
11376    #[test]
11377    fn assert_unique_populated_kind_matches_populated_kinds_accepts_coherent_local_impl() {
11378        fn make_local(k: LocalKind) -> LocalParent {
11379            match k {
11380                LocalKind::Alpha => LocalParent {
11381                    alpha: Some(11),
11382                    ..Default::default()
11383                },
11384                LocalKind::Beta => LocalParent {
11385                    beta: Some(22),
11386                    ..Default::default()
11387                },
11388                LocalKind::Gamma => LocalParent {
11389                    gamma: Some(33),
11390                    ..Default::default()
11391                },
11392            }
11393        }
11394        assert_unique_populated_kind_matches_populated_kinds::<LocalParent, _>(make_local);
11395    }
11396
11397    /// A factory that yields an all-empty parent (so
11398    /// `unique_populated_kind()` returns `None`) MUST fail-loudly at
11399    /// the caller's site through the primitive's single-slot diagonal
11400    /// arm — `None` does not equal `Some(populated)`.
11401    #[test]
11402    #[should_panic(expected = "must equal Some(")]
11403    fn assert_unique_populated_kind_matches_populated_kinds_rejects_empty_factory() {
11404        fn empty_factory(_: LocalKind) -> LocalParent {
11405            LocalParent::default()
11406        }
11407        assert_unique_populated_kind_matches_populated_kinds::<LocalParent, _>(empty_factory);
11408    }
11409
11410    /// The `assert_unique_missing_kind_matches_missing_kinds` primitive
11411    /// accepts the [`LocalParent`] scaffold coherently.
11412    #[test]
11413    fn assert_unique_missing_kind_matches_missing_kinds_accepts_coherent_local_impl() {
11414        fn make_local(k: LocalKind) -> LocalParent {
11415            match k {
11416                LocalKind::Alpha => LocalParent {
11417                    alpha: Some(11),
11418                    ..Default::default()
11419                },
11420                LocalKind::Beta => LocalParent {
11421                    beta: Some(22),
11422                    ..Default::default()
11423                },
11424                LocalKind::Gamma => LocalParent {
11425                    gamma: Some(33),
11426                    ..Default::default()
11427                },
11428            }
11429        }
11430        assert_unique_missing_kind_matches_missing_kinds::<LocalParent, _>(make_local);
11431    }
11432
11433    /// Every one of the four production `.variant()` sites on
11434    /// `ProcessSpec` binds through the exactly-one-populated primitive
11435    /// coherently — every per-site `single_slot_X(k)` factory produces
11436    /// a parent whose `unique_populated_kind()` equals `Some(k)`.
11437    #[test]
11438    fn every_production_tagged_union_binds_through_the_unique_populated_kind_testkit_primitive() {
11439        assert_unique_populated_kind_matches_populated_kinds::<crate::intent::Intent, _>(
11440            single_slot_intent_probe,
11441        );
11442        assert_unique_populated_kind_matches_populated_kinds::<
11443            crate::encapsulates::EncapsulationKind,
11444            _,
11445        >(single_slot_encapsulation_kind_probe);
11446        assert_unique_populated_kind_matches_populated_kinds::<crate::export::ArtifactSource, _>(
11447            single_slot_artifact_source_probe,
11448        );
11449        assert_unique_populated_kind_matches_populated_kinds::<crate::export::VectorChannel, _>(
11450            single_slot_vector_channel_probe,
11451        );
11452    }
11453
11454    /// Every one of the four production `.variant()` sites on
11455    /// `ProcessSpec` binds through the exactly-one-missing primitive
11456    /// coherently.
11457    #[test]
11458    fn every_production_tagged_union_binds_through_the_unique_missing_kind_testkit_primitive() {
11459        assert_unique_missing_kind_matches_missing_kinds::<crate::intent::Intent, _>(
11460            single_slot_intent_probe,
11461        );
11462        assert_unique_missing_kind_matches_missing_kinds::<crate::encapsulates::EncapsulationKind, _>(
11463            single_slot_encapsulation_kind_probe,
11464        );
11465        assert_unique_missing_kind_matches_missing_kinds::<crate::export::ArtifactSource, _>(
11466            single_slot_artifact_source_probe,
11467        );
11468        assert_unique_missing_kind_matches_missing_kinds::<crate::export::VectorChannel, _>(
11469            single_slot_vector_channel_probe,
11470        );
11471    }
11472
11473    // -------------------------------------------------------------------
11474    // `TaggedUnion::is_empty` / `TaggedUnion::is_saturated` trait-level
11475    // truth-table pins on the sibling-shaped `LocalParent` scaffold.
11476    // The two primitives are the Boolean cardinality-endpoint peers of
11477    // `populated_kind_count() == 0` and `missing_kind_count() == 0`
11478    // respectively — every arm below pins one truth-table entry directly
11479    // on the trait's default body without reaching for either scalar
11480    // primitive.
11481    // -------------------------------------------------------------------
11482
11483    /// EMPTY-PARENT pin — a default-constructed `LocalParent` (every
11484    /// slot None) returns `true` at `is_empty` (zero populated slots)
11485    /// AND `false` at `is_saturated` (three missing slots, not zero).
11486    /// Pins the zero-arm of the `is_empty` primitive and the negation
11487    /// of the `is_saturated` primitive on the same fixture — a
11488    /// regression that inverted either default body's composition
11489    /// direction fails here.
11490    #[test]
11491    fn tagged_union_default_is_empty_and_is_saturated_on_empty_parent() {
11492        let p = LocalParent::default();
11493        assert!(p.is_empty(), "empty parent must be is_empty");
11494        assert!(!p.is_saturated(), "empty parent must NOT be is_saturated");
11495        // Composition law with the scalar cardinality primitives.
11496        assert_eq!(p.is_empty(), p.populated_kind_count() == 0);
11497        assert_eq!(p.is_saturated(), p.missing_kind_count() == 0);
11498        // Widened-primitive agreement.
11499        assert_eq!(p.is_empty(), p.populated_kinds().is_empty());
11500        assert_eq!(p.is_saturated(), p.missing_kinds().is_empty());
11501    }
11502
11503    /// SINGLE-SLOT-DIAGONAL pin — a `LocalParent` populating exactly
11504    /// one slot returns `false` at BOTH `is_empty` (one populated, not
11505    /// zero) AND `is_saturated` (two missing, not zero). Pins that a
11506    /// well-formed parent lands OUTSIDE both cardinality endpoints —
11507    /// the Boolean primitives coincide on `false` on this arm, and
11508    /// only on the empty parent (`is_empty` true) or a saturated
11509    /// parent (`is_saturated` true) do they diverge.
11510    #[test]
11511    fn tagged_union_default_is_empty_and_is_saturated_on_single_slot_diagonal() {
11512        for (populated, parent) in [
11513            (
11514                LocalKind::Alpha,
11515                LocalParent {
11516                    alpha: Some(1),
11517                    ..Default::default()
11518                },
11519            ),
11520            (
11521                LocalKind::Beta,
11522                LocalParent {
11523                    beta: Some(2),
11524                    ..Default::default()
11525                },
11526            ),
11527            (
11528                LocalKind::Gamma,
11529                LocalParent {
11530                    gamma: Some(3),
11531                    ..Default::default()
11532                },
11533            ),
11534        ] {
11535            assert!(
11536                !parent.is_empty(),
11537                "single_slot({populated:?}) must NOT be is_empty",
11538            );
11539            assert!(
11540                !parent.is_saturated(),
11541                "single_slot({populated:?}) must NOT be is_saturated",
11542            );
11543            assert_eq!(parent.is_empty(), parent.populated_kind_count() == 0);
11544            assert_eq!(parent.is_saturated(), parent.missing_kind_count() == 0);
11545        }
11546    }
11547
11548    /// SATURATED-PARENT pin — a `LocalParent` with EVERY slot populated
11549    /// returns `false` at `is_empty` (three populated, not zero) AND
11550    /// `true` at `is_saturated` (zero missing). Pins the top-arm of
11551    /// the `is_saturated` primitive and the negation of the `is_empty`
11552    /// primitive on the same fixture — the mirror of the empty-parent
11553    /// pin above, distinguishing the two cardinality endpoints on
11554    /// opposite arms of the same closed-set walk.
11555    #[test]
11556    fn tagged_union_default_is_empty_and_is_saturated_on_saturated_parent() {
11557        let p = LocalParent {
11558            alpha: Some(1),
11559            beta: Some(2),
11560            gamma: Some(3),
11561        };
11562        assert!(!p.is_empty(), "saturated parent must NOT be is_empty");
11563        assert!(p.is_saturated(), "saturated parent must be is_saturated");
11564        assert_eq!(p.is_empty(), p.populated_kind_count() == 0);
11565        assert_eq!(p.is_saturated(), p.missing_kind_count() == 0);
11566        assert_eq!(p.is_empty(), p.populated_kinds().is_empty());
11567        assert_eq!(p.is_saturated(), p.missing_kinds().is_empty());
11568    }
11569
11570    // -------------------------------------------------------------------
11571    // Truth-table pins for `TaggedUnion::has_unique_populated_kind` and
11572    // `TaggedUnion::has_unique_missing_kind` — three arms (empty,
11573    // single-slot diagonal, saturated) on the sibling-shaped
11574    // `LocalParent` scaffold. The two primitives are the Boolean
11575    // cardinality-mid-endpoint peers of `populated_kind_count() == 1`
11576    // and `missing_kind_count() == 1` respectively — every arm below
11577    // pins one truth-table entry directly on the trait's default body
11578    // without reaching for either scalar primitive.
11579    // -------------------------------------------------------------------
11580
11581    /// EMPTY-PARENT pin — a default-constructed `LocalParent` (every
11582    /// slot None) returns `false` at BOTH `has_unique_populated_kind`
11583    /// (zero populated, not one) AND `has_unique_missing_kind` (three
11584    /// missing on `ALL.len() == 3`, not one). Pins the zero-populated
11585    /// arm of the first primitive and the ALL.len()-missing arm of the
11586    /// second on the same fixture.
11587    #[test]
11588    fn tagged_union_default_has_unique_kinds_on_empty_parent() {
11589        let p = LocalParent::default();
11590        assert!(
11591            !p.has_unique_populated_kind(),
11592            "empty parent must NOT be has_unique_populated_kind (zero populated)",
11593        );
11594        assert!(
11595            !p.has_unique_missing_kind(),
11596            "empty parent must NOT be has_unique_missing_kind (three missing)",
11597        );
11598        // Composition law with the scalar cardinality primitives.
11599        assert_eq!(p.has_unique_populated_kind(), p.populated_kind_count() == 1);
11600        assert_eq!(p.has_unique_missing_kind(), p.missing_kind_count() == 1);
11601        // Unique-primitive agreement.
11602        assert_eq!(
11603            p.has_unique_populated_kind(),
11604            p.unique_populated_kind().is_some()
11605        );
11606        assert_eq!(
11607            p.has_unique_missing_kind(),
11608            p.unique_missing_kind().is_some()
11609        );
11610    }
11611
11612    /// SINGLE-SLOT-DIAGONAL pin — a `LocalParent` populating exactly
11613    /// one slot returns `true` at `has_unique_populated_kind` (one
11614    /// populated) AND `false` at `has_unique_missing_kind` (two
11615    /// missing on `ALL.len() == 3`, not one). Pins that the well-
11616    /// formed arm coincides with the one-arm of the populated
11617    /// cardinality and lies OUTSIDE the one-arm of the missing
11618    /// cardinality on any `ALL.len() ≥ 3` closed set.
11619    #[test]
11620    fn tagged_union_default_has_unique_kinds_on_single_slot_diagonal() {
11621        for (populated, parent) in [
11622            (
11623                LocalKind::Alpha,
11624                LocalParent {
11625                    alpha: Some(1),
11626                    ..Default::default()
11627                },
11628            ),
11629            (
11630                LocalKind::Beta,
11631                LocalParent {
11632                    beta: Some(2),
11633                    ..Default::default()
11634                },
11635            ),
11636            (
11637                LocalKind::Gamma,
11638                LocalParent {
11639                    gamma: Some(3),
11640                    ..Default::default()
11641                },
11642            ),
11643        ] {
11644            assert!(
11645                parent.has_unique_populated_kind(),
11646                "single_slot({populated:?}) must be has_unique_populated_kind",
11647            );
11648            assert!(
11649                !parent.has_unique_missing_kind(),
11650                "single_slot({populated:?}) must NOT be has_unique_missing_kind (2 missing on ALL.len()==3)",
11651            );
11652            assert_eq!(
11653                parent.has_unique_populated_kind(),
11654                parent.populated_kind_count() == 1
11655            );
11656            assert_eq!(
11657                parent.has_unique_missing_kind(),
11658                parent.missing_kind_count() == 1
11659            );
11660        }
11661    }
11662
11663    /// SATURATED-PARENT pin — a `LocalParent` with EVERY slot populated
11664    /// returns `false` at BOTH `has_unique_populated_kind` (three
11665    /// populated, not one) AND `has_unique_missing_kind` (zero missing,
11666    /// not one). Pins the top-arm of the populated cardinality (which
11667    /// is NOT the one-arm) and the zero-arm of the missing cardinality
11668    /// (also NOT the one-arm) on the same fixture — the two primitives
11669    /// coincide on `false` here, distinguishing them from the
11670    /// (near-)saturation and near-empty arms outside the LocalParent
11671    /// scaffold's reach.
11672    #[test]
11673    fn tagged_union_default_has_unique_kinds_on_saturated_parent() {
11674        let p = LocalParent {
11675            alpha: Some(1),
11676            beta: Some(2),
11677            gamma: Some(3),
11678        };
11679        assert!(
11680            !p.has_unique_populated_kind(),
11681            "saturated parent must NOT be has_unique_populated_kind (three populated)",
11682        );
11683        assert!(
11684            !p.has_unique_missing_kind(),
11685            "saturated parent must NOT be has_unique_missing_kind (zero missing)",
11686        );
11687        assert_eq!(p.has_unique_populated_kind(), p.populated_kind_count() == 1);
11688        assert_eq!(p.has_unique_missing_kind(), p.missing_kind_count() == 1);
11689    }
11690
11691    /// NEAR-SATURATED (two-slot) pin — a `LocalParent` with exactly
11692    /// two slots populated returns `false` at `has_unique_populated_kind`
11693    /// (two populated, not one) AND `true` at `has_unique_missing_kind`
11694    /// (one missing on `ALL.len() == 3`). This is the SOLE arm on the
11695    /// LocalParent scaffold where the two Boolean cardinality-mid-
11696    /// endpoint peers DIVERGE — the pin distinguishes them from every
11697    /// other truth-table arm where they coincide.
11698    #[test]
11699    fn tagged_union_default_has_unique_kinds_on_near_saturated_parent() {
11700        for parent in [
11701            LocalParent {
11702                alpha: Some(1),
11703                beta: Some(2),
11704                ..Default::default()
11705            },
11706            LocalParent {
11707                alpha: Some(1),
11708                gamma: Some(3),
11709                ..Default::default()
11710            },
11711            LocalParent {
11712                beta: Some(2),
11713                gamma: Some(3),
11714                ..Default::default()
11715            },
11716        ] {
11717            assert!(
11718                !parent.has_unique_populated_kind(),
11719                "near-saturated parent must NOT be has_unique_populated_kind (2 populated)",
11720            );
11721            assert!(
11722                parent.has_unique_missing_kind(),
11723                "near-saturated parent must be has_unique_missing_kind (1 missing)",
11724            );
11725            assert_eq!(
11726                parent.has_unique_populated_kind(),
11727                parent.populated_kind_count() == 1,
11728            );
11729            assert_eq!(
11730                parent.has_unique_missing_kind(),
11731                parent.missing_kind_count() == 1,
11732            );
11733        }
11734    }
11735
11736    // -------------------------------------------------------------------
11737    // `TaggedUnion::has_multiple_(populated|missing)_kinds` default-body
11738    // truth table — pin the four cardinality arms (empty, single-slot
11739    // diagonal, near-saturated, saturated) on the sibling-shaped
11740    // `LocalParent` scaffold. These two primitives are the Boolean
11741    // cardinality many-arm peers of `populated_kind_count() >= 2` and
11742    // `missing_kind_count() >= 2` — the third arm of the {0, 1, ≥2}
11743    // cardinality trichotomy that closes alongside `is_empty` /
11744    // `has_unique_populated_kind` (populated axis) and `is_saturated` /
11745    // `has_unique_missing_kind` (missing axis).
11746    // -------------------------------------------------------------------
11747
11748    /// EMPTY-PARENT pin — an empty `LocalParent` returns `false` at
11749    /// `has_multiple_populated_kinds` (zero populated) AND `true` at
11750    /// `has_multiple_missing_kinds` (three missing on `ALL.len() == 3`,
11751    /// which is `>= 2`). Also pins the trichotomy partition law: on
11752    /// the empty arm exactly `is_empty()` is true on the populated
11753    /// axis, and exactly `has_multiple_missing_kinds()` is true on
11754    /// the missing axis.
11755    #[test]
11756    fn tagged_union_default_has_multiple_kinds_on_empty_parent() {
11757        let p = LocalParent::default();
11758        assert!(
11759            !p.has_multiple_populated_kinds(),
11760            "empty parent must NOT be has_multiple_populated_kinds (zero populated)",
11761        );
11762        assert!(
11763            p.has_multiple_missing_kinds(),
11764            "empty parent must be has_multiple_missing_kinds (three missing on ALL.len() == 3)",
11765        );
11766        // Composition laws.
11767        assert_eq!(
11768            p.has_multiple_populated_kinds(),
11769            p.populated_kind_count() >= 2
11770        );
11771        assert_eq!(p.has_multiple_missing_kinds(), p.missing_kind_count() >= 2);
11772        // Trichotomy partition — EXACTLY ONE of the three Boolean
11773        // primitives on each axis is true.
11774        assert_eq!(
11775            usize::from(p.is_empty())
11776                + usize::from(p.has_unique_populated_kind())
11777                + usize::from(p.has_multiple_populated_kinds()),
11778            1,
11779            "populated-axis trichotomy must be exactly-one on the empty arm",
11780        );
11781        assert_eq!(
11782            usize::from(p.is_saturated())
11783                + usize::from(p.has_unique_missing_kind())
11784                + usize::from(p.has_multiple_missing_kinds()),
11785            1,
11786            "missing-axis trichotomy must be exactly-one on the empty arm",
11787        );
11788    }
11789
11790    /// SINGLE-SLOT-DIAGONAL pin — a `LocalParent` populating exactly
11791    /// one slot returns `false` at `has_multiple_populated_kinds` AND
11792    /// `true` at `has_multiple_missing_kinds` (two missing on
11793    /// `ALL.len() == 3`, which is `>= 2`).
11794    #[test]
11795    fn tagged_union_default_has_multiple_kinds_on_single_slot_diagonal() {
11796        for (populated, parent) in [
11797            (
11798                LocalKind::Alpha,
11799                LocalParent {
11800                    alpha: Some(1),
11801                    ..Default::default()
11802                },
11803            ),
11804            (
11805                LocalKind::Beta,
11806                LocalParent {
11807                    beta: Some(2),
11808                    ..Default::default()
11809                },
11810            ),
11811            (
11812                LocalKind::Gamma,
11813                LocalParent {
11814                    gamma: Some(3),
11815                    ..Default::default()
11816                },
11817            ),
11818        ] {
11819            assert!(
11820                !parent.has_multiple_populated_kinds(),
11821                "single_slot({populated:?}) must NOT be has_multiple_populated_kinds",
11822            );
11823            assert!(
11824                parent.has_multiple_missing_kinds(),
11825                "single_slot({populated:?}) must be has_multiple_missing_kinds (2 missing on ALL.len() == 3)",
11826            );
11827            assert_eq!(
11828                parent.has_multiple_populated_kinds(),
11829                parent.populated_kind_count() >= 2,
11830            );
11831            assert_eq!(
11832                parent.has_multiple_missing_kinds(),
11833                parent.missing_kind_count() >= 2,
11834            );
11835            // Trichotomy partition — well-formed arm satisfies
11836            // `has_unique_populated_kind` on the populated axis and
11837            // `has_multiple_missing_kinds` on the missing axis.
11838            assert_eq!(
11839                usize::from(parent.is_empty())
11840                    + usize::from(parent.has_unique_populated_kind())
11841                    + usize::from(parent.has_multiple_populated_kinds()),
11842                1,
11843                "populated-axis trichotomy must be exactly-one on single_slot({populated:?})",
11844            );
11845            assert_eq!(
11846                usize::from(parent.is_saturated())
11847                    + usize::from(parent.has_unique_missing_kind())
11848                    + usize::from(parent.has_multiple_missing_kinds()),
11849                1,
11850                "missing-axis trichotomy must be exactly-one on single_slot({populated:?})",
11851            );
11852        }
11853    }
11854
11855    /// NEAR-SATURATED (two-slot) pin — a `LocalParent` with exactly
11856    /// two slots populated returns `true` at `has_multiple_populated_kinds`
11857    /// (two populated) AND `false` at `has_multiple_missing_kinds`
11858    /// (one missing on `ALL.len() == 3`).
11859    #[test]
11860    fn tagged_union_default_has_multiple_kinds_on_near_saturated_parent() {
11861        for parent in [
11862            LocalParent {
11863                alpha: Some(1),
11864                beta: Some(2),
11865                ..Default::default()
11866            },
11867            LocalParent {
11868                alpha: Some(1),
11869                gamma: Some(3),
11870                ..Default::default()
11871            },
11872            LocalParent {
11873                beta: Some(2),
11874                gamma: Some(3),
11875                ..Default::default()
11876            },
11877        ] {
11878            assert!(
11879                parent.has_multiple_populated_kinds(),
11880                "near-saturated parent must be has_multiple_populated_kinds (2 populated)",
11881            );
11882            assert!(
11883                !parent.has_multiple_missing_kinds(),
11884                "near-saturated parent must NOT be has_multiple_missing_kinds (1 missing)",
11885            );
11886            assert_eq!(
11887                parent.has_multiple_populated_kinds(),
11888                parent.populated_kind_count() >= 2,
11889            );
11890            assert_eq!(
11891                parent.has_multiple_missing_kinds(),
11892                parent.missing_kind_count() >= 2,
11893            );
11894            // Trichotomy partition — near-saturated arm satisfies
11895            // `has_multiple_populated_kinds` on the populated axis and
11896            // `has_unique_missing_kind` on the missing axis.
11897            assert_eq!(
11898                usize::from(parent.is_empty())
11899                    + usize::from(parent.has_unique_populated_kind())
11900                    + usize::from(parent.has_multiple_populated_kinds()),
11901                1,
11902                "populated-axis trichotomy must be exactly-one on near-saturated arm",
11903            );
11904            assert_eq!(
11905                usize::from(parent.is_saturated())
11906                    + usize::from(parent.has_unique_missing_kind())
11907                    + usize::from(parent.has_multiple_missing_kinds()),
11908                1,
11909                "missing-axis trichotomy must be exactly-one on near-saturated arm",
11910            );
11911        }
11912    }
11913
11914    /// SATURATED-PARENT pin — a `LocalParent` with EVERY slot
11915    /// populated returns `true` at `has_multiple_populated_kinds`
11916    /// (three populated) AND `false` at `has_multiple_missing_kinds`
11917    /// (zero missing).
11918    #[test]
11919    fn tagged_union_default_has_multiple_kinds_on_saturated_parent() {
11920        let p = LocalParent {
11921            alpha: Some(1),
11922            beta: Some(2),
11923            gamma: Some(3),
11924        };
11925        assert!(
11926            p.has_multiple_populated_kinds(),
11927            "saturated parent must be has_multiple_populated_kinds (three populated)",
11928        );
11929        assert!(
11930            !p.has_multiple_missing_kinds(),
11931            "saturated parent must NOT be has_multiple_missing_kinds (zero missing)",
11932        );
11933        assert_eq!(
11934            p.has_multiple_populated_kinds(),
11935            p.populated_kind_count() >= 2
11936        );
11937        assert_eq!(p.has_multiple_missing_kinds(), p.missing_kind_count() >= 2);
11938        // Trichotomy partition — saturated arm satisfies
11939        // `has_multiple_populated_kinds` on the populated axis and
11940        // `is_saturated` on the missing axis.
11941        assert_eq!(
11942            usize::from(p.is_empty())
11943                + usize::from(p.has_unique_populated_kind())
11944                + usize::from(p.has_multiple_populated_kinds()),
11945            1,
11946            "populated-axis trichotomy must be exactly-one on saturated arm",
11947        );
11948        assert_eq!(
11949            usize::from(p.is_saturated())
11950                + usize::from(p.has_unique_missing_kind())
11951                + usize::from(p.has_multiple_missing_kinds()),
11952            1,
11953            "missing-axis trichotomy must be exactly-one on saturated arm",
11954        );
11955    }
11956
11957    /// The `assert_is_empty_matches_populated_kind_count` primitive
11958    /// accepts the [`LocalParent`] scaffold coherently.
11959    #[test]
11960    fn assert_is_empty_matches_populated_kind_count_accepts_coherent_local_impl() {
11961        fn make_local(k: LocalKind) -> LocalParent {
11962            match k {
11963                LocalKind::Alpha => LocalParent {
11964                    alpha: Some(11),
11965                    ..Default::default()
11966                },
11967                LocalKind::Beta => LocalParent {
11968                    beta: Some(22),
11969                    ..Default::default()
11970                },
11971                LocalKind::Gamma => LocalParent {
11972                    gamma: Some(33),
11973                    ..Default::default()
11974                },
11975            }
11976        }
11977        assert_is_empty_matches_populated_kind_count::<LocalParent, _, _>(
11978            make_local,
11979            LocalParent::default,
11980        );
11981    }
11982
11983    /// A factory that yields an all-empty parent on the single-slot
11984    /// diagonal (so `is_empty()` returns `true` when the diagonal
11985    /// contract requires `false`) MUST fail-loudly at the caller's
11986    /// site through the primitive's single-slot-diagonal arm — a
11987    /// regression that dropped the `!is_empty` assertion on the
11988    /// well-formed arm surfaces here.
11989    #[test]
11990    #[should_panic(expected = "must equal false")]
11991    fn assert_is_empty_matches_populated_kind_count_rejects_empty_factory() {
11992        fn empty_factory(_: LocalKind) -> LocalParent {
11993            LocalParent::default()
11994        }
11995        assert_is_empty_matches_populated_kind_count::<LocalParent, _, _>(
11996            empty_factory,
11997            LocalParent::default,
11998        );
11999    }
12000
12001    /// A factory that yields a NON-empty parent from `empty_parent()`
12002    /// (so `is_empty()` returns `false` when the baseline contract
12003    /// requires `true`) MUST fail-loudly at the caller's site through
12004    /// the primitive's baseline arm — a regression that dropped the
12005    /// empty-parent baseline assertion surfaces here.
12006    #[test]
12007    #[should_panic(expected = "on empty_parent() must equal true")]
12008    fn assert_is_empty_matches_populated_kind_count_rejects_non_empty_baseline() {
12009        fn make_local(k: LocalKind) -> LocalParent {
12010            match k {
12011                LocalKind::Alpha => LocalParent {
12012                    alpha: Some(11),
12013                    ..Default::default()
12014                },
12015                LocalKind::Beta => LocalParent {
12016                    beta: Some(22),
12017                    ..Default::default()
12018                },
12019                LocalKind::Gamma => LocalParent {
12020                    gamma: Some(33),
12021                    ..Default::default()
12022                },
12023            }
12024        }
12025        fn non_empty_baseline() -> LocalParent {
12026            LocalParent {
12027                alpha: Some(999),
12028                ..Default::default()
12029            }
12030        }
12031        assert_is_empty_matches_populated_kind_count::<LocalParent, _, _>(
12032            make_local,
12033            non_empty_baseline,
12034        );
12035    }
12036
12037    /// The `assert_is_saturated_matches_missing_kind_count` primitive
12038    /// accepts the [`LocalParent`] scaffold coherently.
12039    #[test]
12040    fn assert_is_saturated_matches_missing_kind_count_accepts_coherent_local_impl() {
12041        fn make_local(k: LocalKind) -> LocalParent {
12042            match k {
12043                LocalKind::Alpha => LocalParent {
12044                    alpha: Some(11),
12045                    ..Default::default()
12046                },
12047                LocalKind::Beta => LocalParent {
12048                    beta: Some(22),
12049                    ..Default::default()
12050                },
12051                LocalKind::Gamma => LocalParent {
12052                    gamma: Some(33),
12053                    ..Default::default()
12054                },
12055            }
12056        }
12057        assert_is_saturated_matches_missing_kind_count::<LocalParent, _, _>(
12058            make_local,
12059            LocalParent::default,
12060        );
12061    }
12062
12063    /// A factory that yields a saturated parent on the single-slot
12064    /// diagonal (so `is_saturated()` returns `true` when the diagonal
12065    /// contract requires `false`) MUST fail-loudly at the caller's
12066    /// site through the primitive's single-slot-diagonal arm.
12067    #[test]
12068    #[should_panic(expected = "must equal false")]
12069    fn assert_is_saturated_matches_missing_kind_count_rejects_saturated_factory() {
12070        fn saturated_factory(_: LocalKind) -> LocalParent {
12071            LocalParent {
12072                alpha: Some(1),
12073                beta: Some(2),
12074                gamma: Some(3),
12075            }
12076        }
12077        assert_is_saturated_matches_missing_kind_count::<LocalParent, _, _>(
12078            saturated_factory,
12079            LocalParent::default,
12080        );
12081    }
12082
12083    /// A factory that yields a saturated parent from `empty_parent()`
12084    /// (so `is_saturated()` returns `true` when the baseline contract
12085    /// requires `false`) MUST fail-loudly at the caller's site through
12086    /// the primitive's baseline arm.
12087    #[test]
12088    #[should_panic(expected = "on empty_parent() must equal false")]
12089    fn assert_is_saturated_matches_missing_kind_count_rejects_saturated_baseline() {
12090        fn make_local(k: LocalKind) -> LocalParent {
12091            match k {
12092                LocalKind::Alpha => LocalParent {
12093                    alpha: Some(11),
12094                    ..Default::default()
12095                },
12096                LocalKind::Beta => LocalParent {
12097                    beta: Some(22),
12098                    ..Default::default()
12099                },
12100                LocalKind::Gamma => LocalParent {
12101                    gamma: Some(33),
12102                    ..Default::default()
12103                },
12104            }
12105        }
12106        fn saturated_baseline() -> LocalParent {
12107            LocalParent {
12108                alpha: Some(1),
12109                beta: Some(2),
12110                gamma: Some(3),
12111            }
12112        }
12113        assert_is_saturated_matches_missing_kind_count::<LocalParent, _, _>(
12114            make_local,
12115            saturated_baseline,
12116        );
12117    }
12118
12119    /// Every one of the four production `.variant()` sites on
12120    /// `ProcessSpec` binds through the zero-populated-cardinality
12121    /// Boolean primitive coherently — every per-site `single_slot_X(k)`
12122    /// factory produces a `!is_empty()` parent, and
12123    /// `X::default().is_empty() == true` on the empty-parent baseline.
12124    #[test]
12125    fn every_production_tagged_union_binds_through_the_is_empty_testkit_primitive() {
12126        assert_is_empty_matches_populated_kind_count::<crate::intent::Intent, _, _>(
12127            single_slot_intent_probe,
12128            crate::intent::Intent::default,
12129        );
12130        assert_is_empty_matches_populated_kind_count::<crate::encapsulates::EncapsulationKind, _, _>(
12131            single_slot_encapsulation_kind_probe,
12132            crate::encapsulates::EncapsulationKind::default,
12133        );
12134        assert_is_empty_matches_populated_kind_count::<crate::export::ArtifactSource, _, _>(
12135            single_slot_artifact_source_probe,
12136            crate::export::ArtifactSource::default,
12137        );
12138        assert_is_empty_matches_populated_kind_count::<crate::export::VectorChannel, _, _>(
12139            single_slot_vector_channel_probe,
12140            crate::export::VectorChannel::default,
12141        );
12142    }
12143
12144    /// Every one of the four production `.variant()` sites on
12145    /// `ProcessSpec` binds through the zero-missing-cardinality
12146    /// Boolean primitive coherently — every per-site `single_slot_X(k)`
12147    /// factory produces a `!is_saturated()` parent (there are ≥ 2
12148    /// missing slots on every real-world tagged union in the
12149    /// workspace), and `X::default().is_saturated() == false` on the
12150    /// empty-parent baseline.
12151    #[test]
12152    fn every_production_tagged_union_binds_through_the_is_saturated_testkit_primitive() {
12153        assert_is_saturated_matches_missing_kind_count::<crate::intent::Intent, _, _>(
12154            single_slot_intent_probe,
12155            crate::intent::Intent::default,
12156        );
12157        assert_is_saturated_matches_missing_kind_count::<
12158            crate::encapsulates::EncapsulationKind,
12159            _,
12160            _,
12161        >(
12162            single_slot_encapsulation_kind_probe,
12163            crate::encapsulates::EncapsulationKind::default,
12164        );
12165        assert_is_saturated_matches_missing_kind_count::<crate::export::ArtifactSource, _, _>(
12166            single_slot_artifact_source_probe,
12167            crate::export::ArtifactSource::default,
12168        );
12169        assert_is_saturated_matches_missing_kind_count::<crate::export::VectorChannel, _, _>(
12170            single_slot_vector_channel_probe,
12171            crate::export::VectorChannel::default,
12172        );
12173    }
12174
12175    /// The `assert_has_any_populated_kind_matches_populated_kind_count`
12176    /// primitive accepts the [`LocalParent`] scaffold coherently.
12177    #[test]
12178    fn assert_has_any_populated_kind_matches_populated_kind_count_accepts_coherent_local_impl() {
12179        fn make_local(k: LocalKind) -> LocalParent {
12180            match k {
12181                LocalKind::Alpha => LocalParent {
12182                    alpha: Some(11),
12183                    ..Default::default()
12184                },
12185                LocalKind::Beta => LocalParent {
12186                    beta: Some(22),
12187                    ..Default::default()
12188                },
12189                LocalKind::Gamma => LocalParent {
12190                    gamma: Some(33),
12191                    ..Default::default()
12192                },
12193            }
12194        }
12195        assert_has_any_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
12196            make_local,
12197            LocalParent::default,
12198        );
12199    }
12200
12201    /// A factory that yields an all-empty parent on the single-slot
12202    /// diagonal (so `has_any_populated_kind()` returns `false` when the
12203    /// diagonal contract requires `true`) MUST fail-loudly at the
12204    /// caller's site through the primitive's single-slot-diagonal arm.
12205    #[test]
12206    #[should_panic(expected = "must equal true")]
12207    fn assert_has_any_populated_kind_matches_populated_kind_count_rejects_empty_factory() {
12208        fn empty_factory(_: LocalKind) -> LocalParent {
12209            LocalParent::default()
12210        }
12211        assert_has_any_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
12212            empty_factory,
12213            LocalParent::default,
12214        );
12215    }
12216
12217    /// A factory that yields a NON-empty parent from `empty_parent()`
12218    /// (so `has_any_populated_kind()` returns `true` when the baseline
12219    /// contract requires `false`) MUST fail-loudly at the caller's site
12220    /// through the primitive's baseline arm.
12221    #[test]
12222    #[should_panic(expected = "on empty_parent() must equal false")]
12223    fn assert_has_any_populated_kind_matches_populated_kind_count_rejects_non_empty_baseline() {
12224        fn make_local(k: LocalKind) -> LocalParent {
12225            match k {
12226                LocalKind::Alpha => LocalParent {
12227                    alpha: Some(11),
12228                    ..Default::default()
12229                },
12230                LocalKind::Beta => LocalParent {
12231                    beta: Some(22),
12232                    ..Default::default()
12233                },
12234                LocalKind::Gamma => LocalParent {
12235                    gamma: Some(33),
12236                    ..Default::default()
12237                },
12238            }
12239        }
12240        fn non_empty_baseline() -> LocalParent {
12241            LocalParent {
12242                alpha: Some(999),
12243                ..Default::default()
12244            }
12245        }
12246        assert_has_any_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
12247            make_local,
12248            non_empty_baseline,
12249        );
12250    }
12251
12252    /// The `assert_has_any_missing_kind_matches_missing_kind_count`
12253    /// primitive accepts the [`LocalParent`] scaffold coherently.
12254    /// `LocalKind::ALL.len() == 3` so a well-formed single-slot parent
12255    /// has `3 - 1 == 2` missing slots, meaning `has_any_missing_kind()
12256    /// == true` on the diagonal.
12257    #[test]
12258    fn assert_has_any_missing_kind_matches_missing_kind_count_accepts_coherent_local_impl() {
12259        fn make_local(k: LocalKind) -> LocalParent {
12260            match k {
12261                LocalKind::Alpha => LocalParent {
12262                    alpha: Some(11),
12263                    ..Default::default()
12264                },
12265                LocalKind::Beta => LocalParent {
12266                    beta: Some(22),
12267                    ..Default::default()
12268                },
12269                LocalKind::Gamma => LocalParent {
12270                    gamma: Some(33),
12271                    ..Default::default()
12272                },
12273            }
12274        }
12275        assert_has_any_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
12276            make_local,
12277            LocalParent::default,
12278        );
12279    }
12280
12281    /// A factory that yields a saturated parent on the single-slot
12282    /// diagonal (so `has_any_missing_kind()` returns `false` when the
12283    /// diagonal contract requires `true`) MUST fail-loudly at the
12284    /// caller's site through the primitive's single-slot-diagonal arm.
12285    #[test]
12286    #[should_panic(expected = "must equal true")]
12287    fn assert_has_any_missing_kind_matches_missing_kind_count_rejects_saturated_factory() {
12288        fn saturated_factory(_: LocalKind) -> LocalParent {
12289            LocalParent {
12290                alpha: Some(1),
12291                beta: Some(2),
12292                gamma: Some(3),
12293            }
12294        }
12295        assert_has_any_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
12296            saturated_factory,
12297            LocalParent::default,
12298        );
12299    }
12300
12301    /// A factory that yields a saturated parent from `empty_parent()`
12302    /// (so `has_any_missing_kind()` returns `false` when the baseline
12303    /// contract requires `true`) MUST fail-loudly at the caller's site
12304    /// through the primitive's baseline arm.
12305    #[test]
12306    #[should_panic(expected = "on empty_parent() must equal true")]
12307    fn assert_has_any_missing_kind_matches_missing_kind_count_rejects_saturated_baseline() {
12308        fn make_local(k: LocalKind) -> LocalParent {
12309            match k {
12310                LocalKind::Alpha => LocalParent {
12311                    alpha: Some(11),
12312                    ..Default::default()
12313                },
12314                LocalKind::Beta => LocalParent {
12315                    beta: Some(22),
12316                    ..Default::default()
12317                },
12318                LocalKind::Gamma => LocalParent {
12319                    gamma: Some(33),
12320                    ..Default::default()
12321                },
12322            }
12323        }
12324        fn saturated_baseline() -> LocalParent {
12325            LocalParent {
12326                alpha: Some(1),
12327                beta: Some(2),
12328                gamma: Some(3),
12329            }
12330        }
12331        assert_has_any_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
12332            make_local,
12333            saturated_baseline,
12334        );
12335    }
12336
12337    /// Every one of the four production `.variant()` sites on
12338    /// `ProcessSpec` binds through the at-least-one-populated-
12339    /// cardinality Boolean primitive coherently — every per-site
12340    /// `single_slot_X(k)` factory produces a `has_any_populated_kind()
12341    /// == true` parent, and `X::default().has_any_populated_kind() ==
12342    /// false` on the empty-parent baseline.
12343    #[test]
12344    fn every_production_tagged_union_binds_through_the_has_any_populated_kind_testkit_primitive() {
12345        assert_has_any_populated_kind_matches_populated_kind_count::<crate::intent::Intent, _, _>(
12346            single_slot_intent_probe,
12347            crate::intent::Intent::default,
12348        );
12349        assert_has_any_populated_kind_matches_populated_kind_count::<
12350            crate::encapsulates::EncapsulationKind,
12351            _,
12352            _,
12353        >(
12354            single_slot_encapsulation_kind_probe,
12355            crate::encapsulates::EncapsulationKind::default,
12356        );
12357        assert_has_any_populated_kind_matches_populated_kind_count::<
12358            crate::export::ArtifactSource,
12359            _,
12360            _,
12361        >(
12362            single_slot_artifact_source_probe,
12363            crate::export::ArtifactSource::default,
12364        );
12365        assert_has_any_populated_kind_matches_populated_kind_count::<
12366            crate::export::VectorChannel,
12367            _,
12368            _,
12369        >(
12370            single_slot_vector_channel_probe,
12371            crate::export::VectorChannel::default,
12372        );
12373    }
12374
12375    /// Every one of the four production `.variant()` sites on
12376    /// `ProcessSpec` binds through the at-least-one-missing-
12377    /// cardinality Boolean primitive coherently — every per-site
12378    /// `single_slot_X(k)` factory produces a `has_any_missing_kind() ==
12379    /// true` parent (there are ≥ 2 missing slots on every real-world
12380    /// tagged union in the workspace, since `ALL.len() ≥ 2`), and
12381    /// `X::default().has_any_missing_kind() == true` on the empty-
12382    /// parent baseline (every slot is missing).
12383    #[test]
12384    fn every_production_tagged_union_binds_through_the_has_any_missing_kind_testkit_primitive() {
12385        assert_has_any_missing_kind_matches_missing_kind_count::<crate::intent::Intent, _, _>(
12386            single_slot_intent_probe,
12387            crate::intent::Intent::default,
12388        );
12389        assert_has_any_missing_kind_matches_missing_kind_count::<
12390            crate::encapsulates::EncapsulationKind,
12391            _,
12392            _,
12393        >(
12394            single_slot_encapsulation_kind_probe,
12395            crate::encapsulates::EncapsulationKind::default,
12396        );
12397        assert_has_any_missing_kind_matches_missing_kind_count::<crate::export::ArtifactSource, _, _>(
12398            single_slot_artifact_source_probe,
12399            crate::export::ArtifactSource::default,
12400        );
12401        assert_has_any_missing_kind_matches_missing_kind_count::<crate::export::VectorChannel, _, _>(
12402            single_slot_vector_channel_probe,
12403            crate::export::VectorChannel::default,
12404        );
12405    }
12406
12407    /// The `assert_has_unique_populated_kind_matches_populated_kind_count`
12408    /// primitive accepts the [`LocalParent`] scaffold coherently.
12409    #[test]
12410    fn assert_has_unique_populated_kind_matches_populated_kind_count_accepts_coherent_local_impl() {
12411        fn make_local(k: LocalKind) -> LocalParent {
12412            match k {
12413                LocalKind::Alpha => LocalParent {
12414                    alpha: Some(11),
12415                    ..Default::default()
12416                },
12417                LocalKind::Beta => LocalParent {
12418                    beta: Some(22),
12419                    ..Default::default()
12420                },
12421                LocalKind::Gamma => LocalParent {
12422                    gamma: Some(33),
12423                    ..Default::default()
12424                },
12425            }
12426        }
12427        assert_has_unique_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
12428            make_local,
12429            LocalParent::default,
12430        );
12431    }
12432
12433    /// A factory that yields an all-empty parent on the single-slot
12434    /// diagonal (so `has_unique_populated_kind()` returns `false` when
12435    /// the diagonal contract requires `true`) MUST fail-loudly at the
12436    /// caller's site through the primitive's single-slot-diagonal arm.
12437    #[test]
12438    #[should_panic(expected = "must equal true")]
12439    fn assert_has_unique_populated_kind_matches_populated_kind_count_rejects_empty_factory() {
12440        fn empty_factory(_: LocalKind) -> LocalParent {
12441            LocalParent::default()
12442        }
12443        assert_has_unique_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
12444            empty_factory,
12445            LocalParent::default,
12446        );
12447    }
12448
12449    /// A factory that yields a WELL-FORMED parent from `empty_parent()`
12450    /// (so `has_unique_populated_kind()` returns `true` when the
12451    /// baseline contract requires `false`) MUST fail-loudly at the
12452    /// caller's site through the primitive's baseline arm.
12453    #[test]
12454    #[should_panic(expected = "on empty_parent() must equal false")]
12455    fn assert_has_unique_populated_kind_matches_populated_kind_count_rejects_wellformed_baseline() {
12456        fn make_local(k: LocalKind) -> LocalParent {
12457            match k {
12458                LocalKind::Alpha => LocalParent {
12459                    alpha: Some(11),
12460                    ..Default::default()
12461                },
12462                LocalKind::Beta => LocalParent {
12463                    beta: Some(22),
12464                    ..Default::default()
12465                },
12466                LocalKind::Gamma => LocalParent {
12467                    gamma: Some(33),
12468                    ..Default::default()
12469                },
12470            }
12471        }
12472        fn wellformed_baseline() -> LocalParent {
12473            LocalParent {
12474                alpha: Some(999),
12475                ..Default::default()
12476            }
12477        }
12478        assert_has_unique_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
12479            make_local,
12480            wellformed_baseline,
12481        );
12482    }
12483
12484    /// The `assert_has_unique_missing_kind_matches_missing_kind_count`
12485    /// primitive accepts the [`LocalParent`] scaffold coherently.
12486    /// `LocalKind::ALL.len() == 3` so a well-formed single-slot parent
12487    /// has `3 - 1 == 2` missing slots, meaning
12488    /// `has_unique_missing_kind() == false` on the diagonal.
12489    #[test]
12490    fn assert_has_unique_missing_kind_matches_missing_kind_count_accepts_coherent_local_impl() {
12491        fn make_local(k: LocalKind) -> LocalParent {
12492            match k {
12493                LocalKind::Alpha => LocalParent {
12494                    alpha: Some(11),
12495                    ..Default::default()
12496                },
12497                LocalKind::Beta => LocalParent {
12498                    beta: Some(22),
12499                    ..Default::default()
12500                },
12501                LocalKind::Gamma => LocalParent {
12502                    gamma: Some(33),
12503                    ..Default::default()
12504                },
12505            }
12506        }
12507        assert_has_unique_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
12508            make_local,
12509            LocalParent::default,
12510        );
12511    }
12512
12513    /// A factory that yields a NEAR-SATURATED (two-slot) parent on the
12514    /// single-slot diagonal — so `has_unique_missing_kind()` returns
12515    /// `true` (exactly one missing on an `ALL.len() == 3` closed set)
12516    /// when the diagonal contract on this scaffold requires `false`
12517    /// (a well-formed one-slot parent has two missing, not one) — MUST
12518    /// fail-loudly at the caller's site through the primitive's
12519    /// single-slot-diagonal arm.
12520    #[test]
12521    #[should_panic(expected = "must equal false")]
12522    fn assert_has_unique_missing_kind_matches_missing_kind_count_rejects_near_saturated_factory() {
12523        fn near_saturated(k: LocalKind) -> LocalParent {
12524            // Populate two slots regardless of `k`, leaving exactly one
12525            // missing — mimics a factory that "helpfully" pre-populates
12526            // extras and drifts off the well-formed diagonal.
12527            let mut p = LocalParent {
12528                alpha: Some(1),
12529                beta: Some(2),
12530                ..Default::default()
12531            };
12532            if let LocalKind::Gamma = k {
12533                p.gamma = Some(3);
12534                // Now saturated — drop back to two-slot by clearing
12535                // alpha, so exactly one missing again.
12536                p.alpha = None;
12537            }
12538            p
12539        }
12540        assert_has_unique_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
12541            near_saturated,
12542            LocalParent::default,
12543        );
12544    }
12545
12546    /// A factory that yields a NEAR-SATURATED parent from
12547    /// `empty_parent()` (so `has_unique_missing_kind()` returns `true`
12548    /// when the baseline contract requires `false`) MUST fail-loudly
12549    /// at the caller's site through the primitive's baseline arm.
12550    #[test]
12551    #[should_panic(expected = "on empty_parent() must equal false")]
12552    fn assert_has_unique_missing_kind_matches_missing_kind_count_rejects_near_saturated_baseline() {
12553        fn make_local(k: LocalKind) -> LocalParent {
12554            match k {
12555                LocalKind::Alpha => LocalParent {
12556                    alpha: Some(11),
12557                    ..Default::default()
12558                },
12559                LocalKind::Beta => LocalParent {
12560                    beta: Some(22),
12561                    ..Default::default()
12562                },
12563                LocalKind::Gamma => LocalParent {
12564                    gamma: Some(33),
12565                    ..Default::default()
12566                },
12567            }
12568        }
12569        fn near_saturated_baseline() -> LocalParent {
12570            LocalParent {
12571                alpha: Some(1),
12572                beta: Some(2),
12573                ..Default::default()
12574            }
12575        }
12576        assert_has_unique_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
12577            make_local,
12578            near_saturated_baseline,
12579        );
12580    }
12581
12582    /// Every one of the four production `.variant()` sites on
12583    /// `ProcessSpec` binds through the one-populated-cardinality
12584    /// Boolean primitive coherently — every per-site `single_slot_X(k)`
12585    /// factory produces a `has_unique_populated_kind() == true` parent,
12586    /// and `X::default().has_unique_populated_kind() == false` on the
12587    /// empty-parent baseline.
12588    #[test]
12589    fn every_production_tagged_union_binds_through_the_has_unique_populated_kind_testkit_primitive()
12590    {
12591        assert_has_unique_populated_kind_matches_populated_kind_count::<crate::intent::Intent, _, _>(
12592            single_slot_intent_probe,
12593            crate::intent::Intent::default,
12594        );
12595        assert_has_unique_populated_kind_matches_populated_kind_count::<
12596            crate::encapsulates::EncapsulationKind,
12597            _,
12598            _,
12599        >(
12600            single_slot_encapsulation_kind_probe,
12601            crate::encapsulates::EncapsulationKind::default,
12602        );
12603        assert_has_unique_populated_kind_matches_populated_kind_count::<
12604            crate::export::ArtifactSource,
12605            _,
12606            _,
12607        >(
12608            single_slot_artifact_source_probe,
12609            crate::export::ArtifactSource::default,
12610        );
12611        assert_has_unique_populated_kind_matches_populated_kind_count::<
12612            crate::export::VectorChannel,
12613            _,
12614            _,
12615        >(
12616            single_slot_vector_channel_probe,
12617            crate::export::VectorChannel::default,
12618        );
12619    }
12620
12621    /// Every one of the four production `.variant()` sites on
12622    /// `ProcessSpec` binds through the one-missing-cardinality Boolean
12623    /// primitive coherently — every per-site `single_slot_X(k)` factory
12624    /// produces a `has_unique_missing_kind() == false` parent (there
12625    /// are ≥ 2 missing slots on every real-world tagged union in the
12626    /// workspace: `Intent` `ALL.len() == 6`, `EncapsulationKind` `>= 3`,
12627    /// `ArtifactSource` `>= 3`, `VectorChannel` `>= 3`), and
12628    /// `X::default().has_unique_missing_kind() == false` on the empty-
12629    /// parent baseline (every slot missing, not exactly one).
12630    #[test]
12631    fn every_production_tagged_union_binds_through_the_has_unique_missing_kind_testkit_primitive() {
12632        assert_has_unique_missing_kind_matches_missing_kind_count::<crate::intent::Intent, _, _>(
12633            single_slot_intent_probe,
12634            crate::intent::Intent::default,
12635        );
12636        assert_has_unique_missing_kind_matches_missing_kind_count::<
12637            crate::encapsulates::EncapsulationKind,
12638            _,
12639            _,
12640        >(
12641            single_slot_encapsulation_kind_probe,
12642            crate::encapsulates::EncapsulationKind::default,
12643        );
12644        assert_has_unique_missing_kind_matches_missing_kind_count::<
12645            crate::export::ArtifactSource,
12646            _,
12647            _,
12648        >(
12649            single_slot_artifact_source_probe,
12650            crate::export::ArtifactSource::default,
12651        );
12652        assert_has_unique_missing_kind_matches_missing_kind_count::<
12653            crate::export::VectorChannel,
12654            _,
12655            _,
12656        >(
12657            single_slot_vector_channel_probe,
12658            crate::export::VectorChannel::default,
12659        );
12660    }
12661
12662    // -------------------------------------------------------------------
12663    // `assert_has_multiple_(populated|missing)_kinds_matches_(populated|
12664    // missing)_kind_count` — the ≥2-cardinality Boolean testkit
12665    // primitives. Pin acceptance on the coherent LocalParent scaffold +
12666    // rejection on the two obvious factory drifts + a production sweep
12667    // binding all four `.variant()` sites through the trichotomy law
12668    // (is_empty + has_unique_populated_kind + has_multiple_populated_kinds
12669    // == 1 on every arm, and the missing-axis peer).
12670    // -------------------------------------------------------------------
12671
12672    /// The `assert_has_multiple_populated_kinds_matches_populated_kind_count`
12673    /// primitive accepts the [`LocalParent`] scaffold coherently — the
12674    /// coherent-impl side has no false-positive drift on the empty
12675    /// baseline, the single-slot diagonal, or the two-slot sweep.
12676    #[test]
12677    fn assert_has_multiple_populated_kinds_matches_populated_kind_count_accepts_coherent_local_impl(
12678    ) {
12679        fn single_slot(k: LocalKind) -> LocalParent {
12680            match k {
12681                LocalKind::Alpha => LocalParent {
12682                    alpha: Some(1),
12683                    ..Default::default()
12684                },
12685                LocalKind::Beta => LocalParent {
12686                    beta: Some(2),
12687                    ..Default::default()
12688                },
12689                LocalKind::Gamma => LocalParent {
12690                    gamma: Some(3),
12691                    ..Default::default()
12692                },
12693            }
12694        }
12695        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
12696            let mut p = LocalParent::default();
12697            for k in [a, b] {
12698                match k {
12699                    LocalKind::Alpha => p.alpha = Some(1),
12700                    LocalKind::Beta => p.beta = Some(2),
12701                    LocalKind::Gamma => p.gamma = Some(3),
12702                }
12703            }
12704            p
12705        }
12706        assert_has_multiple_populated_kinds_matches_populated_kind_count::<LocalParent, _, _, _>(
12707            single_slot,
12708            two_slot,
12709            LocalParent::default,
12710        );
12711    }
12712
12713    /// The primitive rejects an `empty_parent` factory that yields a
12714    /// two-slot parent (baseline expects zero-populated on empty).
12715    #[test]
12716    #[should_panic(
12717        expected = "TaggedUnion::has_multiple_populated_kinds() on empty_parent() must equal false"
12718    )]
12719    fn assert_has_multiple_populated_kinds_matches_populated_kind_count_rejects_two_slot_baseline()
12720    {
12721        fn single_slot(k: LocalKind) -> LocalParent {
12722            match k {
12723                LocalKind::Alpha => LocalParent {
12724                    alpha: Some(1),
12725                    ..Default::default()
12726                },
12727                LocalKind::Beta => LocalParent {
12728                    beta: Some(2),
12729                    ..Default::default()
12730                },
12731                LocalKind::Gamma => LocalParent {
12732                    gamma: Some(3),
12733                    ..Default::default()
12734                },
12735            }
12736        }
12737        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
12738            let mut p = LocalParent::default();
12739            for k in [a, b] {
12740                match k {
12741                    LocalKind::Alpha => p.alpha = Some(1),
12742                    LocalKind::Beta => p.beta = Some(2),
12743                    LocalKind::Gamma => p.gamma = Some(3),
12744                }
12745            }
12746            p
12747        }
12748        fn two_slot_baseline() -> LocalParent {
12749            LocalParent {
12750                alpha: Some(1),
12751                beta: Some(2),
12752                ..Default::default()
12753            }
12754        }
12755        assert_has_multiple_populated_kinds_matches_populated_kind_count::<LocalParent, _, _, _>(
12756            single_slot,
12757            two_slot,
12758            two_slot_baseline,
12759        );
12760    }
12761
12762    /// The primitive rejects a `two_slot` factory that yields a
12763    /// single-slot parent (two-slot sweep expects has_multiple ==
12764    /// true).
12765    #[test]
12766    #[should_panic(expected = "TaggedUnion::has_multiple_populated_kinds() on two_slot(")]
12767    fn assert_has_multiple_populated_kinds_matches_populated_kind_count_rejects_single_slot_two_slot_factory(
12768    ) {
12769        fn single_slot(k: LocalKind) -> LocalParent {
12770            match k {
12771                LocalKind::Alpha => LocalParent {
12772                    alpha: Some(1),
12773                    ..Default::default()
12774                },
12775                LocalKind::Beta => LocalParent {
12776                    beta: Some(2),
12777                    ..Default::default()
12778                },
12779                LocalKind::Gamma => LocalParent {
12780                    gamma: Some(3),
12781                    ..Default::default()
12782                },
12783            }
12784        }
12785        fn drifted_two_slot(a: LocalKind, _: LocalKind) -> LocalParent {
12786            // Only populates the first slot — the two-slot invariant
12787            // is violated.
12788            single_slot(a)
12789        }
12790        assert_has_multiple_populated_kinds_matches_populated_kind_count::<LocalParent, _, _, _>(
12791            single_slot,
12792            drifted_two_slot,
12793            LocalParent::default,
12794        );
12795    }
12796
12797    /// The `assert_has_multiple_missing_kinds_matches_missing_kind_count`
12798    /// primitive accepts the [`LocalParent`] scaffold coherently.
12799    #[test]
12800    fn assert_has_multiple_missing_kinds_matches_missing_kind_count_accepts_coherent_local_impl() {
12801        fn single_slot(k: LocalKind) -> LocalParent {
12802            match k {
12803                LocalKind::Alpha => LocalParent {
12804                    alpha: Some(1),
12805                    ..Default::default()
12806                },
12807                LocalKind::Beta => LocalParent {
12808                    beta: Some(2),
12809                    ..Default::default()
12810                },
12811                LocalKind::Gamma => LocalParent {
12812                    gamma: Some(3),
12813                    ..Default::default()
12814                },
12815            }
12816        }
12817        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
12818            let mut p = LocalParent::default();
12819            for k in [a, b] {
12820                match k {
12821                    LocalKind::Alpha => p.alpha = Some(1),
12822                    LocalKind::Beta => p.beta = Some(2),
12823                    LocalKind::Gamma => p.gamma = Some(3),
12824                }
12825            }
12826            p
12827        }
12828        assert_has_multiple_missing_kinds_matches_missing_kind_count::<LocalParent, _, _, _>(
12829            single_slot,
12830            two_slot,
12831            LocalParent::default,
12832        );
12833    }
12834
12835    /// The primitive rejects a `two_slot` factory that yields an
12836    /// empty parent (two-slot expects `ALL.len() - 2 == 1` missing
12837    /// on `LocalParent`, whose composition law asserts
12838    /// `has_multiple_missing_kinds() == false`; an empty factory
12839    /// yields `ALL.len() == 3` missing where the primitive returns
12840    /// `true` — the composition law and the trichotomy both drift).
12841    #[test]
12842    #[should_panic]
12843    fn assert_has_multiple_missing_kinds_matches_missing_kind_count_rejects_empty_two_slot_factory()
12844    {
12845        fn single_slot(k: LocalKind) -> LocalParent {
12846            match k {
12847                LocalKind::Alpha => LocalParent {
12848                    alpha: Some(1),
12849                    ..Default::default()
12850                },
12851                LocalKind::Beta => LocalParent {
12852                    beta: Some(2),
12853                    ..Default::default()
12854                },
12855                LocalKind::Gamma => LocalParent {
12856                    gamma: Some(3),
12857                    ..Default::default()
12858                },
12859            }
12860        }
12861        fn empty_two_slot(_: LocalKind, _: LocalKind) -> LocalParent {
12862            // Always yields an empty parent — zero populated, three
12863            // missing. The two-slot invariant is violated.
12864            LocalParent::default()
12865        }
12866        assert_has_multiple_missing_kinds_matches_missing_kind_count::<LocalParent, _, _, _>(
12867            single_slot,
12868            empty_two_slot,
12869            LocalParent::default,
12870        );
12871    }
12872
12873    /// The primitive rejects a `empty_parent` factory that yields a
12874    /// saturated parent (empty baseline expects has_multiple_missing
12875    /// == true on ALL.len() == 3 since 3 missing >= 2).
12876    #[test]
12877    #[should_panic]
12878    fn assert_has_multiple_missing_kinds_matches_missing_kind_count_rejects_saturated_empty_baseline(
12879    ) {
12880        fn single_slot(k: LocalKind) -> LocalParent {
12881            match k {
12882                LocalKind::Alpha => LocalParent {
12883                    alpha: Some(1),
12884                    ..Default::default()
12885                },
12886                LocalKind::Beta => LocalParent {
12887                    beta: Some(2),
12888                    ..Default::default()
12889                },
12890                LocalKind::Gamma => LocalParent {
12891                    gamma: Some(3),
12892                    ..Default::default()
12893                },
12894            }
12895        }
12896        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
12897            let mut p = LocalParent::default();
12898            for k in [a, b] {
12899                match k {
12900                    LocalKind::Alpha => p.alpha = Some(1),
12901                    LocalKind::Beta => p.beta = Some(2),
12902                    LocalKind::Gamma => p.gamma = Some(3),
12903                }
12904            }
12905            p
12906        }
12907        fn saturated_baseline() -> LocalParent {
12908            LocalParent {
12909                alpha: Some(1),
12910                beta: Some(2),
12911                gamma: Some(3),
12912            }
12913        }
12914        assert_has_multiple_missing_kinds_matches_missing_kind_count::<LocalParent, _, _, _>(
12915            single_slot,
12916            two_slot,
12917            saturated_baseline,
12918        );
12919    }
12920
12921    /// Every one of the four production `.variant()` sites on
12922    /// `ProcessSpec` binds through the many-cardinality Boolean
12923    /// primitive on the populated axis coherently — every per-site
12924    /// `single_slot_X(k)` factory produces `has_multiple_populated_kinds()
12925    /// == false`, every `two_slot_X(a, b)` produces `== true`, and
12926    /// `X::default().has_multiple_populated_kinds() == false`. The
12927    /// trichotomy partition law (`is_empty` plus `has_unique_populated_kind`
12928    /// plus `has_multiple_populated_kinds` sums to `1`) is pinned inside
12929    /// the testkit on every arm.
12930    #[test]
12931    fn every_production_tagged_union_binds_through_the_has_multiple_populated_kinds_testkit_primitive(
12932    ) {
12933        assert_has_multiple_populated_kinds_matches_populated_kind_count::<
12934            crate::intent::Intent,
12935            _,
12936            _,
12937            _,
12938        >(
12939            single_slot_intent_probe,
12940            two_slot_intent_probe,
12941            crate::intent::Intent::default,
12942        );
12943        assert_has_multiple_populated_kinds_matches_populated_kind_count::<
12944            crate::encapsulates::EncapsulationKind,
12945            _,
12946            _,
12947            _,
12948        >(
12949            single_slot_encapsulation_kind_probe,
12950            two_slot_encapsulation_kind_probe,
12951            crate::encapsulates::EncapsulationKind::default,
12952        );
12953        assert_has_multiple_populated_kinds_matches_populated_kind_count::<
12954            crate::export::ArtifactSource,
12955            _,
12956            _,
12957            _,
12958        >(
12959            single_slot_artifact_source_probe,
12960            two_slot_artifact_source_probe,
12961            crate::export::ArtifactSource::default,
12962        );
12963        assert_has_multiple_populated_kinds_matches_populated_kind_count::<
12964            crate::export::VectorChannel,
12965            _,
12966            _,
12967            _,
12968        >(
12969            single_slot_vector_channel_probe,
12970            two_slot_vector_channel_probe,
12971            crate::export::VectorChannel::default,
12972        );
12973    }
12974
12975    /// Every one of the four production `.variant()` sites on
12976    /// `ProcessSpec` binds through the many-cardinality Boolean
12977    /// primitive on the missing axis coherently. On `Intent`
12978    /// (`ALL.len() == 6`), `EncapsulationKind` (`>= 3`),
12979    /// `ArtifactSource` (`>= 3`), `VectorChannel` (`>= 3`), the
12980    /// single-slot diagonal returns `true` (`ALL.len() - 1 >= 2`);
12981    /// on `Intent` (`ALL.len() == 6 >= 4`) the two-slot sweep also
12982    /// returns `true`. The trichotomy partition law on the missing
12983    /// axis (`is_saturated + has_unique_missing_kind +
12984    /// has_multiple_missing_kinds == 1`) is pinned inside the testkit
12985    /// on every arm.
12986    #[test]
12987    fn every_production_tagged_union_binds_through_the_has_multiple_missing_kinds_testkit_primitive(
12988    ) {
12989        assert_has_multiple_missing_kinds_matches_missing_kind_count::<
12990            crate::intent::Intent,
12991            _,
12992            _,
12993            _,
12994        >(
12995            single_slot_intent_probe,
12996            two_slot_intent_probe,
12997            crate::intent::Intent::default,
12998        );
12999        assert_has_multiple_missing_kinds_matches_missing_kind_count::<
13000            crate::encapsulates::EncapsulationKind,
13001            _,
13002            _,
13003            _,
13004        >(
13005            single_slot_encapsulation_kind_probe,
13006            two_slot_encapsulation_kind_probe,
13007            crate::encapsulates::EncapsulationKind::default,
13008        );
13009        assert_has_multiple_missing_kinds_matches_missing_kind_count::<
13010            crate::export::ArtifactSource,
13011            _,
13012            _,
13013            _,
13014        >(
13015            single_slot_artifact_source_probe,
13016            two_slot_artifact_source_probe,
13017            crate::export::ArtifactSource::default,
13018        );
13019        assert_has_multiple_missing_kinds_matches_missing_kind_count::<
13020            crate::export::VectorChannel,
13021            _,
13022            _,
13023            _,
13024        >(
13025            single_slot_vector_channel_probe,
13026            two_slot_vector_channel_probe,
13027            crate::export::VectorChannel::default,
13028        );
13029    }
13030
13031    // -------------------------------------------------------------------
13032    // `assert_has_at_most_one_(populated|missing)_kind_matches_(populated|
13033    // missing)_kind_count` — the ≤1-cardinality Boolean testkit
13034    // primitives. Boolean-negation peer of the ≥2 testkits above;
13035    // pin acceptance on the coherent LocalParent scaffold + a
13036    // production sweep binding all four `.variant()` sites through
13037    // the three composition laws (definitional Boolean-negation,
13038    // scalar cardinality, and trichotomy union).
13039    // -------------------------------------------------------------------
13040
13041    /// The `assert_has_at_most_one_populated_kind_matches_populated_kind_count`
13042    /// primitive accepts the [`LocalParent`] scaffold coherently — the
13043    /// coherent-impl side reads `true` on the empty baseline (0 ≤ 1)
13044    /// and every single-slot arrangement (1 ≤ 1), and `false` on every
13045    /// off-diagonal two-slot arrangement (2 > 1). All three composition
13046    /// laws hold on every arm.
13047    #[test]
13048    fn assert_has_at_most_one_populated_kind_matches_populated_kind_count_accepts_coherent_local_impl(
13049    ) {
13050        fn single_slot(k: LocalKind) -> LocalParent {
13051            match k {
13052                LocalKind::Alpha => LocalParent {
13053                    alpha: Some(1),
13054                    ..Default::default()
13055                },
13056                LocalKind::Beta => LocalParent {
13057                    beta: Some(2),
13058                    ..Default::default()
13059                },
13060                LocalKind::Gamma => LocalParent {
13061                    gamma: Some(3),
13062                    ..Default::default()
13063                },
13064            }
13065        }
13066        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13067            let mut p = LocalParent::default();
13068            for k in [a, b] {
13069                match k {
13070                    LocalKind::Alpha => p.alpha = Some(1),
13071                    LocalKind::Beta => p.beta = Some(2),
13072                    LocalKind::Gamma => p.gamma = Some(3),
13073                }
13074            }
13075            p
13076        }
13077        assert_has_at_most_one_populated_kind_matches_populated_kind_count::<LocalParent, _, _, _>(
13078            single_slot,
13079            two_slot,
13080            LocalParent::default,
13081        );
13082    }
13083
13084    /// The primitive rejects a `two_slot` factory that yields a
13085    /// well-formed single-populated parent — the two-slot sweep expects
13086    /// `has_at_most_one_populated_kind() == false` (2 > 1), but a
13087    /// single-slot yields `true` (1 ≤ 1).
13088    #[test]
13089    #[should_panic(expected = "TaggedUnion::has_at_most_one_populated_kind() on two_slot(")]
13090    fn assert_has_at_most_one_populated_kind_matches_populated_kind_count_rejects_single_slot_two_slot_factory(
13091    ) {
13092        fn single_slot(k: LocalKind) -> LocalParent {
13093            match k {
13094                LocalKind::Alpha => LocalParent {
13095                    alpha: Some(1),
13096                    ..Default::default()
13097                },
13098                LocalKind::Beta => LocalParent {
13099                    beta: Some(2),
13100                    ..Default::default()
13101                },
13102                LocalKind::Gamma => LocalParent {
13103                    gamma: Some(3),
13104                    ..Default::default()
13105                },
13106            }
13107        }
13108        fn single_slot_two_slot(a: LocalKind, _b: LocalKind) -> LocalParent {
13109            match a {
13110                LocalKind::Alpha => LocalParent {
13111                    alpha: Some(1),
13112                    ..Default::default()
13113                },
13114                LocalKind::Beta => LocalParent {
13115                    beta: Some(2),
13116                    ..Default::default()
13117                },
13118                LocalKind::Gamma => LocalParent {
13119                    gamma: Some(3),
13120                    ..Default::default()
13121                },
13122            }
13123        }
13124        assert_has_at_most_one_populated_kind_matches_populated_kind_count::<LocalParent, _, _, _>(
13125            single_slot,
13126            single_slot_two_slot,
13127            LocalParent::default,
13128        );
13129    }
13130
13131    /// The `assert_has_at_most_one_missing_kind_matches_missing_kind_count`
13132    /// primitive accepts the [`LocalParent`] scaffold coherently. On
13133    /// `ALL.len() == 3` the missing counts are: empty=3, single_slot=2,
13134    /// two_slot=1, saturated=0. So `has_at_most_one_missing_kind()`
13135    /// reads `false` on empty (3 > 1), `false` on single_slot (2 > 1),
13136    /// `true` on two_slot (1 ≤ 1). All three composition laws hold on
13137    /// every arm.
13138    #[test]
13139    fn assert_has_at_most_one_missing_kind_matches_missing_kind_count_accepts_coherent_local_impl()
13140    {
13141        fn single_slot(k: LocalKind) -> LocalParent {
13142            match k {
13143                LocalKind::Alpha => LocalParent {
13144                    alpha: Some(1),
13145                    ..Default::default()
13146                },
13147                LocalKind::Beta => LocalParent {
13148                    beta: Some(2),
13149                    ..Default::default()
13150                },
13151                LocalKind::Gamma => LocalParent {
13152                    gamma: Some(3),
13153                    ..Default::default()
13154                },
13155            }
13156        }
13157        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13158            let mut p = LocalParent::default();
13159            for k in [a, b] {
13160                match k {
13161                    LocalKind::Alpha => p.alpha = Some(1),
13162                    LocalKind::Beta => p.beta = Some(2),
13163                    LocalKind::Gamma => p.gamma = Some(3),
13164                }
13165            }
13166            p
13167        }
13168        assert_has_at_most_one_missing_kind_matches_missing_kind_count::<LocalParent, _, _, _>(
13169            single_slot,
13170            two_slot,
13171            LocalParent::default,
13172        );
13173    }
13174
13175    /// The primitive rejects a saturated `empty_parent` factory — on
13176    /// `ALL.len() == 3` the baseline expects `has_at_most_one_missing_kind()
13177    /// == false` (all 3 missing on the genuine empty arm), but a
13178    /// saturated factory yields 0 missing → `true`.
13179    #[test]
13180    #[should_panic(
13181        expected = "TaggedUnion::has_at_most_one_missing_kind() on empty_parent() must equal false"
13182    )]
13183    fn assert_has_at_most_one_missing_kind_matches_missing_kind_count_rejects_saturated_empty_baseline(
13184    ) {
13185        fn single_slot(k: LocalKind) -> LocalParent {
13186            match k {
13187                LocalKind::Alpha => LocalParent {
13188                    alpha: Some(1),
13189                    ..Default::default()
13190                },
13191                LocalKind::Beta => LocalParent {
13192                    beta: Some(2),
13193                    ..Default::default()
13194                },
13195                LocalKind::Gamma => LocalParent {
13196                    gamma: Some(3),
13197                    ..Default::default()
13198                },
13199            }
13200        }
13201        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13202            let mut p = LocalParent::default();
13203            for k in [a, b] {
13204                match k {
13205                    LocalKind::Alpha => p.alpha = Some(1),
13206                    LocalKind::Beta => p.beta = Some(2),
13207                    LocalKind::Gamma => p.gamma = Some(3),
13208                }
13209            }
13210            p
13211        }
13212        fn saturated_baseline() -> LocalParent {
13213            LocalParent {
13214                alpha: Some(1),
13215                beta: Some(2),
13216                gamma: Some(3),
13217            }
13218        }
13219        assert_has_at_most_one_missing_kind_matches_missing_kind_count::<LocalParent, _, _, _>(
13220            single_slot,
13221            two_slot,
13222            saturated_baseline,
13223        );
13224    }
13225
13226    /// Every one of the four production `.variant()` sites on
13227    /// `ProcessSpec` binds through the ≤1-populated-cardinality Boolean
13228    /// primitive coherently — every per-site `single_slot_X(k)` factory
13229    /// produces `has_at_most_one_populated_kind() == true` (1 ≤ 1),
13230    /// every `two_slot_X(a, b)` produces `== false` (2 > 1), and
13231    /// `X::default().has_at_most_one_populated_kind() == true` on the
13232    /// empty-parent baseline (0 ≤ 1). All three composition laws
13233    /// (definitional negation, scalar cardinality, trichotomy union)
13234    /// are pinned inside the testkit on every arm.
13235    #[test]
13236    fn every_production_tagged_union_binds_through_the_has_at_most_one_populated_kind_testkit_primitive(
13237    ) {
13238        assert_has_at_most_one_populated_kind_matches_populated_kind_count::<
13239            crate::intent::Intent,
13240            _,
13241            _,
13242            _,
13243        >(
13244            single_slot_intent_probe,
13245            two_slot_intent_probe,
13246            crate::intent::Intent::default,
13247        );
13248        assert_has_at_most_one_populated_kind_matches_populated_kind_count::<
13249            crate::encapsulates::EncapsulationKind,
13250            _,
13251            _,
13252            _,
13253        >(
13254            single_slot_encapsulation_kind_probe,
13255            two_slot_encapsulation_kind_probe,
13256            crate::encapsulates::EncapsulationKind::default,
13257        );
13258        assert_has_at_most_one_populated_kind_matches_populated_kind_count::<
13259            crate::export::ArtifactSource,
13260            _,
13261            _,
13262            _,
13263        >(
13264            single_slot_artifact_source_probe,
13265            two_slot_artifact_source_probe,
13266            crate::export::ArtifactSource::default,
13267        );
13268        assert_has_at_most_one_populated_kind_matches_populated_kind_count::<
13269            crate::export::VectorChannel,
13270            _,
13271            _,
13272            _,
13273        >(
13274            single_slot_vector_channel_probe,
13275            two_slot_vector_channel_probe,
13276            crate::export::VectorChannel::default,
13277        );
13278    }
13279
13280    /// Every one of the four production `.variant()` sites on
13281    /// `ProcessSpec` binds through the ≤1-missing-cardinality Boolean
13282    /// primitive coherently. On `Intent` (`ALL.len() == 6`),
13283    /// `EncapsulationKind` (`>= 3`), `ArtifactSource` (`>= 3`),
13284    /// `VectorChannel` (`>= 3`), the single-slot diagonal returns
13285    /// `false` (`ALL.len() - 1 >= 2`), the two-slot sweep returns
13286    /// `false` on any `ALL.len() >= 4` (Intent) and `true` on
13287    /// `ALL.len() == 3` (the smaller unions have `1 <= 1` missing on
13288    /// the two-slot arm), and the empty baseline returns `false`
13289    /// (`ALL.len() >= 2`).
13290    #[test]
13291    fn every_production_tagged_union_binds_through_the_has_at_most_one_missing_kind_testkit_primitive(
13292    ) {
13293        assert_has_at_most_one_missing_kind_matches_missing_kind_count::<
13294            crate::intent::Intent,
13295            _,
13296            _,
13297            _,
13298        >(
13299            single_slot_intent_probe,
13300            two_slot_intent_probe,
13301            crate::intent::Intent::default,
13302        );
13303        assert_has_at_most_one_missing_kind_matches_missing_kind_count::<
13304            crate::encapsulates::EncapsulationKind,
13305            _,
13306            _,
13307            _,
13308        >(
13309            single_slot_encapsulation_kind_probe,
13310            two_slot_encapsulation_kind_probe,
13311            crate::encapsulates::EncapsulationKind::default,
13312        );
13313        assert_has_at_most_one_missing_kind_matches_missing_kind_count::<
13314            crate::export::ArtifactSource,
13315            _,
13316            _,
13317            _,
13318        >(
13319            single_slot_artifact_source_probe,
13320            two_slot_artifact_source_probe,
13321            crate::export::ArtifactSource::default,
13322        );
13323        assert_has_at_most_one_missing_kind_matches_missing_kind_count::<
13324            crate::export::VectorChannel,
13325            _,
13326            _,
13327            _,
13328        >(
13329            single_slot_vector_channel_probe,
13330            two_slot_vector_channel_probe,
13331            crate::export::VectorChannel::default,
13332        );
13333    }
13334
13335    /// The `assert_is_partially_populated_matches_cardinality` primitive
13336    /// accepts the [`LocalParent`] scaffold coherently — the middle-arm
13337    /// Boolean projection reads `true` on every single-slot and two-slot
13338    /// arrangement (0 < populated < 3) and `false` on the empty
13339    /// baseline (0 populated), and the parent-state trichotomy partition
13340    /// (`is_empty + is_partially_populated + is_saturated == 1`) holds
13341    /// on every arm.
13342    #[test]
13343    fn assert_is_partially_populated_matches_cardinality_accepts_coherent_local_impl() {
13344        fn single_slot(k: LocalKind) -> LocalParent {
13345            match k {
13346                LocalKind::Alpha => LocalParent {
13347                    alpha: Some(1),
13348                    ..Default::default()
13349                },
13350                LocalKind::Beta => LocalParent {
13351                    beta: Some(2),
13352                    ..Default::default()
13353                },
13354                LocalKind::Gamma => LocalParent {
13355                    gamma: Some(3),
13356                    ..Default::default()
13357                },
13358            }
13359        }
13360        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13361            let mut p = LocalParent::default();
13362            for k in [a, b] {
13363                match k {
13364                    LocalKind::Alpha => p.alpha = Some(1),
13365                    LocalKind::Beta => p.beta = Some(2),
13366                    LocalKind::Gamma => p.gamma = Some(3),
13367                }
13368            }
13369            p
13370        }
13371        assert_is_partially_populated_matches_cardinality::<LocalParent, _, _, _>(
13372            single_slot,
13373            two_slot,
13374            LocalParent::default,
13375        );
13376    }
13377
13378    /// The primitive rejects a `single_slot` factory that yields an
13379    /// empty parent (single-slot expects `is_partially_populated() ==
13380    /// true` because on `ALL.len() == 3` a well-formed parent has
13381    /// `1 populated + 2 missing` — but an empty factory yields 0
13382    /// populated, so the middle-arm assertion drifts).
13383    #[test]
13384    #[should_panic(expected = "must equal true")]
13385    fn assert_is_partially_populated_matches_cardinality_rejects_empty_single_slot_factory() {
13386        fn empty_single_slot(_: LocalKind) -> LocalParent {
13387            LocalParent::default()
13388        }
13389        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13390            let mut p = LocalParent::default();
13391            for k in [a, b] {
13392                match k {
13393                    LocalKind::Alpha => p.alpha = Some(1),
13394                    LocalKind::Beta => p.beta = Some(2),
13395                    LocalKind::Gamma => p.gamma = Some(3),
13396                }
13397            }
13398            p
13399        }
13400        assert_is_partially_populated_matches_cardinality::<LocalParent, _, _, _>(
13401            empty_single_slot,
13402            two_slot,
13403            LocalParent::default,
13404        );
13405    }
13406
13407    /// The primitive rejects an `empty_parent` factory that yields a
13408    /// saturated parent (empty baseline expects
13409    /// `is_partially_populated() == false` because 0 populated is the
13410    /// empty arm — a saturated factory has `ALL.len()` populated + 0
13411    /// missing, which is ALSO the `false` arm of the middle Boolean
13412    /// but drifts on the trichotomy partition since
13413    /// `is_saturated == true` while the primitive expected
13414    /// `is_empty == true` on the baseline).
13415    #[test]
13416    #[should_panic]
13417    fn assert_is_partially_populated_matches_cardinality_rejects_saturated_empty_baseline() {
13418        fn single_slot(k: LocalKind) -> LocalParent {
13419            match k {
13420                LocalKind::Alpha => LocalParent {
13421                    alpha: Some(1),
13422                    ..Default::default()
13423                },
13424                LocalKind::Beta => LocalParent {
13425                    beta: Some(2),
13426                    ..Default::default()
13427                },
13428                LocalKind::Gamma => LocalParent {
13429                    gamma: Some(3),
13430                    ..Default::default()
13431                },
13432            }
13433        }
13434        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13435            let mut p = LocalParent::default();
13436            for k in [a, b] {
13437                match k {
13438                    LocalKind::Alpha => p.alpha = Some(1),
13439                    LocalKind::Beta => p.beta = Some(2),
13440                    LocalKind::Gamma => p.gamma = Some(3),
13441                }
13442            }
13443            p
13444        }
13445        fn saturated_baseline() -> LocalParent {
13446            LocalParent {
13447                alpha: Some(1),
13448                beta: Some(2),
13449                gamma: Some(3),
13450            }
13451        }
13452        assert_is_partially_populated_matches_cardinality::<LocalParent, _, _, _>(
13453            single_slot,
13454            two_slot,
13455            saturated_baseline,
13456        );
13457    }
13458
13459    /// Every one of the four production `.variant()` sites on
13460    /// `ProcessSpec` binds through the parent-state-middle-arm Boolean
13461    /// primitive coherently — every per-site `single_slot_X(k)` factory
13462    /// produces `is_partially_populated() == true` (well-formed has
13463    /// `1 populated + ALL.len() - 1 ≥ 1 missing`), every
13464    /// `two_slot_X(a, b)` produces `== true` (`ALL.len() ≥ 3` on every
13465    /// production union so two_slot has `2 populated + ALL.len() - 2
13466    /// ≥ 1 missing`), and `X::default().is_partially_populated() ==
13467    /// false` on the empty-parent baseline. The parent-state
13468    /// trichotomy partition law (`is_empty + is_partially_populated
13469    /// + is_saturated == 1`) is pinned inside the testkit on every arm.
13470    #[test]
13471    fn every_production_tagged_union_binds_through_the_is_partially_populated_testkit_primitive() {
13472        assert_is_partially_populated_matches_cardinality::<crate::intent::Intent, _, _, _>(
13473            single_slot_intent_probe,
13474            two_slot_intent_probe,
13475            crate::intent::Intent::default,
13476        );
13477        assert_is_partially_populated_matches_cardinality::<
13478            crate::encapsulates::EncapsulationKind,
13479            _,
13480            _,
13481            _,
13482        >(
13483            single_slot_encapsulation_kind_probe,
13484            two_slot_encapsulation_kind_probe,
13485            crate::encapsulates::EncapsulationKind::default,
13486        );
13487        assert_is_partially_populated_matches_cardinality::<crate::export::ArtifactSource, _, _, _>(
13488            single_slot_artifact_source_probe,
13489            two_slot_artifact_source_probe,
13490            crate::export::ArtifactSource::default,
13491        );
13492        assert_is_partially_populated_matches_cardinality::<crate::export::VectorChannel, _, _, _>(
13493            single_slot_vector_channel_probe,
13494            two_slot_vector_channel_probe,
13495            crate::export::VectorChannel::default,
13496        );
13497    }
13498
13499    /// The `assert_has_only_matches_unique_populated_kind` primitive
13500    /// accepts the [`LocalParent`] scaffold coherently — the kind-scoped
13501    /// strict-refinement predicate reads `true` iff the probed kind
13502    /// equals the populated kind on every single-slot arrangement (the
13503    /// diagonal), `false` on every off-diagonal pair regardless of
13504    /// probed kind, and `false` on the empty baseline for every kind.
13505    /// The five composition laws (widened uniqueness, cardinality-
13506    /// refinement, kind-scoped implication, kind-domain exhaustivity,
13507    /// well-formed diagonal) hold on every arm.
13508    #[test]
13509    fn assert_has_only_matches_unique_populated_kind_accepts_coherent_local_impl() {
13510        fn single_slot(k: LocalKind) -> LocalParent {
13511            match k {
13512                LocalKind::Alpha => LocalParent {
13513                    alpha: Some(1),
13514                    ..Default::default()
13515                },
13516                LocalKind::Beta => LocalParent {
13517                    beta: Some(2),
13518                    ..Default::default()
13519                },
13520                LocalKind::Gamma => LocalParent {
13521                    gamma: Some(3),
13522                    ..Default::default()
13523                },
13524            }
13525        }
13526        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13527            let mut p = LocalParent::default();
13528            for k in [a, b] {
13529                match k {
13530                    LocalKind::Alpha => p.alpha = Some(1),
13531                    LocalKind::Beta => p.beta = Some(2),
13532                    LocalKind::Gamma => p.gamma = Some(3),
13533                }
13534            }
13535            p
13536        }
13537        assert_has_only_matches_unique_populated_kind::<LocalParent, _, _, _>(
13538            single_slot,
13539            two_slot,
13540            LocalParent::default,
13541        );
13542    }
13543
13544    /// The primitive rejects a `single_slot` factory that populates
13545    /// the WRONG kind (always `Beta` regardless of what kind is asked
13546    /// for) — the well-formed diagonal law
13547    /// `single_slot(k).has_only(k) == true` fails on
13548    /// `k ∈ {Alpha, Gamma}` where the factory populated `Beta` instead.
13549    #[test]
13550    #[should_panic(expected = "must equal true")]
13551    fn assert_has_only_matches_unique_populated_kind_rejects_wrong_slot_factory() {
13552        fn always_beta(_: LocalKind) -> LocalParent {
13553            LocalParent {
13554                beta: Some(2),
13555                ..Default::default()
13556            }
13557        }
13558        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13559            let mut p = LocalParent::default();
13560            for k in [a, b] {
13561                match k {
13562                    LocalKind::Alpha => p.alpha = Some(1),
13563                    LocalKind::Beta => p.beta = Some(2),
13564                    LocalKind::Gamma => p.gamma = Some(3),
13565                }
13566            }
13567            p
13568        }
13569        assert_has_only_matches_unique_populated_kind::<LocalParent, _, _, _>(
13570            always_beta,
13571            two_slot,
13572            LocalParent::default,
13573        );
13574    }
13575
13576    /// The primitive rejects an `empty_parent` factory that yields a
13577    /// saturated parent — the empty-baseline exhaustivity assertion
13578    /// `empty_parent().is_empty() == true` fails on the saturated
13579    /// baseline, catching a factory that mis-represents the empty arm.
13580    #[test]
13581    #[should_panic(expected = "must satisfy is_empty() == true")]
13582    fn assert_has_only_matches_unique_populated_kind_rejects_saturated_empty_baseline() {
13583        fn single_slot(k: LocalKind) -> LocalParent {
13584            match k {
13585                LocalKind::Alpha => LocalParent {
13586                    alpha: Some(1),
13587                    ..Default::default()
13588                },
13589                LocalKind::Beta => LocalParent {
13590                    beta: Some(2),
13591                    ..Default::default()
13592                },
13593                LocalKind::Gamma => LocalParent {
13594                    gamma: Some(3),
13595                    ..Default::default()
13596                },
13597            }
13598        }
13599        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13600            let mut p = LocalParent::default();
13601            for k in [a, b] {
13602                match k {
13603                    LocalKind::Alpha => p.alpha = Some(1),
13604                    LocalKind::Beta => p.beta = Some(2),
13605                    LocalKind::Gamma => p.gamma = Some(3),
13606                }
13607            }
13608            p
13609        }
13610        fn saturated_baseline() -> LocalParent {
13611            LocalParent {
13612                alpha: Some(1),
13613                beta: Some(2),
13614                gamma: Some(3),
13615            }
13616        }
13617        assert_has_only_matches_unique_populated_kind::<LocalParent, _, _, _>(
13618            single_slot,
13619            two_slot,
13620            saturated_baseline,
13621        );
13622    }
13623
13624    /// Every one of the four production `.variant()` sites on
13625    /// `ProcessSpec` binds through the kind-scoped strict-refinement
13626    /// Boolean primitive coherently — every per-site `single_slot_X(k)`
13627    /// factory produces `has_only(k) == true` (well-formed truth table
13628    /// on the diagonal), every off-diagonal probe returns `false`
13629    /// (well-formed truth table off the diagonal), every
13630    /// `two_slot_X(a, b)` produces `has_only(k) == false` for every
13631    /// `k` (multi-populated arm), and `X::default().has_only(k) ==
13632    /// false` on the empty baseline for every `k`. The kind-domain
13633    /// exhaustivity law (`count k where has_only(k) ≤ 1` per parent,
13634    /// with equality iff well-formed) is pinned inside the testkit on
13635    /// every arm.
13636    #[test]
13637    fn every_production_tagged_union_binds_through_the_has_only_testkit_primitive() {
13638        assert_has_only_matches_unique_populated_kind::<crate::intent::Intent, _, _, _>(
13639            single_slot_intent_probe,
13640            two_slot_intent_probe,
13641            crate::intent::Intent::default,
13642        );
13643        assert_has_only_matches_unique_populated_kind::<
13644            crate::encapsulates::EncapsulationKind,
13645            _,
13646            _,
13647            _,
13648        >(
13649            single_slot_encapsulation_kind_probe,
13650            two_slot_encapsulation_kind_probe,
13651            crate::encapsulates::EncapsulationKind::default,
13652        );
13653        assert_has_only_matches_unique_populated_kind::<crate::export::ArtifactSource, _, _, _>(
13654            single_slot_artifact_source_probe,
13655            two_slot_artifact_source_probe,
13656            crate::export::ArtifactSource::default,
13657        );
13658        assert_has_only_matches_unique_populated_kind::<crate::export::VectorChannel, _, _, _>(
13659            single_slot_vector_channel_probe,
13660            two_slot_vector_channel_probe,
13661            crate::export::VectorChannel::default,
13662        );
13663    }
13664
13665    // -------------------------------------------------------------------
13666    // `assert_lacks_only_matches_unique_missing_kind` — the closed-set-
13667    // complement mirror of `assert_has_only_matches_unique_populated_kind`
13668    // on the MISSING axis. Pin the composition-law truth table
13669    // (`lacks_only(kind) == (unique_missing_kind() == Some(kind))`,
13670    // cardinality-refinement under complement, kind-scoped implication
13671    // under complement, kind-domain exhaustivity ≤ 1) directly on the
13672    // sibling-shaped `LocalParent` scaffold + on every one of the four
13673    // production `.variant()` parents — a regression on either the fused
13674    // walk's negated presence probe, the argument-scoped short-circuit,
13675    // or the exhaustivity partition fails here before any per-parent
13676    // consumer surfaces the drift.
13677    // -------------------------------------------------------------------
13678
13679    /// The `assert_lacks_only_matches_unique_missing_kind` primitive
13680    /// accepts the [`LocalParent`] scaffold coherently — the closed-set-
13681    /// complement mirror of the populated-axis kind-scoped strict-
13682    /// refinement predicate reads `true` iff the probed kind names the
13683    /// SOLE missing slot. On `LocalParent`'s `ALL.len() == 3` closed
13684    /// set: the empty baseline has 3 missing (so `lacks_only(k) ==
13685    /// false` for every `k`), every single-slot arm has 2 missing (so
13686    /// `lacks_only(k) == false` for every `k`), and every off-diagonal
13687    /// two-slot arm has 1 missing — the third kind, where `lacks_only`
13688    /// returns `true` for that one probe and `false` for the two
13689    /// populated probes. The four composition laws (widened
13690    /// uniqueness, cardinality-refinement under complement, kind-
13691    /// scoped implication under complement, kind-domain exhaustivity)
13692    /// hold on every arm.
13693    #[test]
13694    fn assert_lacks_only_matches_unique_missing_kind_accepts_coherent_local_impl() {
13695        fn single_slot(k: LocalKind) -> LocalParent {
13696            match k {
13697                LocalKind::Alpha => LocalParent {
13698                    alpha: Some(1),
13699                    ..Default::default()
13700                },
13701                LocalKind::Beta => LocalParent {
13702                    beta: Some(2),
13703                    ..Default::default()
13704                },
13705                LocalKind::Gamma => LocalParent {
13706                    gamma: Some(3),
13707                    ..Default::default()
13708                },
13709            }
13710        }
13711        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13712            let mut p = LocalParent::default();
13713            for k in [a, b] {
13714                match k {
13715                    LocalKind::Alpha => p.alpha = Some(1),
13716                    LocalKind::Beta => p.beta = Some(2),
13717                    LocalKind::Gamma => p.gamma = Some(3),
13718                }
13719            }
13720            p
13721        }
13722        assert_lacks_only_matches_unique_missing_kind::<LocalParent, _, _, _>(
13723            single_slot,
13724            two_slot,
13725            LocalParent::default,
13726        );
13727    }
13728
13729    /// The primitive rejects a `two_slot` factory that yields a
13730    /// saturated parent (all three slots populated, zero missing) —
13731    /// the factory-precondition truth table on the two-slot arm reads
13732    /// `expected == (k != a && k != b)` for the third kind on
13733    /// `ALL.len() == 3`, but the saturated factory has zero missing so
13734    /// `lacks_only(third) == false` where `expected == true`. Caught
13735    /// by the hard-coded arm expectation BEFORE any composition law
13736    /// reconciles two internally-drifted trait bodies.
13737    #[test]
13738    #[should_panic(expected = "must equal true on ALL.len() == 3")]
13739    fn assert_lacks_only_matches_unique_missing_kind_rejects_saturated_two_slot_factory() {
13740        fn single_slot(k: LocalKind) -> LocalParent {
13741            match k {
13742                LocalKind::Alpha => LocalParent {
13743                    alpha: Some(1),
13744                    ..Default::default()
13745                },
13746                LocalKind::Beta => LocalParent {
13747                    beta: Some(2),
13748                    ..Default::default()
13749                },
13750                LocalKind::Gamma => LocalParent {
13751                    gamma: Some(3),
13752                    ..Default::default()
13753                },
13754            }
13755        }
13756        fn saturated_two_slot(_: LocalKind, _: LocalKind) -> LocalParent {
13757            // Always yields a saturated parent — zero missing.
13758            LocalParent {
13759                alpha: Some(1),
13760                beta: Some(2),
13761                gamma: Some(3),
13762            }
13763        }
13764        assert_lacks_only_matches_unique_missing_kind::<LocalParent, _, _, _>(
13765            single_slot,
13766            saturated_two_slot,
13767            LocalParent::default,
13768        );
13769    }
13770
13771    /// The primitive rejects a `empty_parent` factory that yields a
13772    /// saturated parent — the empty-baseline exhaustivity assertion
13773    /// `empty_parent().is_empty() == true` fails on the saturated
13774    /// baseline, catching a factory that mis-represents the empty arm.
13775    #[test]
13776    #[should_panic(expected = "must satisfy is_empty() == true")]
13777    fn assert_lacks_only_matches_unique_missing_kind_rejects_saturated_empty_baseline() {
13778        fn single_slot(k: LocalKind) -> LocalParent {
13779            match k {
13780                LocalKind::Alpha => LocalParent {
13781                    alpha: Some(1),
13782                    ..Default::default()
13783                },
13784                LocalKind::Beta => LocalParent {
13785                    beta: Some(2),
13786                    ..Default::default()
13787                },
13788                LocalKind::Gamma => LocalParent {
13789                    gamma: Some(3),
13790                    ..Default::default()
13791                },
13792            }
13793        }
13794        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13795            let mut p = LocalParent::default();
13796            for k in [a, b] {
13797                match k {
13798                    LocalKind::Alpha => p.alpha = Some(1),
13799                    LocalKind::Beta => p.beta = Some(2),
13800                    LocalKind::Gamma => p.gamma = Some(3),
13801                }
13802            }
13803            p
13804        }
13805        fn saturated_baseline() -> LocalParent {
13806            LocalParent {
13807                alpha: Some(1),
13808                beta: Some(2),
13809                gamma: Some(3),
13810            }
13811        }
13812        assert_lacks_only_matches_unique_missing_kind::<LocalParent, _, _, _>(
13813            single_slot,
13814            two_slot,
13815            saturated_baseline,
13816        );
13817    }
13818
13819    /// Every one of the four production `.variant()` sites on
13820    /// `ProcessSpec` binds through the kind-scoped strict-refinement
13821    /// Boolean primitive on the MISSING axis coherently — on the
13822    /// three `ALL.len() == 3` sites (`EncapsulationKind`,
13823    /// `ArtifactSource`, `VectorChannel`) every off-diagonal
13824    /// `two_slot_X(a, b)` produces `lacks_only(third) == true` for
13825    /// exactly the third kind and `lacks_only(k) == false` for the
13826    /// two populated kinds; on the `ALL.len() == 6` site (`Intent`)
13827    /// every off-diagonal two-slot arm has 4 missing so `lacks_only(k)
13828    /// == false` for every `k`. Every single-slot arm on every site
13829    /// has `ALL.len() - 1 >= 2` missing, so `lacks_only(k) == false`
13830    /// for every `k`. The `X::default()` empty baseline on every site
13831    /// has `ALL.len() >= 3` missing, so `lacks_only(k) == false` for
13832    /// every `k`. The composition-law shape binds every regime
13833    /// through the same substrate site. The kind-domain exhaustivity
13834    /// law (`count k where lacks_only(k) ≤ 1` per parent, with
13835    /// equality iff exactly one slot is missing) is pinned inside the
13836    /// testkit on every arm.
13837    #[test]
13838    fn every_production_tagged_union_binds_through_the_lacks_only_testkit_primitive() {
13839        assert_lacks_only_matches_unique_missing_kind::<crate::intent::Intent, _, _, _>(
13840            single_slot_intent_probe,
13841            two_slot_intent_probe,
13842            crate::intent::Intent::default,
13843        );
13844        assert_lacks_only_matches_unique_missing_kind::<
13845            crate::encapsulates::EncapsulationKind,
13846            _,
13847            _,
13848            _,
13849        >(
13850            single_slot_encapsulation_kind_probe,
13851            two_slot_encapsulation_kind_probe,
13852            crate::encapsulates::EncapsulationKind::default,
13853        );
13854        assert_lacks_only_matches_unique_missing_kind::<crate::export::ArtifactSource, _, _, _>(
13855            single_slot_artifact_source_probe,
13856            two_slot_artifact_source_probe,
13857            crate::export::ArtifactSource::default,
13858        );
13859        assert_lacks_only_matches_unique_missing_kind::<crate::export::VectorChannel, _, _, _>(
13860            single_slot_vector_channel_probe,
13861            two_slot_vector_channel_probe,
13862            crate::export::VectorChannel::default,
13863        );
13864    }
13865
13866    // -------------------------------------------------------------------
13867    // `assert_lacks_matches_has_complement` — the missing-axis SUBSET
13868    // primitive testkit. Pin the composition-law truth table
13869    // (definitional complement, missing-set membership, kind-scoped
13870    // implication from lacks_only, cardinality partition against
13871    // missing_kind_count, factory-precondition arm expectation) directly
13872    // on the sibling-shaped `LocalParent` scaffold + on every one of the
13873    // four production `.variant()` parents — a regression on either the
13874    // definitional negation, the missing-set membership projection, or
13875    // the cardinality partition fails here before any per-parent
13876    // consumer surfaces the drift.
13877    // -------------------------------------------------------------------
13878
13879    /// The `assert_lacks_matches_has_complement` primitive accepts the
13880    /// [`LocalParent`] scaffold coherently — the closed-set-complement
13881    /// peer of the kind-scoped SUBSET populated-axis predicate reads
13882    /// `true` iff the probed kind is missing. On `LocalParent`'s
13883    /// `ALL.len() == 3` closed set: the empty baseline has 3 missing
13884    /// (so `lacks(k) == true` for every `k`), every single-slot arm
13885    /// has 2 missing (so `lacks(k) == true` for every `k != populated`
13886    /// and `false` for `k == populated`), and every off-diagonal
13887    /// two-slot arm has 1 missing (so `lacks(k) == true` for the third
13888    /// kind and `false` for the two populated kinds). The five
13889    /// composition laws (definitional complement, missing-set
13890    /// membership, kind-scoped implication from lacks_only,
13891    /// cardinality partition against missing_kind_count, factory-
13892    /// precondition arm expectation) hold on every arm.
13893    #[test]
13894    fn assert_lacks_matches_has_complement_accepts_coherent_local_impl() {
13895        fn single_slot(k: LocalKind) -> LocalParent {
13896            match k {
13897                LocalKind::Alpha => LocalParent {
13898                    alpha: Some(1),
13899                    ..Default::default()
13900                },
13901                LocalKind::Beta => LocalParent {
13902                    beta: Some(2),
13903                    ..Default::default()
13904                },
13905                LocalKind::Gamma => LocalParent {
13906                    gamma: Some(3),
13907                    ..Default::default()
13908                },
13909            }
13910        }
13911        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13912            let mut p = LocalParent::default();
13913            for k in [a, b] {
13914                match k {
13915                    LocalKind::Alpha => p.alpha = Some(1),
13916                    LocalKind::Beta => p.beta = Some(2),
13917                    LocalKind::Gamma => p.gamma = Some(3),
13918                }
13919            }
13920            p
13921        }
13922        assert_lacks_matches_has_complement::<LocalParent, _, _, _>(
13923            single_slot,
13924            two_slot,
13925            LocalParent::default,
13926        );
13927    }
13928
13929    /// The primitive rejects a `single_slot` factory that yields a
13930    /// saturated parent (all three slots populated, zero missing) —
13931    /// the factory-precondition truth table on the well-formed
13932    /// single-slot arm reads `expected == (probed != populated)`, but
13933    /// the saturated factory has zero missing so `lacks(probed) ==
13934    /// false` for EVERY probe, mismatching the `true` expectation
13935    /// on every off-diagonal probe. Caught by the hard-coded arm
13936    /// expectation BEFORE the definitional complement law reconciles
13937    /// two internally-drifted trait bodies.
13938    #[test]
13939    #[should_panic(expected = "must equal true")]
13940    fn assert_lacks_matches_has_complement_rejects_saturated_single_slot_factory() {
13941        fn saturated_single_slot(_: LocalKind) -> LocalParent {
13942            LocalParent {
13943                alpha: Some(1),
13944                beta: Some(2),
13945                gamma: Some(3),
13946            }
13947        }
13948        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13949            let mut p = LocalParent::default();
13950            for k in [a, b] {
13951                match k {
13952                    LocalKind::Alpha => p.alpha = Some(1),
13953                    LocalKind::Beta => p.beta = Some(2),
13954                    LocalKind::Gamma => p.gamma = Some(3),
13955                }
13956            }
13957            p
13958        }
13959        assert_lacks_matches_has_complement::<LocalParent, _, _, _>(
13960            saturated_single_slot,
13961            two_slot,
13962            LocalParent::default,
13963        );
13964    }
13965
13966    /// The primitive rejects an `empty_parent` factory that yields a
13967    /// saturated parent — the empty-baseline exhaustivity assertion
13968    /// `empty_parent().is_empty() == true` fails on the saturated
13969    /// baseline, catching a factory that mis-represents the empty arm
13970    /// BEFORE any composition law reconciles two internally-drifted
13971    /// trait bodies.
13972    #[test]
13973    #[should_panic(expected = "must satisfy is_empty() == true")]
13974    fn assert_lacks_matches_has_complement_rejects_saturated_empty_baseline() {
13975        fn single_slot(k: LocalKind) -> LocalParent {
13976            match k {
13977                LocalKind::Alpha => LocalParent {
13978                    alpha: Some(1),
13979                    ..Default::default()
13980                },
13981                LocalKind::Beta => LocalParent {
13982                    beta: Some(2),
13983                    ..Default::default()
13984                },
13985                LocalKind::Gamma => LocalParent {
13986                    gamma: Some(3),
13987                    ..Default::default()
13988                },
13989            }
13990        }
13991        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
13992            let mut p = LocalParent::default();
13993            for k in [a, b] {
13994                match k {
13995                    LocalKind::Alpha => p.alpha = Some(1),
13996                    LocalKind::Beta => p.beta = Some(2),
13997                    LocalKind::Gamma => p.gamma = Some(3),
13998                }
13999            }
14000            p
14001        }
14002        fn saturated_baseline() -> LocalParent {
14003            LocalParent {
14004                alpha: Some(1),
14005                beta: Some(2),
14006                gamma: Some(3),
14007            }
14008        }
14009        assert_lacks_matches_has_complement::<LocalParent, _, _, _>(
14010            single_slot,
14011            two_slot,
14012            saturated_baseline,
14013        );
14014    }
14015
14016    /// Every one of the four production `.variant()` sites on
14017    /// `ProcessSpec` binds through the closed-set-complement peer of
14018    /// `has` on the kind-scoped SUBSET axis coherently — every
14019    /// `single_slot_X(k)` factory produces `lacks(k) == false` on the
14020    /// diagonal and `lacks(other) == true` off-diagonal, every
14021    /// `two_slot_X(a, b)` produces `lacks(k) == true` iff `k != a && k
14022    /// != b`, and `X::default().lacks(k) == true` on the empty
14023    /// baseline for every `k`. The cardinality-partition law (`count k
14024    /// where lacks(k) == missing_kind_count()` per parent) is pinned
14025    /// inside the testkit on every arm.
14026    #[test]
14027    fn every_production_tagged_union_binds_through_the_lacks_testkit_primitive() {
14028        assert_lacks_matches_has_complement::<crate::intent::Intent, _, _, _>(
14029            single_slot_intent_probe,
14030            two_slot_intent_probe,
14031            crate::intent::Intent::default,
14032        );
14033        assert_lacks_matches_has_complement::<crate::encapsulates::EncapsulationKind, _, _, _>(
14034            single_slot_encapsulation_kind_probe,
14035            two_slot_encapsulation_kind_probe,
14036            crate::encapsulates::EncapsulationKind::default,
14037        );
14038        assert_lacks_matches_has_complement::<crate::export::ArtifactSource, _, _, _>(
14039            single_slot_artifact_source_probe,
14040            two_slot_artifact_source_probe,
14041            crate::export::ArtifactSource::default,
14042        );
14043        assert_lacks_matches_has_complement::<crate::export::VectorChannel, _, _, _>(
14044            single_slot_vector_channel_probe,
14045            two_slot_vector_channel_probe,
14046            crate::export::VectorChannel::default,
14047        );
14048    }
14049
14050    // -------------------------------------------------------------------
14051    // `assert_two_slots_ambiguous` — the ALL×ALL ambiguity sweep as ONE
14052    // substrate primitive. Pin the truth table (every off-diagonal pair
14053    // resolves to `TaggedUnionError::ambiguous`, diagonal pairs are
14054    // skipped, a factory that yields a non-Ambiguous parent fails-loudly
14055    // at the caller's site) directly on the sibling-shaped `LocalParent`
14056    // scaffold — a regression on either the pair-iteration order or the
14057    // expected-carrier composition fails here before any per-parent test
14058    // surfaces the drift.
14059    // -------------------------------------------------------------------
14060
14061    /// Every off-diagonal pair across [`LocalKind::ALL`] × `ALL`
14062    /// resolves through the substrate primitive to
14063    /// [`LocalParentError::Ambiguous`] on the sibling-shaped local
14064    /// scaffold. Pins the primitive's Ok arm (no false positives on the
14065    /// coherent-impl side) at ONE boundary — a regression that drops
14066    /// the diagonal skip, mis-iterates `ClosedSet::ALL`, or composes a
14067    /// divergent expected carrier fails here before any per-parent
14068    /// inherent test surfaces the drift.
14069    #[test]
14070    fn assert_two_slots_ambiguous_accepts_coherent_local_impl() {
14071        fn two_local(a: LocalKind, b: LocalKind) -> LocalParent {
14072            let mut p = LocalParent::default();
14073            for k in [a, b] {
14074                match k {
14075                    LocalKind::Alpha => p.alpha = Some(11),
14076                    LocalKind::Beta => p.beta = Some(22),
14077                    LocalKind::Gamma => p.gamma = Some(33),
14078                }
14079            }
14080            p
14081        }
14082        assert_two_slots_ambiguous::<LocalParent, _>(two_local);
14083    }
14084
14085    /// A factory that yields a single-slot parent for the FIRST kind
14086    /// (ignoring the second) — every off-diagonal pair resolves to
14087    /// exactly-one Ok(Variant), NOT Ambiguous — MUST fail-loudly at
14088    /// the caller's site through the primitive's "two-slot parent
14089    /// must not resolve to a variant" arm. Pin the Ok-side failure
14090    /// mode so a regression that mis-routes the substrate primitive's
14091    /// resolved-Ok arm past the assertion (silently succeeding on a
14092    /// single-slot factory) is caught here.
14093    #[test]
14094    #[should_panic(expected = "two-slot parent must not resolve to a variant")]
14095    fn assert_two_slots_ambiguous_rejects_factory_that_populates_only_one_slot() {
14096        fn single_only(a: LocalKind, _: LocalKind) -> LocalParent {
14097            let mut p = LocalParent::default();
14098            match a {
14099                LocalKind::Alpha => p.alpha = Some(11),
14100                LocalKind::Beta => p.beta = Some(22),
14101                LocalKind::Gamma => p.gamma = Some(33),
14102            }
14103            p
14104        }
14105        assert_two_slots_ambiguous::<LocalParent, _>(single_only);
14106    }
14107
14108    /// A factory that yields an all-empty parent (so `.variant()`
14109    /// resolves to the `Empty` carrier, NOT `Ambiguous`) MUST
14110    /// fail-loudly at the caller's site through the primitive's
14111    /// `assert_eq!` arm — the composed expected carrier
14112    /// [`TaggedUnionError::ambiguous`] mismatches the resolved
14113    /// [`TaggedUnionError::empty`] carrier. Pin the Empty-arm failure
14114    /// mode so a regression that mis-projects the None arm of
14115    /// [`ResolveError`] onto Ambiguous (silently succeeding on an
14116    /// empty factory) is caught here.
14117    #[test]
14118    #[should_panic(expected = "should resolve Ambiguous")]
14119    fn assert_two_slots_ambiguous_rejects_factory_that_populates_no_slots() {
14120        fn empty_factory(_: LocalKind, _: LocalKind) -> LocalParent {
14121            LocalParent::default()
14122        }
14123        assert_two_slots_ambiguous::<LocalParent, _>(empty_factory);
14124    }
14125
14126    // -------------------------------------------------------------------
14127    // `assert_single_slot_key_matches_label` — the wire-key / kind-label
14128    // alignment sweep as ONE substrate primitive. Pin the truth table
14129    // (every populated slot serializes to exactly one JSON key whose
14130    // name equals the addressing kind's ClosedSet label; a factory that
14131    // populates the wrong slot / no slot / multiple slots fails-loudly
14132    // at the caller's site) directly on the sibling-shaped `LocalParent`
14133    // scaffold — a regression on either the exactly-one arm or the
14134    // name-equality arm fails here before any per-parent inherent test
14135    // surfaces the drift.
14136    // -------------------------------------------------------------------
14137
14138    /// Every kind across [`LocalKind::ALL`] serializes through the
14139    /// substrate primitive to a JSON object with EXACTLY ONE key whose
14140    /// name equals `<LocalKind as ClosedSet>::label` on the addressed
14141    /// kind. Pins the primitive's Ok arm (no false positives on the
14142    /// coherent-impl side) at ONE boundary — a regression that inspects
14143    /// the wrong serde value (e.g. `to_string` instead of `to_value`),
14144    /// counts fields off-by-one, or projects the wrong `ClosedSet`
14145    /// method (`labels_joined` instead of `label`) fails here before any
14146    /// per-parent inherent test surfaces the drift.
14147    #[test]
14148    fn assert_single_slot_key_matches_label_accepts_coherent_local_impl() {
14149        fn make_local(k: LocalKind) -> LocalParent {
14150            match k {
14151                LocalKind::Alpha => LocalParent {
14152                    alpha: Some(11),
14153                    ..Default::default()
14154                },
14155                LocalKind::Beta => LocalParent {
14156                    beta: Some(22),
14157                    ..Default::default()
14158                },
14159                LocalKind::Gamma => LocalParent {
14160                    gamma: Some(33),
14161                    ..Default::default()
14162                },
14163            }
14164        }
14165        assert_single_slot_key_matches_label::<LocalParent, _>(make_local);
14166    }
14167
14168    /// A factory that returns a single-slot parent for the WRONG kind
14169    /// (populates `beta` regardless of what kind is asked for) MUST
14170    /// fail-loudly at the caller's site through the primitive's
14171    /// name-equality arm — the emitted key does not match the addressed
14172    /// kind's label. Pins the drift-detection failure mode so a
14173    /// regression that drops the `assert_eq!(keys[0], label)` arm
14174    /// (silently succeeding on any-key-at-all) is caught here. The
14175    /// caller's site is the `#[should_panic]` boundary through the
14176    /// primitive's `#[track_caller]` compound-lift.
14177    #[test]
14178    #[should_panic(expected = "wire-key drift")]
14179    fn assert_single_slot_key_matches_label_rejects_factory_that_populates_wrong_slot() {
14180        fn always_beta(_: LocalKind) -> LocalParent {
14181            LocalParent {
14182                beta: Some(22),
14183                ..Default::default()
14184            }
14185        }
14186        assert_single_slot_key_matches_label::<LocalParent, _>(always_beta);
14187    }
14188
14189    /// A factory that returns an all-empty parent (so serializing
14190    /// yields ZERO keys, not exactly-one) MUST fail-loudly at the
14191    /// caller's site through the primitive's exactly-one arm. Pins the
14192    /// zero-key failure mode so a regression that projects
14193    /// `obj.keys().count() >= 1` (rather than `== 1`) is caught here.
14194    #[test]
14195    #[should_panic(expected = "exactly one populated field")]
14196    fn assert_single_slot_key_matches_label_rejects_factory_that_populates_no_slots() {
14197        fn empty_factory(_: LocalKind) -> LocalParent {
14198            LocalParent::default()
14199        }
14200        assert_single_slot_key_matches_label::<LocalParent, _>(empty_factory);
14201    }
14202
14203    /// A factory that returns a parent with TWO populated slots (so
14204    /// serializing yields two keys, not exactly-one) MUST fail-loudly
14205    /// at the caller's site through the primitive's exactly-one arm.
14206    /// Pins the many-keys failure mode so a regression that projects
14207    /// `obj.keys().count() <= 1` (rather than `== 1`) is caught here.
14208    /// Cross-pins the substrate promise that a single-slot factory
14209    /// truly populates ONE slot — a future factory bug that leaks
14210    /// residual populated slots between calls (e.g. via shared mutable
14211    /// state) is caught HERE at the primitive boundary.
14212    #[test]
14213    #[should_panic(expected = "exactly one populated field")]
14214    fn assert_single_slot_key_matches_label_rejects_factory_that_populates_two_slots() {
14215        fn two_slot_factory(_: LocalKind) -> LocalParent {
14216            LocalParent {
14217                alpha: Some(1),
14218                beta: Some(2),
14219                gamma: None,
14220            }
14221        }
14222        assert_single_slot_key_matches_label::<LocalParent, _>(two_slot_factory);
14223    }
14224
14225    /// The macro-emitted [`MacroLocalParent`] scaffold impls
14226    /// [`TaggedUnion`] through the [`declare_tagged_union_impls!`]
14227    /// three-block macro AND additionally derives `serde::Serialize` +
14228    /// `#[serde(skip_serializing_if = "Option::is_none")]` on every
14229    /// slot — so the wire-key primitive dispatches on the MACRO-emitted
14230    /// impl path byte-identically with the hand-rolled [`LocalParent`]
14231    /// path above. Pins the substrate-wide guarantee that a fifth
14232    /// sibling landing through the macro picks up the wire-alignment
14233    /// check for free, without a hand-rolled `TaggedUnion` block, so
14234    /// long as its serde derives match the substrate-wide
14235    /// `skip_serializing_if = "Option::is_none"` shape every production
14236    /// site already carries. A regression that mis-routes the
14237    /// primitive's serialize call through the WRONG entry point (e.g.
14238    /// calling a bespoke `to_json` that bypasses serde) is caught here.
14239    #[test]
14240    fn assert_single_slot_key_matches_label_accepts_macro_emitted_impl() {
14241        fn make_macro_local(k: MacroLocalKind) -> MacroLocalParent {
14242            match k {
14243                MacroLocalKind::Foo => MacroLocalParent {
14244                    foo: Some(7),
14245                    bar: None,
14246                },
14247                MacroLocalKind::Bar => MacroLocalParent {
14248                    foo: None,
14249                    bar: Some(8),
14250                },
14251            }
14252        }
14253        assert_single_slot_key_matches_label::<MacroLocalParent, _>(make_macro_local);
14254    }
14255
14256    // -------------------------------------------------------------------
14257    // `assert_wire_key_matches_label` — bound-relaxed peer of the
14258    // `assert_single_slot_key_matches_label` primitive. Pin the truth
14259    // table (every populated slot serializes to exactly one JSON key
14260    // whose name equals the addressing kind's ClosedSet label; a
14261    // factory that populates the wrong slot / no slot / multiple slots
14262    // fails-loudly at the caller's site) on a NON-TaggedUnion parent
14263    // scaffold — the delegation-only path from the trait-projected
14264    // primitive would silently pass this test if the bound-relaxed
14265    // primitive's body regressed, so the direct-dispatch probes here
14266    // pin the bound-relaxed pathway independently.
14267    // -------------------------------------------------------------------
14268
14269    /// Local parent that carries the wire-format shape (`Option<T>`
14270    /// slots + `#[serde(skip_serializing_if = "Option::is_none")]`
14271    /// annotations) but DELIBERATELY does NOT impl [`TaggedUnion`] —
14272    /// pins the bound-relaxed sweep on the exact shape [`crate::lifetime::Lifetime`]
14273    /// carries in production (empty resolves to a default variant,
14274    /// not to a typed error, so the trait's `T::Error` bound doesn't
14275    /// hold and the trait-projected surface excludes it).
14276    #[derive(Default, serde::Serialize)]
14277    struct BareParent {
14278        #[serde(skip_serializing_if = "Option::is_none")]
14279        alpha: Option<u32>,
14280        #[serde(skip_serializing_if = "Option::is_none")]
14281        beta: Option<u32>,
14282        #[serde(skip_serializing_if = "Option::is_none")]
14283        gamma: Option<u32>,
14284    }
14285
14286    /// The bound-relaxed primitive dispatches Ok on a coherent
14287    /// non-TaggedUnion impl — pin the happy path directly on the
14288    /// [`BareParent`] scaffold so a regression that gates the sweep
14289    /// body on the `T: TaggedUnion` bound (accidentally re-adding it,
14290    /// or projecting through `T::Kind` instead of the caller-supplied
14291    /// `K` generic) fails HERE at the primitive-independent boundary
14292    /// rather than at the [`crate::lifetime::Lifetime`] production
14293    /// site alone. The Ok arm is the "no drift" outcome; a divergence
14294    /// surfaces as a labeled assertion failure at the caller site
14295    /// (this test's own line) via the primitive's `#[track_caller]`.
14296    #[test]
14297    fn assert_wire_key_matches_label_accepts_coherent_bare_parent_impl() {
14298        fn make_bare(k: LocalKind) -> BareParent {
14299            match k {
14300                LocalKind::Alpha => BareParent {
14301                    alpha: Some(11),
14302                    ..Default::default()
14303                },
14304                LocalKind::Beta => BareParent {
14305                    beta: Some(22),
14306                    ..Default::default()
14307                },
14308                LocalKind::Gamma => BareParent {
14309                    gamma: Some(33),
14310                    ..Default::default()
14311                },
14312            }
14313        }
14314        assert_wire_key_matches_label::<BareParent, LocalKind, _>(make_bare);
14315    }
14316
14317    /// A factory that returns a bare-parent for the WRONG kind
14318    /// (populates `beta` regardless of what kind is asked for) MUST
14319    /// fail-loudly at the caller's site through the bound-relaxed
14320    /// primitive's name-equality arm — the emitted key does not match
14321    /// the addressed kind's label. Pins the drift-detection failure
14322    /// mode on the non-TaggedUnion pathway so a regression that drops
14323    /// the `assert_eq!(keys[0], label)` arm (silently succeeding on
14324    /// any-key-at-all) is caught here — mechanical peer of the
14325    /// sibling `assert_single_slot_key_matches_label_rejects_factory_that_populates_wrong_slot`
14326    /// on the TaggedUnion pathway.
14327    #[test]
14328    #[should_panic(expected = "wire-key drift")]
14329    fn assert_wire_key_matches_label_rejects_factory_that_populates_wrong_slot() {
14330        fn always_beta(_: LocalKind) -> BareParent {
14331            BareParent {
14332                beta: Some(22),
14333                ..Default::default()
14334            }
14335        }
14336        assert_wire_key_matches_label::<BareParent, LocalKind, _>(always_beta);
14337    }
14338
14339    /// A factory that returns an all-empty bare-parent (so serializing
14340    /// yields ZERO keys, not exactly-one) MUST fail-loudly at the
14341    /// caller's site through the bound-relaxed primitive's
14342    /// exactly-one arm. Pins the zero-key failure mode on the
14343    /// non-TaggedUnion pathway.
14344    #[test]
14345    #[should_panic(expected = "exactly one populated field")]
14346    fn assert_wire_key_matches_label_rejects_factory_that_populates_no_slots() {
14347        fn empty_factory(_: LocalKind) -> BareParent {
14348            BareParent::default()
14349        }
14350        assert_wire_key_matches_label::<BareParent, LocalKind, _>(empty_factory);
14351    }
14352
14353    /// The trait-projected [`assert_single_slot_key_matches_label`]
14354    /// is a one-line delegation to the bound-relaxed
14355    /// [`assert_wire_key_matches_label`] peer — pin the delegation
14356    /// shape at ONE boundary so a regression that inlines a
14357    /// divergent sweep body into the trait-projected surface (rather
14358    /// than the one-line dispatch) is caught here. Ok on a coherent
14359    /// impl means BOTH primitives dispatch through the SAME body on
14360    /// the same fixture — [`LocalParent`] impls [`TaggedUnion`], so
14361    /// both the trait-projected surface and the bound-relaxed peer
14362    /// reach it, and a divergence between the two dispatches would
14363    /// surface here as one succeeding + the other failing.
14364    #[test]
14365    fn assert_single_slot_key_matches_label_delegates_to_wire_key_matches_label() {
14366        fn make_local(k: LocalKind) -> LocalParent {
14367            match k {
14368                LocalKind::Alpha => LocalParent {
14369                    alpha: Some(11),
14370                    ..Default::default()
14371                },
14372                LocalKind::Beta => LocalParent {
14373                    beta: Some(22),
14374                    ..Default::default()
14375                },
14376                LocalKind::Gamma => LocalParent {
14377                    gamma: Some(33),
14378                    ..Default::default()
14379                },
14380            }
14381        }
14382        // Both surfaces reach the same body — dispatched here through
14383        // BOTH entry points so a divergence between them fails one
14384        // arm while the other passes.
14385        assert_single_slot_key_matches_label::<LocalParent, _>(make_local);
14386        assert_wire_key_matches_label::<LocalParent, LocalKind, _>(make_local);
14387    }
14388
14389    /// Every one of the five production borrowed-view enums impls
14390    /// [`VariantKind`] byte-identically with its inherent `.kind()`
14391    /// (or `.target()` on `EncapsulationKindVariant`) — pin the
14392    /// delegation shape at ONE substrate boundary so a regression that
14393    /// inlines a divergent match body into the trait impl (rather than
14394    /// the one-line delegation) is caught here. `Lifetime`'s
14395    /// borrowed-view is included even though `Lifetime` isn't a
14396    /// [`TaggedUnion`] impl — the reverse projection applies uniformly.
14397    #[test]
14398    fn every_production_variant_kind_impl_matches_inherent_projection() {
14399        use crate::encapsulates::{EncapsulationKindVariant, ExistingHelmRelease};
14400        use crate::export::{ArtifactVariant, ChannelVariant, HttpEventChannel, ReceiptsSource};
14401        use crate::intent::{IntentVariant, NixIntent};
14402        use crate::lifetime::{LifetimeVariant, PermanentLifetime};
14403
14404        let nix = NixIntent {
14405            flake_ref: "github:a/b".into(),
14406            attribute: "x".into(),
14407            system: None,
14408            attic_cache: None,
14409            extra_args: vec![],
14410            delegate_to_nix_build: false,
14411        };
14412        let iv = IntentVariant::Nix(&nix);
14413        assert_eq!(iv.kind(), iv.variant_kind());
14414
14415        let perm = PermanentLifetime::default();
14416        let lv = LifetimeVariant::Permanent(&perm);
14417        assert_eq!(lv.kind(), lv.variant_kind());
14418
14419        let hr = ExistingHelmRelease {
14420            namespace: "ns".into(),
14421            name: "n".into(),
14422            release_name: "r".into(),
14423        };
14424        let ev = EncapsulationKindVariant::ExistingHelmRelease(&hr);
14425        assert_eq!(ev.target(), ev.variant_kind());
14426
14427        let rs = ReceiptsSource {};
14428        let av = ArtifactVariant::Receipts(&rs);
14429        assert_eq!(av.kind(), av.variant_kind());
14430
14431        let ch = HttpEventChannel::signal("s");
14432        let cv = ChannelVariant::HttpEvent(&ch);
14433        assert_eq!(cv.kind(), cv.variant_kind());
14434    }
14435}