Skip to main content

tatara_process/
boundary.rs

1//! Boundary conditions — predicates that gate phase transitions.
2
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5
6use crate::flux_resource::FluxResource;
7
8/// Boundary specification — preconditions gate Running,
9/// postconditions gate Running → Attested.
10#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
11#[serde(rename_all = "camelCase")]
12pub struct Boundary {
13    #[serde(default)]
14    pub preconditions: Vec<Condition>,
15    #[serde(default)]
16    pub postconditions: Vec<Condition>,
17    /// Max time before VERIFY fails — parsed as a `go`-style duration.
18    /// Empty = controller default (15m).
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub timeout: Option<String>,
21}
22
23impl Boundary {
24    /// True iff at least one [`Condition`] in
25    /// `preconditions ∪ postconditions` carries the given
26    /// [`ConditionKind`] — the ONE substrate primitive that owns the
27    /// (closed-set discriminator, boundary-condition presence) probe on
28    /// this typed surface.
29    ///
30    /// # Semantics
31    ///
32    /// The two condition vectors are unioned: a caller asking "does this
33    /// spec name a `ClosedLoopAuth` predicate anywhere" doesn't care
34    /// whether the operator authored it on the pre- or post-condition
35    /// side. A boundary with the given kind on ONLY preconditions returns
36    /// `true`; a boundary with the given kind on ONLY postconditions
37    /// returns `true`; a boundary with neither returns `false`.
38    ///
39    /// # Sibling to [`crate::intent::Intent::has`] + [`crate::lifetime::Lifetime::has`]
40    ///
41    /// Same shape, same axis, third instance in the workspace-wide
42    /// closed-set-driven presence-probe algebra. `Intent::has` +
43    /// `Lifetime::has` publish the same `(&self, K) -> bool` signature
44    /// where `K` is the discriminator's `Kind` (auto-derived through
45    /// `#[derive(DeriveClosedSet)]`). A future normalization at that
46    /// probe shape (a widened return carrying the matching Condition
47    /// ref, a debug-build assertion on pre/post drift, a fleet-wide
48    /// warn on redundant duplicates) lands at ONE site per surface
49    /// and every downstream `<xxx>-<kind>` require-tag family +
50    /// closed-set audit dispatcher picks it up mechanically.
51    ///
52    /// # Peer on the ephemeral surface — [`crate::ephemeral::EphemeralSpec::has_condition_kind`]
53    ///
54    /// Same signature `(ConditionKind) -> bool`, same union body
55    /// (`preconditions.has_kind(k) || postconditions.has_kind(k)`), on
56    /// the sugar-surface type [`crate::ephemeral::EphemeralSpec`] whose
57    /// pre/post condition vectors live directly on the struct rather
58    /// than inside a nested [`Boundary`] slot. Both methods compose
59    /// against the ONE slice-level substrate primitive
60    /// [`ConditionSliceExt::has_kind`] — a regression at the per-slice
61    /// walk fails at that primitive's tests rather than as silent drift
62    /// at either struct-level union caller. The ephemeral require-tag
63    /// classifier reaches its `condition-<kind>` prefix family through
64    /// the peer method byte-for-byte symmetrical with the point
65    /// surface's `condition-<kind>` family that composes through this
66    /// method.
67    ///
68    /// # Compounding
69    ///
70    /// The point-domain require-tag surface in
71    /// `tatara-reconciler::bin::tatara-check` composes this primitive
72    /// with the closed-set `FromStr` autoderived on [`ConditionKind`]
73    /// through the `strip_and_classify_prefixed_kind` substrate to
74    /// publish a `condition-<kind>` prefix family byte-for-byte
75    /// symmetrical with `intent-<kind>` + `lifetime-<kind>`. A future
76    /// [`ConditionKind`] variant added to `ALL` reaches every downstream
77    /// (require-tag classifier, coherence check, editor completion
78    /// provider) through the SAME closed-set walk with no per-caller
79    /// edit.
80    ///
81    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition preserves
82    /// proofs — the presence-probe body lives at ONE substrate site so
83    /// every downstream `condition-<kind>` requires-tag surface,
84    /// closed-set audit dispatcher, and future variant addition binds
85    /// through the SAME shape). THEORY.md §VI.1 (generation over
86    /// composition — a ninth [`ConditionKind`] variant lands at ONE
87    /// `ALL` entry + ONE `as_str` arm and the presence probe picks it
88    /// up mechanically without further per-consumer edits).
89    #[must_use]
90    pub fn has_condition_kind(&self, kind: ConditionKind) -> bool {
91        self.has_precondition_kind(kind) || self.has_postcondition_kind(kind)
92    }
93
94    /// True iff at least one [`Condition`] in `self.preconditions`
95    /// carries the given [`ConditionKind`] — the precondition-side arm
96    /// of the (precondition, postcondition, condition-union) triad on
97    /// [`Boundary`], sibling to [`Self::has_postcondition_kind`] and
98    /// half-composition of [`Self::has_condition_kind`].
99    ///
100    /// Thin typed delegate to [`ConditionSliceExt::has_kind`] over
101    /// [`Self::preconditions`]. Peer of [`Self::has_postcondition_kind`]
102    /// on the (precondition, postcondition) partition of the boundary's
103    /// two condition-vector slots; both peers compose against the SAME
104    /// slice-level substrate primitive and their `||` composition is
105    /// [`Self::has_condition_kind`]. A regression that swapped the
106    /// slice at either arm (a copy-paste that pointed the precondition
107    /// probe at `self.postconditions`, an inline `.iter().any` closure
108    /// body that outlasted the lift) surfaces at the composition-law
109    /// pin `boundary_has_condition_kind_composes_precondition_and_postcondition_arms`
110    /// rather than as silent classifier drift at every downstream
111    /// `precondition-<kind>` require-tag callsite.
112    ///
113    /// # Why lift
114    ///
115    /// Pre-lift the point-domain `precondition-<kind>` require-tag
116    /// classifier in `tatara-reconciler::bin::tatara-check` reached the
117    /// precondition-side slice through direct field access
118    /// (`spec.boundary.preconditions.has_kind(k)`) while its sibling
119    /// `condition-<kind>` classifier routed through the named
120    /// [`Self::has_condition_kind`] primitive. The asymmetry meant a
121    /// future normalization at the presence-probe shape (a widened
122    /// return carrying the matching [`Condition`] ref, a debug-build
123    /// assertion on redundant duplicates, a fleet-wide warn on
124    /// pre-only ClosedLoopAuth authoring) would land at the union
125    /// primitive but bypass the two half-slice classifiers. Post-lift
126    /// the (precondition, postcondition, condition-union) triad lives
127    /// at ONE typed algebra surface on [`Boundary`], with the
128    /// `condition-<K> = precondition-<K> ∨ postcondition-<K>`
129    /// composition law pinned as a first-class typed invariant
130    /// (see the composition-pin test in this module) rather than a
131    /// per-caller discipline.
132    ///
133    /// # Semantics
134    ///
135    /// Returns `true` iff `self.preconditions.iter().any(|c| c.kind ==
136    /// kind)`. Ignores `self.postconditions` — an operator who authored
137    /// the kind on ONLY postconditions gets `false` from this probe and
138    /// `true` from [`Self::has_postcondition_kind`]. The two half-slice
139    /// arms partition the (kind, side) matrix exhaustively across the
140    /// four states (kind absent both, pre-only, post-only, both).
141    ///
142    /// # Sibling to [`crate::ephemeral::EphemeralSpec::has_precondition_kind`]
143    ///
144    /// Same shape, same axis, third and fourth methods in the
145    /// workspace-wide `has_(pre|post)condition_kind` two-surface
146    /// family. [`crate::ephemeral::EphemeralSpec::has_precondition_kind`]
147    /// composes byte-identical `preconditions.has_kind(k)` semantics on
148    /// the sugar-surface type's direct `preconditions: Vec<Condition>`
149    /// field, so both surfaces publish a `precondition-<kind>` require-
150    /// tag prefix family byte-for-byte symmetrical (point surface
151    /// through this method, ephemeral surface through its peer).
152    ///
153    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition
154    /// preserves proofs — the per-slice presence-probe body lives at
155    /// ONE substrate site so every downstream `precondition-<kind>`
156    /// require-tag surface, closed-set audit dispatcher, and future
157    /// variant addition binds through the SAME shape). THEORY.md §VI.1
158    /// (generation over composition — the union primitive
159    /// [`Self::has_condition_kind`] emerges from the composition of
160    /// its two half-slice arms rather than as a hand-authored `||`
161    /// closure at every downstream consumer).
162    #[must_use]
163    pub fn has_precondition_kind(&self, kind: ConditionKind) -> bool {
164        self.preconditions.has_kind(kind)
165    }
166
167    /// True iff at least one [`Condition`] in `self.postconditions`
168    /// carries the given [`ConditionKind`] — the postcondition-side arm
169    /// of the (precondition, postcondition, condition-union) triad on
170    /// [`Boundary`], sibling to [`Self::has_precondition_kind`] and
171    /// half-composition of [`Self::has_condition_kind`].
172    ///
173    /// Thin typed delegate to [`ConditionSliceExt::has_kind`] over
174    /// [`Self::postconditions`]. Peer of [`Self::has_precondition_kind`]
175    /// on the (precondition, postcondition) partition of the boundary's
176    /// two condition-vector slots. See [`Self::has_precondition_kind`]
177    /// for the full rationale — the two methods share ONE lift
178    /// motivation, ONE fail-before-pass-after composition-law pin, and
179    /// ONE two-surface parity contract with the ephemeral sugar type
180    /// via [`crate::ephemeral::EphemeralSpec::has_postcondition_kind`].
181    #[must_use]
182    pub fn has_postcondition_kind(&self, kind: ConditionKind) -> bool {
183        self.postconditions.has_kind(kind)
184    }
185
186    /// Returns the first [`Condition`] in
187    /// `preconditions ∪ postconditions` carrying the given
188    /// [`ConditionKind`], searching preconditions first — the
189    /// widened peer of [`Self::has_condition_kind`] one refinement
190    /// higher on the presence-probe algebra.
191    ///
192    /// # Sibling to [`Self::has_condition_kind`]
193    ///
194    /// Same axis, one refinement wider: `has_condition_kind` collapses
195    /// the return to a `bool` (`find_condition_kind(k).is_some()`);
196    /// this method returns the matching `&Condition` so consumers can
197    /// read [`Condition::params`] (the `probeImage`, the `expression`,
198    /// the `flakeRef`) at the presence probe's own callsite without
199    /// re-walking the two condition vectors. Pinned by the composition
200    /// law `has_condition_kind(K) == find_condition_kind(K).is_some()`
201    /// at [`Boundary`]'s substrate-delegation test.
202    ///
203    /// # Semantics — precondition takes precedence
204    ///
205    /// Walks [`Self::preconditions`] first, then [`Self::postconditions`]:
206    /// a kind authored on BOTH sides returns the precondition-side
207    /// [`Condition`]. Callers that need the postcondition-side match
208    /// specifically reach for [`Self::find_postcondition_kind`]; callers
209    /// that need every match across both sides walk the two vectors
210    /// directly. Composition law: `find_condition_kind(K) ==
211    /// find_precondition_kind(K).or_else(|| find_postcondition_kind(K))`,
212    /// pinned as a first-class typed invariant.
213    ///
214    /// # Peer on the ephemeral surface — [`crate::ephemeral::EphemeralSpec::find_condition_kind`]
215    ///
216    /// Same signature `(ConditionKind) -> Option<&Condition>`, same
217    /// precondition-first body, on the sugar-surface type whose
218    /// pre/post condition vectors live directly on the struct. Both
219    /// methods compose against the SAME slice-level substrate primitive
220    /// [`ConditionSliceExt::find_kind`] — a regression at the per-slice
221    /// walk fails at that primitive's tests rather than as silent drift
222    /// at either struct-level widened caller.
223    ///
224    /// # Compounding
225    ///
226    /// A future diagnostic consumer (an operator-facing "condition
227    /// {kind} matched on {side} with params.{key}={value}" message
228    /// emitted by the require-tag classifier, a coherence check that
229    /// verifies "every `ClosedLoopAuth` postcondition carries a
230    /// non-empty `probeImage`" by inspecting the returned
231    /// `&Condition.params`, an editor completion listing which
232    /// params-keys appear on the present kind) reaches for the
233    /// matching [`Condition`] through this ONE method rather than
234    /// re-walking the two vectors with `iter().find(...)` at the
235    /// callsite. The presence-probe axis now carries both refinements
236    /// (bool via `has_condition_kind`, `&Condition` via
237    /// `find_condition_kind`) at ONE typed algebra surface per struct.
238    ///
239    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition
240    /// preserves proofs — the widened return lives at ONE substrate
241    /// site so every downstream diagnostic consumer + coherence check
242    /// binds through the SAME shape rather than restating the
243    /// `.iter().find(|c| c.kind == K)` closure body).
244    #[must_use]
245    pub fn find_condition_kind(&self, kind: ConditionKind) -> Option<&Condition> {
246        self.find_precondition_kind(kind)
247            .or_else(|| self.find_postcondition_kind(kind))
248    }
249
250    /// Returns the first [`Condition`] in [`Self::preconditions`]
251    /// carrying the given [`ConditionKind`], or `None` — the
252    /// precondition-side arm of the (precondition, postcondition,
253    /// condition-union) widened triad on [`Boundary`]. Thin typed
254    /// delegate to [`ConditionSliceExt::find_kind`] over
255    /// [`Self::preconditions`].
256    ///
257    /// Peer of [`Self::find_postcondition_kind`] on the (precondition,
258    /// postcondition) partition of the boundary's two condition-vector
259    /// slots; both peers compose against the SAME slice-level substrate
260    /// primitive and their `or_else` composition is
261    /// [`Self::find_condition_kind`]. Byte-identical semantics to
262    /// [`Self::has_precondition_kind`] with a widened `Option<&Condition>`
263    /// return rather than a `bool`.
264    #[must_use]
265    pub fn find_precondition_kind(&self, kind: ConditionKind) -> Option<&Condition> {
266        self.preconditions.find_kind(kind)
267    }
268
269    /// Returns the first [`Condition`] in [`Self::postconditions`]
270    /// carrying the given [`ConditionKind`], or `None` — the
271    /// postcondition-side arm of the (precondition, postcondition,
272    /// condition-union) widened triad on [`Boundary`]. Thin typed
273    /// delegate to [`ConditionSliceExt::find_kind`] over
274    /// [`Self::postconditions`].
275    ///
276    /// Peer of [`Self::find_precondition_kind`] on the (precondition,
277    /// postcondition) partition of the boundary's two condition-vector
278    /// slots. See [`Self::find_precondition_kind`] for the full
279    /// rationale — the two methods share ONE lift motivation, ONE
280    /// fail-before-pass-after composition-law pin, and ONE two-surface
281    /// parity contract with the ephemeral sugar type via
282    /// [`crate::ephemeral::EphemeralSpec::find_postcondition_kind`].
283    #[must_use]
284    pub fn find_postcondition_kind(&self, kind: ConditionKind) -> Option<&Condition> {
285        self.postconditions.find_kind(kind)
286    }
287
288    /// Returns an iterator over every [`Condition`] in
289    /// `preconditions ∪ postconditions` carrying the given
290    /// [`ConditionKind`], walking preconditions first — the
291    /// widened peer of [`Self::find_condition_kind`] one refinement
292    /// higher on the presence-probe algebra. Byte-for-byte
293    /// equivalent to
294    /// `self.iter_precondition_kind(kind).chain(self.iter_postcondition_kind(kind))`.
295    ///
296    /// # Sibling to [`Self::find_condition_kind`]
297    ///
298    /// Same axis, one refinement wider: `find_condition_kind`
299    /// collapses the return to the FIRST match (yielding
300    /// `Option<&Condition>`); this method yields every match across
301    /// both sides. Pinned by the composition law
302    /// `find_condition_kind(K) == iter_condition_kind(K).next()` at
303    /// [`Boundary`]'s substrate-delegation test — the two refinements
304    /// share ONE walk order by construction (preconditions first,
305    /// then postconditions), so a regression that reversed the
306    /// [`Chain`](std::iter::Chain) order or narrowed the union to an
307    /// intersection surfaces HERE at the substrate boundary rather
308    /// than as silent skew between the first-match and stream
309    /// refinements downstream consumers reach through.
310    ///
311    /// # Peer on the ephemeral surface — [`crate::ephemeral::EphemeralSpec::iter_condition_kind`]
312    ///
313    /// Same signature `(ConditionKind) -> Chain<KindMatches<'_>,
314    /// KindMatches<'_>>`, same precondition-first chain body, on the
315    /// sugar-surface type whose pre/post condition vectors live
316    /// directly on the struct. Both methods compose against the SAME
317    /// slice-level substrate primitive [`ConditionSliceExt::iter_kind`]
318    /// — a regression at the per-slice walk fails at that primitive's
319    /// tests rather than as silent drift at either struct-level
320    /// widened caller.
321    ///
322    /// # Compounding
323    ///
324    /// A future coherence check that enforces "each
325    /// [`ConditionKind`] appears at most once across
326    /// preconditions ∪ postconditions" reads
327    /// `boundary.iter_condition_kind(k).nth(1).is_none()` at ONE
328    /// call site rather than restating the count-with-filter closure
329    /// body over the two vector slots. A future diagnostic
330    /// enumerating every match (an operator-facing "N ClosedLoopAuth
331    /// conditions matched, listing sides + params" message emitted
332    /// by the require-tag classifier) reaches this ONE method
333    /// through `boundary.iter_condition_kind(k).collect()` rather
334    /// than chaining two half-slice walks at the callsite.
335    /// The presence-probe axis on [`Boundary`] now carries three
336    /// refinements (bool via `has_condition_kind`,
337    /// `Option<&Condition>` via `find_condition_kind`,
338    /// `impl Iterator<Item = &Condition>` via
339    /// `iter_condition_kind`) at ONE typed algebra surface, byte-
340    /// for-byte peer of the same triad on
341    /// [`crate::ephemeral::EphemeralSpec`].
342    ///
343    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition
344    /// preserves proofs — the widened stream lives at ONE substrate
345    /// site so every downstream diagnostic + coherence consumer binds
346    /// through the SAME shape rather than restating the two-half
347    /// chain body).
348    pub fn iter_condition_kind(
349        &self,
350        kind: ConditionKind,
351    ) -> std::iter::Chain<KindMatches<'_>, KindMatches<'_>> {
352        self.iter_precondition_kind(kind)
353            .chain(self.iter_postcondition_kind(kind))
354    }
355
356    /// Returns an iterator over every [`Condition`] in
357    /// [`Self::preconditions`] carrying the given [`ConditionKind`]
358    /// — the precondition-side arm of the (precondition,
359    /// postcondition, condition-union) iterator triad on
360    /// [`Boundary`]. Thin typed delegate to
361    /// [`ConditionSliceExt::iter_kind`] over [`Self::preconditions`].
362    ///
363    /// Peer of [`Self::iter_postcondition_kind`] on the (precondition,
364    /// postcondition) partition of the boundary's two condition-vector
365    /// slots; both peers compose against the SAME slice-level substrate
366    /// primitive and their [`Chain`](std::iter::Chain) composition is
367    /// [`Self::iter_condition_kind`]. Byte-identical semantics to
368    /// [`Self::find_precondition_kind`] with a widened stream return
369    /// rather than only the first match.
370    pub fn iter_precondition_kind(&self, kind: ConditionKind) -> KindMatches<'_> {
371        self.preconditions.iter_kind(kind)
372    }
373
374    /// Returns an iterator over every [`Condition`] in
375    /// [`Self::postconditions`] carrying the given [`ConditionKind`]
376    /// — the postcondition-side arm of the (precondition,
377    /// postcondition, condition-union) iterator triad on
378    /// [`Boundary`]. Thin typed delegate to
379    /// [`ConditionSliceExt::iter_kind`] over
380    /// [`Self::postconditions`].
381    ///
382    /// Peer of [`Self::iter_precondition_kind`] on the (precondition,
383    /// postcondition) partition of the boundary's two condition-vector
384    /// slots. See [`Self::iter_precondition_kind`] for the full
385    /// rationale — the two methods share ONE lift motivation, ONE
386    /// fail-before-pass-after composition-law pin, and ONE
387    /// two-surface parity contract with the ephemeral sugar type via
388    /// [`crate::ephemeral::EphemeralSpec::iter_postcondition_kind`].
389    pub fn iter_postcondition_kind(&self, kind: ConditionKind) -> KindMatches<'_> {
390        self.postconditions.iter_kind(kind)
391    }
392
393    /// Number of [`Condition`]s in `preconditions ∪ postconditions`
394    /// carrying the given [`ConditionKind`] — the scalar cardinality
395    /// arm of the (precondition, postcondition, condition-union)
396    /// count triad on [`Boundary`]. Composed as
397    /// `count_precondition_kind(k) + count_postcondition_kind(k)` —
398    /// the ONE SUM-composed arm on the presence-probe algebra
399    /// (distinct from `has_condition_kind`'s `||` union,
400    /// `find_condition_kind`'s `or_else` first-match, and
401    /// `iter_condition_kind`'s `Chain` stream).
402    ///
403    /// # Sibling to [`Self::iter_condition_kind`]
404    ///
405    /// Same axis, one refinement lower on the cardinality projection:
406    /// `iter_condition_kind` yields the whole match stream across both
407    /// sides; this method collapses that stream to its cardinality
408    /// without materializing any intermediate [`Vec`]. Composition law
409    /// `count_condition_kind(K) == iter_condition_kind(K).count()`
410    /// pinned as a first-class typed invariant at the substrate-
411    /// delegation test.
412    ///
413    /// # Peer on the ephemeral surface — [`crate::ephemeral::EphemeralSpec::count_condition_kind`]
414    ///
415    /// Same signature `(ConditionKind) -> usize`, same SUM body, on
416    /// the sugar-surface type whose pre/post condition vectors live
417    /// directly on the struct. Both methods compose against the SAME
418    /// slice-level substrate primitive [`ConditionSliceExt::count_kind`]
419    /// — a regression at the per-slice count fails at that primitive's
420    /// tests rather than as silent drift at either struct-level union
421    /// caller.
422    ///
423    /// # Compounding
424    ///
425    /// A future coherence check that enforces "each [`ConditionKind`]
426    /// appears at most once across preconditions ∪ postconditions"
427    /// reads `boundary.count_condition_kind(k) <= 1` at ONE call site.
428    /// A future require-tag classifier arm that surfaces multiplicity
429    /// to the operator (a hypothetical `condition-count-<kind>` prefix
430    /// family, an audit dump reporting "N ClosedLoopAuth conditions
431    /// matched") reaches this ONE method rather than restating the
432    /// `.iter_condition_kind(k).count()` chain body at the callsite.
433    /// The presence-probe axis on [`Boundary`] now carries FOUR
434    /// refinements (bool via `has_condition_kind`, `Option<&Condition>`
435    /// via `find_condition_kind`, `impl Iterator<Item = &Condition>`
436    /// via `iter_condition_kind`, `usize` via `count_condition_kind`)
437    /// at ONE typed algebra surface per struct, byte-for-byte peer of
438    /// the same tetrad on [`crate::ephemeral::EphemeralSpec`].
439    ///
440    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition
441    /// preserves proofs — the scalar cardinality lives at ONE
442    /// substrate site so every downstream diagnostic + coherence
443    /// consumer binds through the SAME shape rather than restating
444    /// the two-half sum body).
445    #[must_use]
446    pub fn count_condition_kind(&self, kind: ConditionKind) -> usize {
447        self.count_precondition_kind(kind) + self.count_postcondition_kind(kind)
448    }
449
450    /// Number of [`Condition`]s in [`Self::preconditions`] carrying
451    /// the given [`ConditionKind`] — the precondition-side arm of the
452    /// (precondition, postcondition, condition-union) count triad on
453    /// [`Boundary`]. Thin typed delegate to
454    /// [`ConditionSliceExt::count_kind`] over [`Self::preconditions`].
455    ///
456    /// Peer of [`Self::count_postcondition_kind`] on the (precondition,
457    /// postcondition) partition of the boundary's two condition-vector
458    /// slots; both peers compose against the SAME slice-level substrate
459    /// primitive and their `+` composition is
460    /// [`Self::count_condition_kind`]. Byte-identical semantics to
461    /// [`Self::iter_precondition_kind`] with the scalar `usize`
462    /// cardinality projection rather than the widened stream.
463    #[must_use]
464    pub fn count_precondition_kind(&self, kind: ConditionKind) -> usize {
465        self.preconditions.count_kind(kind)
466    }
467
468    /// Number of [`Condition`]s in [`Self::postconditions`] carrying
469    /// the given [`ConditionKind`] — the postcondition-side arm of
470    /// the (precondition, postcondition, condition-union) count triad
471    /// on [`Boundary`]. Thin typed delegate to
472    /// [`ConditionSliceExt::count_kind`] over
473    /// [`Self::postconditions`].
474    ///
475    /// Peer of [`Self::count_precondition_kind`]. See that method for
476    /// the full rationale — the two methods share ONE lift motivation,
477    /// ONE fail-before-pass-after composition-law pin, and ONE
478    /// two-surface parity contract with the ephemeral sugar type via
479    /// [`crate::ephemeral::EphemeralSpec::count_postcondition_kind`].
480    #[must_use]
481    pub fn count_postcondition_kind(&self, kind: ConditionKind) -> usize {
482        self.postconditions.count_kind(kind)
483    }
484
485    /// The set of [`ConditionKind`] variants that appear at least once in
486    /// `preconditions ∪ postconditions`, projected in
487    /// [`ConditionKind::ALL`] order — the closed-set-inversion refinement
488    /// on the presence-probe algebra (distinct axis from the four point-
489    /// probe refinements: bool via [`Self::has_condition_kind`],
490    /// `Option<&Condition>` via [`Self::find_condition_kind`],
491    /// `impl Iterator<Item = &Condition>` via [`Self::iter_condition_kind`],
492    /// `usize` via [`Self::count_condition_kind`]).
493    ///
494    /// # Composed body
495    ///
496    /// `ConditionKind::ALL.into_iter().filter(|k|
497    /// self.has_condition_kind(*k)).collect()` — a thin projection over
498    /// the closed set composed against the two-slice union primitive
499    /// [`Self::has_condition_kind`]. Equivalent to the set-union of
500    /// [`Self::distinct_precondition_kinds`] and
501    /// [`Self::distinct_postcondition_kinds`] projected in canonical
502    /// [`ConditionKind::ALL`] order (the union composition law pinned by
503    /// the substrate testkit macro [`crate::assert_surface_union_composition_laws`]).
504    ///
505    /// # Peer on the ephemeral surface — [`crate::ephemeral::EphemeralSpec::distinct_condition_kinds`]
506    ///
507    /// Same signature `(&Self) -> Vec<ConditionKind>`, same closed-set-
508    /// inversion body, on the sugar-surface type whose pre/post condition
509    /// vectors live directly on the struct. Both methods compose against
510    /// the SAME slice-level substrate primitive
511    /// [`ConditionSliceExt::distinct_kinds`] via the two-slice union
512    /// composed through [`Self::has_condition_kind`] — a regression at
513    /// the per-slice walk fails at that primitive's tests rather than as
514    /// silent drift at either struct-level union caller.
515    ///
516    /// # Sibling to the four point-probe refinements
517    ///
518    /// FIFTH refinement on the boundary-surface presence-probe algebra,
519    /// distinct in axis from the other four: `has_condition_kind` /
520    /// `find_condition_kind` / `iter_condition_kind` /
521    /// `count_condition_kind` fix a [`ConditionKind`] and vary the return
522    /// type; this refinement INVERTS the axis by fixing the boundary and
523    /// varying over [`ConditionKind::ALL`]. The composition law
524    /// `distinct_condition_kinds().contains(&k) == has_condition_kind(k)`
525    /// for every `k ∈ ConditionKind::ALL` binds the closed-set-inversion
526    /// probe to the point probe at the (precondition, postcondition,
527    /// condition-union) triad.
528    ///
529    /// # Compounding
530    ///
531    /// A future coherence check that enforces "every process boundary
532    /// carries at least ONE distinct kind" (a warning surfaced when
533    /// `spec.boundary.distinct_condition_kinds().is_empty()`) reaches
534    /// this ONE method rather than paying for the eight-way sweep with
535    /// `has_condition_kind` at every callsite. A future require-tag
536    /// classifier that surfaces the distinct-set cardinality as a scalar
537    /// (a hypothetical `condition-kinds-distinct-<n>` prefix family, an
538    /// audit dump reporting "boundary carries N distinct kinds") reaches
539    /// this ONE method through `.distinct_condition_kinds().len()`
540    /// rather than restating the closed-set-inverted filter idiom at
541    /// every callsite.
542    ///
543    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition preserves
544    /// proofs — the closed-set-inversion aggregate is a typed projection
545    /// of [`Self::has_condition_kind`] over [`ConditionKind::ALL`], and
546    /// every downstream aggregate consumer binds through the SAME shape).
547    /// THEORY.md §VI.1 (generation over composition — a new
548    /// [`ConditionKind`] variant added to `ALL` reaches this method
549    /// mechanically through the closed-set walk).
550    #[must_use]
551    pub fn distinct_condition_kinds(&self) -> Vec<ConditionKind> {
552        ConditionKind::ALL
553            .into_iter()
554            .filter(|k| self.has_condition_kind(*k))
555            .collect()
556    }
557
558    /// The set of [`ConditionKind`] variants appearing at least once in
559    /// [`Self::preconditions`], projected in [`ConditionKind::ALL`]
560    /// order — the precondition-side arm of the (precondition,
561    /// postcondition, condition-union) distinct-set triad on
562    /// [`Boundary`]. Thin typed delegate to
563    /// [`ConditionSliceExt::distinct_kinds`] over
564    /// [`Self::preconditions`].
565    ///
566    /// Peer of [`Self::distinct_postcondition_kinds`] on the
567    /// (precondition, postcondition) partition of the boundary's two
568    /// condition-vector slots; both peers compose against the SAME
569    /// slice-level substrate primitive and their canonical set-union
570    /// (projected in [`ConditionKind::ALL`] order) is
571    /// [`Self::distinct_condition_kinds`].
572    #[must_use]
573    pub fn distinct_precondition_kinds(&self) -> Vec<ConditionKind> {
574        self.preconditions.distinct_kinds()
575    }
576
577    /// The set of [`ConditionKind`] variants appearing at least once in
578    /// [`Self::postconditions`], projected in [`ConditionKind::ALL`]
579    /// order — the postcondition-side arm of the (precondition,
580    /// postcondition, condition-union) distinct-set triad on
581    /// [`Boundary`]. Thin typed delegate to
582    /// [`ConditionSliceExt::distinct_kinds`] over
583    /// [`Self::postconditions`].
584    ///
585    /// Peer of [`Self::distinct_precondition_kinds`]. See that method
586    /// for the full rationale — the two methods share ONE lift
587    /// motivation, ONE fail-before-pass-after composition-law pin, and
588    /// ONE two-surface parity contract with the ephemeral sugar type
589    /// via [`crate::ephemeral::EphemeralSpec::distinct_postcondition_kinds`].
590    #[must_use]
591    pub fn distinct_postcondition_kinds(&self) -> Vec<ConditionKind> {
592        self.postconditions.distinct_kinds()
593    }
594
595    /// Scalar cardinality of the [`ConditionKind`] set appearing at
596    /// least once in `preconditions ∪ postconditions` — the
597    /// condition-union arm of the (precondition, postcondition,
598    /// condition-union) distinct-kind-count triad on [`Boundary`].
599    ///
600    /// # Composed body
601    ///
602    /// `ConditionKind::ALL.iter().filter(|k|
603    /// self.has_condition_kind(**k)).count()` — a thin projection over
604    /// the closed set composed against the two-slice union primitive
605    /// [`Self::has_condition_kind`], byte-identical to the trait-level
606    /// [`ConditionSliceExt::distinct_kind_count`] but reaching through
607    /// the boundary's two-slice union rather than a single slice.
608    /// Equivalent to `self.distinct_condition_kinds().len()` without
609    /// materializing the intermediate `Vec<ConditionKind>`.
610    ///
611    /// # Sibling to [`Self::distinct_condition_kinds`]
612    ///
613    /// Scalar projection of the closed-set-inversion widened primitive
614    /// on the boundary-union surface — where `distinct_condition_kinds`
615    /// returns the SET, `distinct_condition_kind_count` collapses it to
616    /// its cardinality. Byte-for-byte peer of the point-domain scalar
617    /// projection [`ConditionSliceExt::distinct_kind_count`] one
618    /// struct-layer down, and of the peer surface sugar
619    /// [`crate::ephemeral::EphemeralSpec::distinct_condition_kind_count`]
620    /// one struct-layer sideways.
621    ///
622    /// # Compounding
623    ///
624    /// A future coherence check that enforces "every process boundary
625    /// carries at least ONE distinct kind" now reads
626    /// `spec.boundary.distinct_condition_kind_count() > 0` at ONE call
627    /// site rather than paying for
628    /// `spec.boundary.distinct_condition_kinds().len() > 0` (with its
629    /// intermediate heap allocation) or the eight-way `has_*_kind`
630    /// sweep at the callsite. A future require-tag classifier arm that
631    /// publishes the distinct-set cardinality as a scalar (a
632    /// hypothetical `condition-kinds-distinct-<n>` prefix family)
633    /// reaches this ONE primitive without allocating.
634    ///
635    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
636    /// preserves proofs (the scalar cardinality composes the SAME
637    /// closed-set walk on both this boundary surface and the
638    /// slice-level substrate primitive). THEORY.md §VI.1 — generation
639    /// over composition (a new [`ConditionKind`] variant added to
640    /// `ALL` reaches this primitive mechanically through the closed-set
641    /// walk).
642    #[must_use]
643    pub fn distinct_condition_kind_count(&self) -> usize {
644        ConditionKind::ALL
645            .iter()
646            .filter(|k| self.has_condition_kind(**k))
647            .count()
648    }
649
650    /// Scalar cardinality of the [`ConditionKind`] set appearing at
651    /// least once in [`Self::preconditions`] — the precondition-side
652    /// arm of the (precondition, postcondition, condition-union)
653    /// distinct-kind-count triad on [`Boundary`]. Thin typed delegate
654    /// to [`ConditionSliceExt::distinct_kind_count`] over
655    /// [`Self::preconditions`].
656    ///
657    /// Peer of [`Self::distinct_postcondition_kind_count`] on the
658    /// (precondition, postcondition) partition of the boundary's two
659    /// condition-vector slots; both peers compose against the SAME
660    /// slice-level substrate primitive so a regression at the per-slice
661    /// closed-set walk fails at that primitive's tests rather than as
662    /// silent drift at either struct-level scalar-cardinality arm.
663    #[must_use]
664    pub fn distinct_precondition_kind_count(&self) -> usize {
665        self.preconditions.distinct_kind_count()
666    }
667
668    /// Scalar cardinality of the [`ConditionKind`] set appearing at
669    /// least once in [`Self::postconditions`] — the postcondition-side
670    /// arm of the (precondition, postcondition, condition-union)
671    /// distinct-kind-count triad on [`Boundary`]. Thin typed delegate
672    /// to [`ConditionSliceExt::distinct_kind_count`] over
673    /// [`Self::postconditions`].
674    ///
675    /// Peer of [`Self::distinct_precondition_kind_count`]. See that
676    /// method for the full rationale — the two methods share ONE lift
677    /// motivation, ONE fail-before-pass-after composition-law pin, and
678    /// ONE two-surface parity contract with the ephemeral sugar type
679    /// via
680    /// [`crate::ephemeral::EphemeralSpec::distinct_postcondition_kind_count`].
681    #[must_use]
682    pub fn distinct_postcondition_kind_count(&self) -> usize {
683        self.postconditions.distinct_kind_count()
684    }
685
686    /// The set of [`ConditionKind`] variants that do NOT appear in
687    /// `preconditions ∪ postconditions`, projected in
688    /// [`ConditionKind::ALL`] order — the closed-set-inversion
689    /// COMPLEMENT of [`Self::distinct_condition_kinds`] on the
690    /// (precondition, postcondition, condition-union) missing-set triad.
691    ///
692    /// # Composed body
693    ///
694    /// `ConditionKind::ALL.into_iter().filter(|k|
695    /// !self.has_condition_kind(*k)).collect()` — a thin projection
696    /// over the closed set composed against the two-slice union
697    /// primitive [`Self::has_condition_kind`] under a negated
698    /// predicate. Equivalent to the SET-INTERSECTION of
699    /// [`Self::missing_precondition_kinds`] and
700    /// [`Self::missing_postcondition_kinds`] projected in canonical
701    /// [`ConditionKind::ALL`] order — a kind is missing from the
702    /// union iff it is missing from BOTH half-slices (the union-
703    /// composition law pinned by the substrate testkit macro
704    /// [`crate::assert_surface_union_composition_laws`]).
705    ///
706    /// # Peer on the ephemeral surface — [`crate::ephemeral::EphemeralSpec::missing_condition_kinds`]
707    ///
708    /// Same signature `(&Self) -> Vec<ConditionKind>`, same closed-set-
709    /// complement body, on the sugar-surface type. Both methods compose
710    /// against the SAME slice-level substrate primitive
711    /// [`ConditionSliceExt::missing_kinds`] via the two-slice union
712    /// composed through [`Self::has_condition_kind`] — a regression at
713    /// the per-slice walk fails at that primitive's tests rather than
714    /// as silent drift at either struct-level complement caller.
715    ///
716    /// # Sibling to [`Self::distinct_condition_kinds`]
717    ///
718    /// SIXTH refinement on the boundary-surface presence-probe algebra,
719    /// on the SAME closed-set-inversion axis as `distinct_condition_kinds`
720    /// but under a NEGATED point-probe. The composition law
721    /// `missing_condition_kinds().contains(&k) ==
722    /// !has_condition_kind(k)` for every `k ∈ ConditionKind::ALL`
723    /// binds the complement to the point probe at the triad — and the
724    /// two widened primitives PARTITION `ConditionKind::ALL` (their
725    /// union covers `ALL`, their intersection is empty, their
726    /// cardinalities sum to `ALL.len()`).
727    ///
728    /// # Compounding
729    ///
730    /// A future coherence check that enforces "every process boundary
731    /// carries a [`ConditionKind::JobAttested`] postcondition" surfaces
732    /// the operator-facing gap diagnostic
733    /// `spec.boundary.postconditions.missing_kinds()` verbatim (naming
734    /// EVERY kind absent from postconditions in canonical order). A
735    /// future operator-facing "boundary is MISSING [JobAttested,
736    /// ClosedLoopAuth]" audit dump reads this ONE method rather than
737    /// restating the negated closed-set walk at every consumer. A
738    /// hypothetical `condition-kinds-missing-<n>` require-tag classifier
739    /// prefix family that publishes the missing-set cardinality as a
740    /// scalar reaches `.missing_condition_kinds().len()`.
741    ///
742    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition
743    /// preserves proofs — the closed-set complement is a typed
744    /// projection of [`Self::has_condition_kind`] over
745    /// [`ConditionKind::ALL`] under negation, and every downstream
746    /// gap-analysis consumer binds through the SAME shape).
747    /// THEORY.md §VI.1 (generation over composition — a new
748    /// [`ConditionKind`] variant added to `ALL` reaches this method
749    /// mechanically through the closed-set walk).
750    #[must_use]
751    pub fn missing_condition_kinds(&self) -> Vec<ConditionKind> {
752        ConditionKind::ALL
753            .into_iter()
754            .filter(|k| !self.has_condition_kind(*k))
755            .collect()
756    }
757
758    /// The set of [`ConditionKind`] variants that do NOT appear in
759    /// [`Self::preconditions`], projected in [`ConditionKind::ALL`]
760    /// order — the precondition-side arm of the (precondition,
761    /// postcondition, condition-union) missing-set triad on
762    /// [`Boundary`]. Thin typed delegate to
763    /// [`ConditionSliceExt::missing_kinds`] over
764    /// [`Self::preconditions`].
765    ///
766    /// Peer of [`Self::missing_postcondition_kinds`] on the
767    /// (precondition, postcondition) partition of the boundary's two
768    /// condition-vector slots; both peers compose against the SAME
769    /// slice-level substrate primitive and their SET-INTERSECTION
770    /// (projected in [`ConditionKind::ALL`] order) is
771    /// [`Self::missing_condition_kinds`].
772    #[must_use]
773    pub fn missing_precondition_kinds(&self) -> Vec<ConditionKind> {
774        self.preconditions.missing_kinds()
775    }
776
777    /// The set of [`ConditionKind`] variants that do NOT appear in
778    /// [`Self::postconditions`], projected in [`ConditionKind::ALL`]
779    /// order — the postcondition-side arm of the (precondition,
780    /// postcondition, condition-union) missing-set triad on
781    /// [`Boundary`]. Thin typed delegate to
782    /// [`ConditionSliceExt::missing_kinds`] over
783    /// [`Self::postconditions`].
784    ///
785    /// Peer of [`Self::missing_precondition_kinds`]. See that method
786    /// for the full rationale — the two methods share ONE lift
787    /// motivation, ONE fail-before-pass-after composition-law pin, and
788    /// ONE two-surface parity contract with the ephemeral sugar type
789    /// via [`crate::ephemeral::EphemeralSpec::missing_postcondition_kinds`].
790    #[must_use]
791    pub fn missing_postcondition_kinds(&self) -> Vec<ConditionKind> {
792        self.postconditions.missing_kinds()
793    }
794
795    /// Scalar cardinality of the [`ConditionKind`] set NOT appearing in
796    /// `preconditions ∪ postconditions` — the condition-union arm of the
797    /// (precondition, postcondition, condition-union) missing-kind-count
798    /// triad on [`Boundary`].
799    ///
800    /// # Composed body
801    ///
802    /// `ConditionKind::ALL.iter().filter(|k|
803    /// !self.has_condition_kind(**k)).count()` — a thin projection over
804    /// the closed set composed against the two-slice union primitive
805    /// [`Self::has_condition_kind`] under a NEGATED predicate, byte-
806    /// identical to the trait-level
807    /// [`ConditionSliceExt::missing_kind_count`] but reaching through
808    /// the boundary's two-slice union rather than a single slice.
809    /// Equivalent to `self.missing_condition_kinds().len()` without
810    /// materializing the intermediate `Vec<ConditionKind>`.
811    ///
812    /// # Sibling to [`Self::missing_condition_kinds`] /
813    /// [`Self::distinct_condition_kind_count`]
814    ///
815    /// Scalar projection of the closed-set-complement widened primitive
816    /// on the boundary-union surface — where `missing_condition_kinds`
817    /// returns the SET, `missing_condition_kind_count` collapses it to
818    /// its cardinality. Byte-for-byte peer of the point-domain scalar
819    /// projection [`ConditionSliceExt::missing_kind_count`] one struct-
820    /// layer down, and of the peer surface sugar
821    /// [`crate::ephemeral::EphemeralSpec::missing_condition_kind_count`]
822    /// one struct-layer sideways.
823    ///
824    /// The scalar-partition composition law
825    /// `distinct_condition_kind_count() + missing_condition_kind_count()
826    /// == ConditionKind::ALL.len()` binds this method's return to its
827    /// distinct-side peer through the closed-set cardinality — the
828    /// scalar consequence of the widened-primitive partition law that
829    /// [`assert_slice_refinement_composition_laws`] pins on each slice
830    /// and that [`crate::assert_surface_union_composition_laws`] lifts
831    /// to the two-slice union.
832    ///
833    /// # Compounding
834    ///
835    /// A future coherence check that enforces "every process boundary
836    /// carries EVERY [`ConditionKind`] under some slot" now reads
837    /// `spec.boundary.missing_condition_kind_count() == 0` at ONE call
838    /// site rather than paying for
839    /// `spec.boundary.missing_condition_kinds().is_empty()` (with its
840    /// intermediate heap allocation) or the eight-way negated `has_*_kind`
841    /// sweep at the callsite. A future require-tag classifier arm that
842    /// publishes the missing-set cardinality as a scalar (a hypothetical
843    /// `condition-kinds-missing-<n>` prefix family) reaches this ONE
844    /// primitive without allocating.
845    ///
846    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
847    /// preserves proofs (the scalar cardinality composes the SAME
848    /// closed-set walk under negation on both this boundary surface and
849    /// the slice-level substrate primitive). THEORY.md §VI.1 —
850    /// generation over composition (a new [`ConditionKind`] variant
851    /// added to `ALL` reaches this primitive mechanically through the
852    /// closed-set walk).
853    #[must_use]
854    pub fn missing_condition_kind_count(&self) -> usize {
855        ConditionKind::ALL
856            .iter()
857            .filter(|k| !self.has_condition_kind(**k))
858            .count()
859    }
860
861    /// Scalar cardinality of the [`ConditionKind`] set NOT appearing in
862    /// [`Self::preconditions`] — the precondition-side arm of the
863    /// (precondition, postcondition, condition-union) missing-kind-count
864    /// triad on [`Boundary`]. Thin typed delegate to
865    /// [`ConditionSliceExt::missing_kind_count`] over
866    /// [`Self::preconditions`].
867    ///
868    /// Peer of [`Self::missing_postcondition_kind_count`] on the
869    /// (precondition, postcondition) partition of the boundary's two
870    /// condition-vector slots; both peers compose against the SAME
871    /// slice-level substrate primitive so a regression at the per-slice
872    /// negated closed-set walk fails at that primitive's tests rather
873    /// than as silent drift at either struct-level scalar-cardinality
874    /// arm.
875    #[must_use]
876    pub fn missing_precondition_kind_count(&self) -> usize {
877        self.preconditions.missing_kind_count()
878    }
879
880    /// Scalar cardinality of the [`ConditionKind`] set NOT appearing in
881    /// [`Self::postconditions`] — the postcondition-side arm of the
882    /// (precondition, postcondition, condition-union) missing-kind-count
883    /// triad on [`Boundary`]. Thin typed delegate to
884    /// [`ConditionSliceExt::missing_kind_count`] over
885    /// [`Self::postconditions`].
886    ///
887    /// Peer of [`Self::missing_precondition_kind_count`]. See that
888    /// method for the full rationale — the two methods share ONE lift
889    /// motivation, ONE fail-before-pass-after composition-law pin, and
890    /// ONE two-surface parity contract with the ephemeral sugar type
891    /// via
892    /// [`crate::ephemeral::EphemeralSpec::missing_postcondition_kind_count`].
893    #[must_use]
894    pub fn missing_postcondition_kind_count(&self) -> usize {
895        self.postconditions.missing_kind_count()
896    }
897
898    /// Earliest [`ConditionKind::ALL`] entry present in
899    /// `preconditions ∪ postconditions`, or `None` when neither side
900    /// populates any variant — the union arm of the (precondition,
901    /// postcondition, condition-union) first-distinct-kind triad on
902    /// [`Boundary`].
903    ///
904    /// # Composed body
905    ///
906    /// `ConditionKind::ALL.iter().copied().find(|k|
907    /// self.has_condition_kind(*k))` — a closed-set walk composed
908    /// against the two-slice union primitive
909    /// [`Self::has_condition_kind`] that SHORT-CIRCUITS at the earliest
910    /// match. Byte-identical to the trait-level
911    /// [`ConditionSliceExt::first_distinct_kind`] but reaching through
912    /// the boundary's two-slice union rather than a single slice.
913    /// Equivalent to `self.distinct_condition_kinds().first().copied()`
914    /// without materializing the intermediate `Vec<ConditionKind>`.
915    ///
916    /// # Sibling to [`Self::distinct_condition_kinds`] /
917    /// [`Self::distinct_condition_kind_count`]
918    ///
919    /// Third scalar projection of the closed-set-inversion widened
920    /// primitive on the boundary-union surface: `distinct_condition_kinds`
921    /// returns the SET, `distinct_condition_kind_count` collapses it to
922    /// its cardinality, and `first_distinct_condition_kind` collapses
923    /// it to its earliest element. Byte-for-byte peer of the point-domain
924    /// scalar projection [`ConditionSliceExt::first_distinct_kind`] one
925    /// struct-layer down, and of the peer surface sugar
926    /// [`crate::ephemeral::EphemeralSpec::first_distinct_condition_kind`]
927    /// one struct-layer sideways.
928    ///
929    /// # Compounding
930    ///
931    /// A future coherence check that surfaces "boundary starts with
932    /// PromQL" reads `spec.boundary.first_distinct_condition_kind() ==
933    /// Some(ConditionKind::PromQL)` at ONE call site rather than
934    /// paying for `spec.boundary.distinct_condition_kinds().first() ==
935    /// Some(&ConditionKind::PromQL)` (with its intermediate heap
936    /// allocation) or the eight-way `has_*_kind` sweep at the callsite.
937    /// A future require-tag classifier arm that publishes the earliest
938    /// distinct kind as a scalar
939    /// (`condition-kinds-first-distinct-<kind>`) reaches this ONE
940    /// primitive without allocating.
941    ///
942    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
943    /// preserves proofs (the earliest-element projection composes the
944    /// SAME closed-set walk on both this boundary surface and the
945    /// slice-level substrate primitive under short-circuit semantics).
946    /// THEORY.md §VI.1 — generation over composition (a new
947    /// [`ConditionKind`] variant added to `ALL` reaches this primitive
948    /// mechanically through the closed-set walk).
949    #[must_use]
950    pub fn first_distinct_condition_kind(&self) -> Option<ConditionKind> {
951        ConditionKind::ALL
952            .iter()
953            .copied()
954            .find(|k| self.has_condition_kind(*k))
955    }
956
957    /// Earliest [`ConditionKind::ALL`] entry present in
958    /// [`Self::preconditions`], or `None` when preconditions carry no
959    /// matching kind — the precondition-side arm of the (precondition,
960    /// postcondition, condition-union) first-distinct-kind triad on
961    /// [`Boundary`]. Thin typed delegate to
962    /// [`ConditionSliceExt::first_distinct_kind`] over
963    /// [`Self::preconditions`].
964    ///
965    /// Peer of [`Self::first_distinct_postcondition_kind`] on the
966    /// (precondition, postcondition) partition of the boundary's two
967    /// condition-vector slots; both peers compose against the SAME
968    /// slice-level substrate primitive so a regression at the per-slice
969    /// short-circuit walk fails at that primitive's tests rather than
970    /// as silent drift at either struct-level arm.
971    #[must_use]
972    pub fn first_distinct_precondition_kind(&self) -> Option<ConditionKind> {
973        self.preconditions.first_distinct_kind()
974    }
975
976    /// Earliest [`ConditionKind::ALL`] entry present in
977    /// [`Self::postconditions`], or `None` when postconditions carry no
978    /// matching kind — the postcondition-side arm of the (precondition,
979    /// postcondition, condition-union) first-distinct-kind triad on
980    /// [`Boundary`]. Thin typed delegate to
981    /// [`ConditionSliceExt::first_distinct_kind`] over
982    /// [`Self::postconditions`].
983    ///
984    /// Peer of [`Self::first_distinct_precondition_kind`]. See that
985    /// method for the full rationale — the two methods share ONE lift
986    /// motivation, ONE fail-before-pass-after composition-law pin, and
987    /// ONE two-surface parity contract with the ephemeral sugar type
988    /// via
989    /// [`crate::ephemeral::EphemeralSpec::first_distinct_postcondition_kind`].
990    #[must_use]
991    pub fn first_distinct_postcondition_kind(&self) -> Option<ConditionKind> {
992        self.postconditions.first_distinct_kind()
993    }
994
995    /// Earliest [`ConditionKind::ALL`] entry ABSENT from
996    /// `preconditions ∪ postconditions`, or `None` when the union
997    /// carries every variant — the union arm of the (precondition,
998    /// postcondition, condition-union) first-missing-kind triad on
999    /// [`Boundary`].
1000    ///
1001    /// # Composed body
1002    ///
1003    /// `ConditionKind::ALL.iter().copied().find(|k|
1004    /// !self.has_condition_kind(*k))` — a closed-set walk composed
1005    /// against the two-slice union primitive
1006    /// [`Self::has_condition_kind`] under a NEGATED predicate that
1007    /// SHORT-CIRCUITS at the earliest empty slot. Byte-identical to the
1008    /// trait-level [`ConditionSliceExt::first_missing_kind`] but
1009    /// reaching through the boundary's two-slice union rather than a
1010    /// single slice. Equivalent to
1011    /// `self.missing_condition_kinds().first().copied()` without
1012    /// materializing the intermediate `Vec<ConditionKind>`.
1013    ///
1014    /// # Sibling to [`Self::missing_condition_kinds`] /
1015    /// [`Self::missing_condition_kind_count`]
1016    ///
1017    /// Third scalar projection of the closed-set-complement widened
1018    /// primitive on the boundary-union surface. Byte-for-byte peer of
1019    /// [`Self::first_distinct_condition_kind`] one axis over under a
1020    /// negated predicate: where `first_distinct_condition_kind` scalar-
1021    /// projects the closed-set-INVERSION widened primitive onto its
1022    /// earliest element, this method scalar-projects the closed-set-
1023    /// COMPLEMENT widened primitive onto its earliest element.
1024    ///
1025    /// # Compounding
1026    ///
1027    /// A future coherence check that surfaces "boundary starts missing
1028    /// ProcessPhase" reads `spec.boundary.first_missing_condition_kind()
1029    /// == Some(ConditionKind::ProcessPhase)` at ONE call site rather
1030    /// than paying for `spec.boundary.missing_condition_kinds().first()
1031    /// == Some(&ConditionKind::ProcessPhase)` (with its intermediate
1032    /// heap allocation). An operator-facing "first still-unfilled
1033    /// closed-loop kind" audit reaches this ONE substrate site rather
1034    /// than restating the negated closed-set walk at every consumer.
1035    ///
1036    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition
1037    /// preserves proofs — the complement-earliest-element projection
1038    /// composes the SAME closed-set walk on both this boundary surface
1039    /// and the slice-level substrate primitive under short-circuit
1040    /// semantics with a negated predicate). THEORY.md §VI.1
1041    /// (generation over composition — a new [`ConditionKind`] variant
1042    /// added to `ALL` reaches this primitive mechanically through the
1043    /// closed-set walk).
1044    #[must_use]
1045    pub fn first_missing_condition_kind(&self) -> Option<ConditionKind> {
1046        ConditionKind::ALL
1047            .iter()
1048            .copied()
1049            .find(|k| !self.has_condition_kind(*k))
1050    }
1051
1052    /// Earliest [`ConditionKind::ALL`] entry ABSENT from
1053    /// [`Self::preconditions`], or `None` when preconditions carry
1054    /// every variant — the precondition-side arm of the (precondition,
1055    /// postcondition, condition-union) first-missing-kind triad on
1056    /// [`Boundary`]. Thin typed delegate to
1057    /// [`ConditionSliceExt::first_missing_kind`] over
1058    /// [`Self::preconditions`].
1059    ///
1060    /// Peer of [`Self::first_missing_postcondition_kind`] on the
1061    /// (precondition, postcondition) partition of the boundary's two
1062    /// condition-vector slots; both peers compose against the SAME
1063    /// slice-level substrate primitive so a regression at the per-slice
1064    /// negated short-circuit walk fails at that primitive's tests
1065    /// rather than as silent drift at either struct-level arm.
1066    #[must_use]
1067    pub fn first_missing_precondition_kind(&self) -> Option<ConditionKind> {
1068        self.preconditions.first_missing_kind()
1069    }
1070
1071    /// Earliest [`ConditionKind::ALL`] entry ABSENT from
1072    /// [`Self::postconditions`], or `None` when postconditions carry
1073    /// every variant — the postcondition-side arm of the (precondition,
1074    /// postcondition, condition-union) first-missing-kind triad on
1075    /// [`Boundary`]. Thin typed delegate to
1076    /// [`ConditionSliceExt::first_missing_kind`] over
1077    /// [`Self::postconditions`].
1078    ///
1079    /// Peer of [`Self::first_missing_precondition_kind`]. See that
1080    /// method for the full rationale — the two methods share ONE lift
1081    /// motivation, ONE fail-before-pass-after composition-law pin, and
1082    /// ONE two-surface parity contract with the ephemeral sugar type
1083    /// via
1084    /// [`crate::ephemeral::EphemeralSpec::first_missing_postcondition_kind`].
1085    #[must_use]
1086    pub fn first_missing_postcondition_kind(&self) -> Option<ConditionKind> {
1087        self.postconditions.first_missing_kind()
1088    }
1089
1090    /// Latest [`ConditionKind::ALL`] entry present in
1091    /// `preconditions ∪ postconditions`, or `None` when neither side
1092    /// populates any variant — the union arm of the (precondition,
1093    /// postcondition, condition-union) last-distinct-kind triad on
1094    /// [`Boundary`].
1095    ///
1096    /// # Composed body
1097    ///
1098    /// `ConditionKind::ALL.iter().rev().copied().find(|k|
1099    /// self.has_condition_kind(*k))` — a REVERSED closed-set walk
1100    /// composed against the two-slice union primitive
1101    /// [`Self::has_condition_kind`] that SHORT-CIRCUITS at the latest
1102    /// match. Byte-identical to the trait-level
1103    /// [`ConditionSliceExt::last_distinct_kind`] but reaching through
1104    /// the boundary's two-slice union rather than a single slice.
1105    /// Equivalent to `self.distinct_condition_kinds().last().copied()`
1106    /// without materializing the intermediate `Vec<ConditionKind>`.
1107    ///
1108    /// # Sibling to [`Self::first_distinct_condition_kind`]
1109    ///
1110    /// Time-reversed peer of the earliest-element scalar projection
1111    /// under the SAME two-slice union predicate. Together with
1112    /// `first_distinct_condition_kind` and the two `_missing_*` peers
1113    /// the four scalar-endpoint projections close the "endpoint of
1114    /// closed-set-inversion/complement widened primitive" refinement
1115    /// axis on the boundary-union surface.
1116    ///
1117    /// # Compounding
1118    ///
1119    /// A future coherence check that surfaces "boundary ends with
1120    /// ClosedLoopAuth" reads `spec.boundary.last_distinct_condition_kind()
1121    /// == Some(ConditionKind::ClosedLoopAuth)` at ONE call site rather
1122    /// than paying for `spec.boundary.distinct_condition_kinds().last()
1123    /// == Some(&…)` with its intermediate heap allocation. A future
1124    /// require-tag classifier arm that publishes the latest distinct
1125    /// kind as a scalar (`condition-kinds-last-distinct-<kind>`) reaches
1126    /// this ONE primitive without allocating.
1127    ///
1128    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
1129    /// preserves proofs (the latest-element projection composes the
1130    /// SAME reversed closed-set walk on both this boundary surface and
1131    /// the slice-level substrate primitive under short-circuit
1132    /// semantics). THEORY.md §VI.1 — generation over composition (a
1133    /// new [`ConditionKind`] variant added to `ALL` reaches this
1134    /// primitive mechanically through the reversed closed-set walk).
1135    #[must_use]
1136    pub fn last_distinct_condition_kind(&self) -> Option<ConditionKind> {
1137        ConditionKind::ALL
1138            .iter()
1139            .rev()
1140            .copied()
1141            .find(|k| self.has_condition_kind(*k))
1142    }
1143
1144    /// Latest [`ConditionKind::ALL`] entry present in
1145    /// [`Self::preconditions`], or `None` when preconditions carry no
1146    /// matching kind — the precondition-side arm of the (precondition,
1147    /// postcondition, condition-union) last-distinct-kind triad on
1148    /// [`Boundary`]. Thin typed delegate to
1149    /// [`ConditionSliceExt::last_distinct_kind`] over
1150    /// [`Self::preconditions`].
1151    ///
1152    /// Peer of [`Self::last_distinct_postcondition_kind`] on the
1153    /// (precondition, postcondition) partition of the boundary's two
1154    /// condition-vector slots; both peers compose against the SAME
1155    /// slice-level substrate primitive so a regression at the per-
1156    /// slice REVERSED short-circuit walk fails at that primitive's
1157    /// tests rather than as silent drift at either struct-level arm.
1158    #[must_use]
1159    pub fn last_distinct_precondition_kind(&self) -> Option<ConditionKind> {
1160        self.preconditions.last_distinct_kind()
1161    }
1162
1163    /// Latest [`ConditionKind::ALL`] entry present in
1164    /// [`Self::postconditions`], or `None` when postconditions carry
1165    /// no matching kind — the postcondition-side arm of the
1166    /// (precondition, postcondition, condition-union) last-distinct-
1167    /// kind triad on [`Boundary`]. Thin typed delegate to
1168    /// [`ConditionSliceExt::last_distinct_kind`] over
1169    /// [`Self::postconditions`].
1170    ///
1171    /// Peer of [`Self::last_distinct_precondition_kind`]. See that
1172    /// method for the full rationale — the two methods share ONE lift
1173    /// motivation, ONE fail-before-pass-after composition-law pin, and
1174    /// ONE two-surface parity contract with the ephemeral sugar type
1175    /// via
1176    /// [`crate::ephemeral::EphemeralSpec::last_distinct_postcondition_kind`].
1177    #[must_use]
1178    pub fn last_distinct_postcondition_kind(&self) -> Option<ConditionKind> {
1179        self.postconditions.last_distinct_kind()
1180    }
1181
1182    /// Latest [`ConditionKind::ALL`] entry ABSENT from
1183    /// `preconditions ∪ postconditions`, or `None` when the union
1184    /// carries every variant — the union arm of the (precondition,
1185    /// postcondition, condition-union) last-missing-kind triad on
1186    /// [`Boundary`].
1187    ///
1188    /// # Composed body
1189    ///
1190    /// `ConditionKind::ALL.iter().rev().copied().find(|k|
1191    /// !self.has_condition_kind(*k))` — a REVERSED closed-set walk
1192    /// composed against the two-slice union primitive
1193    /// [`Self::has_condition_kind`] under a NEGATED predicate that
1194    /// SHORT-CIRCUITS at the latest empty slot. Byte-identical to the
1195    /// trait-level [`ConditionSliceExt::last_missing_kind`] but
1196    /// reaching through the boundary's two-slice union rather than a
1197    /// single slice. Equivalent to
1198    /// `self.missing_condition_kinds().last().copied()` without
1199    /// materializing the intermediate `Vec<ConditionKind>`.
1200    ///
1201    /// # Sibling to [`Self::first_missing_condition_kind`]
1202    ///
1203    /// Time-reversed peer of the earliest-element scalar projection
1204    /// under the SAME negated two-slice union predicate. Fourth
1205    /// scalar projection on the closed-set-complement axis on the
1206    /// boundary-union surface (first, count, missing_kinds already
1207    /// shipped; this method closes the endpoint pair on the
1208    /// complement side).
1209    ///
1210    /// # Compounding
1211    ///
1212    /// A future coherence check that surfaces "boundary is latest-
1213    /// missing PromQL" reads
1214    /// `spec.boundary.last_missing_condition_kind() ==
1215    /// Some(ConditionKind::PromQL)` at ONE call site rather than
1216    /// paying for `spec.boundary.missing_condition_kinds().last()`
1217    /// with its intermediate heap allocation. An operator-facing
1218    /// "last still-unfilled closed-loop kind" audit reaches this ONE
1219    /// substrate site rather than restating the negated reversed
1220    /// closed-set walk at every consumer.
1221    ///
1222    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition
1223    /// preserves proofs — the complement-latest-element projection
1224    /// composes the SAME reversed closed-set walk on both this
1225    /// boundary surface and the slice-level substrate primitive
1226    /// under short-circuit semantics with a negated predicate).
1227    /// THEORY.md §VI.1 (generation over composition — a new
1228    /// [`ConditionKind`] variant added to `ALL` reaches this
1229    /// primitive mechanically through the reversed closed-set walk).
1230    #[must_use]
1231    pub fn last_missing_condition_kind(&self) -> Option<ConditionKind> {
1232        ConditionKind::ALL
1233            .iter()
1234            .rev()
1235            .copied()
1236            .find(|k| !self.has_condition_kind(*k))
1237    }
1238
1239    /// Latest [`ConditionKind::ALL`] entry ABSENT from
1240    /// [`Self::preconditions`], or `None` when preconditions carry
1241    /// every variant — the precondition-side arm of the (precondition,
1242    /// postcondition, condition-union) last-missing-kind triad on
1243    /// [`Boundary`]. Thin typed delegate to
1244    /// [`ConditionSliceExt::last_missing_kind`] over
1245    /// [`Self::preconditions`].
1246    ///
1247    /// Peer of [`Self::last_missing_postcondition_kind`] on the
1248    /// (precondition, postcondition) partition of the boundary's two
1249    /// condition-vector slots; both peers compose against the SAME
1250    /// slice-level substrate primitive so a regression at the per-
1251    /// slice negated REVERSED short-circuit walk fails at that
1252    /// primitive's tests rather than as silent drift at either
1253    /// struct-level arm.
1254    #[must_use]
1255    pub fn last_missing_precondition_kind(&self) -> Option<ConditionKind> {
1256        self.preconditions.last_missing_kind()
1257    }
1258
1259    /// Latest [`ConditionKind::ALL`] entry ABSENT from
1260    /// [`Self::postconditions`], or `None` when postconditions carry
1261    /// every variant — the postcondition-side arm of the (precondition,
1262    /// postcondition, condition-union) last-missing-kind triad on
1263    /// [`Boundary`]. Thin typed delegate to
1264    /// [`ConditionSliceExt::last_missing_kind`] over
1265    /// [`Self::postconditions`].
1266    ///
1267    /// Peer of [`Self::last_missing_precondition_kind`]. See that
1268    /// method for the full rationale — the two methods share ONE lift
1269    /// motivation, ONE fail-before-pass-after composition-law pin, and
1270    /// ONE two-surface parity contract with the ephemeral sugar type
1271    /// via
1272    /// [`crate::ephemeral::EphemeralSpec::last_missing_postcondition_kind`].
1273    #[must_use]
1274    pub fn last_missing_postcondition_kind(&self) -> Option<ConditionKind> {
1275        self.postconditions.last_missing_kind()
1276    }
1277
1278    /// `true` iff `preconditions ∪ postconditions` carries every
1279    /// [`ConditionKind::ALL`] variant at least once — the union arm
1280    /// of the (precondition, postcondition, condition-union)
1281    /// saturation-predicate triad on [`Boundary`].
1282    ///
1283    /// # Composed body
1284    ///
1285    /// `ConditionKind::ALL.iter().all(|k| self.has_condition_kind(*k))`
1286    /// — a SHORT-CIRCUITING closed-set walk composed against the
1287    /// two-slice union primitive [`Self::has_condition_kind`], byte-
1288    /// identical to the trait-level [`ConditionSliceExt::is_kind_saturated`]
1289    /// but reaching through the boundary's two-slice union rather than
1290    /// a single slice. Equivalent to `self.missing_condition_kinds()
1291    /// .is_empty()` without materializing the `Vec<ConditionKind>`, and
1292    /// to `self.missing_condition_kind_count() == 0` without paying for
1293    /// the counter walk on every arm.
1294    ///
1295    /// # Peer on the ephemeral surface — [`crate::ephemeral::EphemeralSpec::is_condition_kind_saturated`]
1296    ///
1297    /// Byte-identical signature `(&Self) -> bool`, byte-identical
1298    /// closed-set-walk body, on the sugar-surface type whose pre/post
1299    /// condition vectors live directly on the struct. Both methods
1300    /// compose against the SAME slice-level substrate primitive
1301    /// [`ConditionSliceExt::is_kind_saturated`] via the two-slice
1302    /// union composed through [`Self::has_condition_kind`] — a
1303    /// regression at the per-slice `all` short-circuit fails at that
1304    /// primitive's tests rather than as silent drift at either
1305    /// struct-level saturation caller.
1306    ///
1307    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
1308    /// preserves proofs (the saturation-endpoint projection composes
1309    /// the SAME closed-set walk on both this boundary surface and the
1310    /// slice-level substrate primitive under short-circuit semantics).
1311    /// THEORY.md §VI.1 — generation over composition (a new
1312    /// [`ConditionKind`] variant added to `ALL` reaches this primitive
1313    /// mechanically through the `all` short-circuit).
1314    #[must_use]
1315    pub fn is_condition_kind_saturated(&self) -> bool {
1316        ConditionKind::ALL
1317            .iter()
1318            .all(|k| self.has_condition_kind(*k))
1319    }
1320
1321    /// `true` iff [`Self::preconditions`] carries every
1322    /// [`ConditionKind::ALL`] variant at least once — the precondition-
1323    /// side arm of the (precondition, postcondition, condition-union)
1324    /// saturation-predicate triad on [`Boundary`]. Thin typed delegate
1325    /// to [`ConditionSliceExt::is_kind_saturated`] over
1326    /// [`Self::preconditions`].
1327    ///
1328    /// Peer of [`Self::is_postcondition_kind_saturated`] on the
1329    /// (precondition, postcondition) partition of the boundary's two
1330    /// condition-vector slots; both peers compose against the SAME
1331    /// slice-level substrate primitive so a regression at the per-
1332    /// slice `all` short-circuit fails at that primitive's tests
1333    /// rather than as silent drift at either struct-level arm.
1334    #[must_use]
1335    pub fn is_precondition_kind_saturated(&self) -> bool {
1336        self.preconditions.is_kind_saturated()
1337    }
1338
1339    /// `true` iff [`Self::postconditions`] carries every
1340    /// [`ConditionKind::ALL`] variant at least once — the postcondition-
1341    /// side arm of the (precondition, postcondition, condition-union)
1342    /// saturation-predicate triad on [`Boundary`]. Thin typed delegate
1343    /// to [`ConditionSliceExt::is_kind_saturated`] over
1344    /// [`Self::postconditions`].
1345    ///
1346    /// Peer of [`Self::is_precondition_kind_saturated`]. See that
1347    /// method for the full rationale — the two methods share ONE lift
1348    /// motivation, ONE fail-before-pass-after composition-law pin, and
1349    /// ONE two-surface parity contract with the ephemeral sugar type
1350    /// via
1351    /// [`crate::ephemeral::EphemeralSpec::is_postcondition_kind_saturated`].
1352    #[must_use]
1353    pub fn is_postcondition_kind_saturated(&self) -> bool {
1354        self.postconditions.is_kind_saturated()
1355    }
1356
1357    /// `true` iff `preconditions ∪ postconditions` is MISSING at least
1358    /// one [`ConditionKind::ALL`] variant — the union arm of the
1359    /// (precondition, postcondition, condition-union) at-least-one
1360    /// halfspace triad on [`Boundary`], byte-for-byte peer of the
1361    /// saturation-predicate triad
1362    /// [`Self::is_condition_kind_saturated`] under a definitional
1363    /// negation.
1364    ///
1365    /// # Composed body
1366    ///
1367    /// `!self.is_condition_kind_saturated()` — the definitional
1368    /// negation of the two-slice union saturation primitive. The
1369    /// underlying `ConditionKind::ALL.iter().all(has_condition_kind)`
1370    /// walk returns `false` at the FIRST missing kind (yielding `true`
1371    /// here) WITHOUT materializing
1372    /// [`Self::missing_condition_kinds`]'s `Vec` and WITHOUT walking
1373    /// every entry to build [`Self::missing_condition_kind_count`]'s
1374    /// scalar. Strictly cheaper than either widened primitive on every
1375    /// partially-populated arm.
1376    ///
1377    /// # Peer on the ephemeral surface — [`crate::ephemeral::EphemeralSpec::has_any_missing_condition_kind`]
1378    ///
1379    /// Byte-identical signature `(&Self) -> bool`, byte-identical
1380    /// `!self.is_condition_kind_saturated()` body, on the sugar-surface
1381    /// type whose pre/post condition vectors live directly on the
1382    /// struct. Both methods compose against the SAME slice-level
1383    /// substrate primitive [`ConditionSliceExt::has_any_missing_kind`]
1384    /// via the two-slice union composed through
1385    /// [`Self::is_condition_kind_saturated`] — a regression at the
1386    /// per-slice `all` short-circuit fails at that primitive's tests
1387    /// rather than as silent drift at either struct-level at-least-one
1388    /// halfspace caller.
1389    ///
1390    /// # Compounding
1391    ///
1392    /// A `has-any-missing-kind` require-tag classifier arm — byte-
1393    /// for-byte peer of the tagged-union `has-any-missing-kind`
1394    /// classifier one struct-layer up + the saturation-predicate
1395    /// triad's negated dual — reaches this primitive at ONE call
1396    /// site rather than negating `boundary.is_condition_kind_saturated()`
1397    /// at the callsite or restating
1398    /// `boundary.missing_condition_kind_count() > 0` (which walks
1399    /// every slot to count) or
1400    /// `!boundary.missing_condition_kinds().is_empty()` (which
1401    /// allocates the Vec before the negated emptiness check).
1402    ///
1403    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition
1404    /// preserves proofs — the at-least-one halfspace projection
1405    /// composes the SAME two-slice union negation on both this
1406    /// boundary surface and the slice-level substrate primitive under
1407    /// definitional negation). THEORY.md §VI.1 (generation over
1408    /// composition — a new [`ConditionKind`] variant reaches both
1409    /// surfaces' at-least-one halfspace triads mechanically through
1410    /// the delegated union primitive).
1411    #[must_use]
1412    pub fn has_any_missing_condition_kind(&self) -> bool {
1413        !self.is_condition_kind_saturated()
1414    }
1415
1416    /// `true` iff [`Self::preconditions`] is MISSING at least one
1417    /// [`ConditionKind::ALL`] variant — the precondition-side arm of
1418    /// the (precondition, postcondition, condition-union) at-least-
1419    /// one halfspace triad on [`Boundary`]. Thin typed delegate to
1420    /// [`ConditionSliceExt::has_any_missing_kind`] over
1421    /// [`Self::preconditions`].
1422    ///
1423    /// Peer of [`Self::has_any_missing_postcondition_kind`] on the
1424    /// (precondition, postcondition) partition of the boundary's two
1425    /// condition-vector slots; both peers compose against the SAME
1426    /// slice-level substrate primitive so a regression at the per-
1427    /// slice `all` short-circuit under negation fails at that
1428    /// primitive's tests rather than as silent drift at either
1429    /// struct-level arm.
1430    #[must_use]
1431    pub fn has_any_missing_precondition_kind(&self) -> bool {
1432        self.preconditions.has_any_missing_kind()
1433    }
1434
1435    /// `true` iff [`Self::postconditions`] is MISSING at least one
1436    /// [`ConditionKind::ALL`] variant — the postcondition-side arm of
1437    /// the (precondition, postcondition, condition-union) at-least-
1438    /// one halfspace triad on [`Boundary`]. Thin typed delegate to
1439    /// [`ConditionSliceExt::has_any_missing_kind`] over
1440    /// [`Self::postconditions`].
1441    ///
1442    /// Peer of [`Self::has_any_missing_precondition_kind`]. See that
1443    /// method for the full rationale — the two methods share ONE lift
1444    /// motivation, ONE fail-before-pass-after composition-law pin, and
1445    /// ONE two-surface parity contract with the ephemeral sugar type
1446    /// via
1447    /// [`crate::ephemeral::EphemeralSpec::has_any_missing_postcondition_kind`].
1448    #[must_use]
1449    pub fn has_any_missing_postcondition_kind(&self) -> bool {
1450        self.postconditions.has_any_missing_kind()
1451    }
1452
1453    /// `true` iff `preconditions ∪ postconditions` is MISSING EXACTLY
1454    /// ONE [`ConditionKind::ALL`] variant — the union arm of the
1455    /// (precondition, postcondition, condition-union) cardinality-mid-
1456    /// endpoint triad on [`Boundary`] closing the "one hole remaining"
1457    /// near-saturation-endpoint on the union of the two condition
1458    /// slots. The near-saturation-endpoint Boolean fast-path peer of
1459    /// [`Self::is_condition_kind_saturated`] on the union axis: where
1460    /// the saturation-endpoint predicate answers "is the union covered
1461    /// by every ALL variant?", `has_unique_missing_condition_kind`
1462    /// answers "is the union one kind away from covered?".
1463    ///
1464    /// Composed body: constructs a two-step-short-circuit walk over
1465    /// [`ConditionKind::ALL`] under the [`Self::has_condition_kind`]
1466    /// union primitive negated — the first missing union arm surfaces,
1467    /// then the walk short-circuits at the second. Byte-for-byte peer
1468    /// of [`ConditionSliceExt::has_unique_missing_kind`] one slice-
1469    /// layer down, lifted to compose against
1470    /// [`Self::has_condition_kind`]'s pre-OR-post union rather than
1471    /// against a single slice's `has_kind`. A regression at the union
1472    /// primitive fails at the slice-level substrate tests + the union
1473    /// composition-law tests rather than as silent drift here.
1474    ///
1475    /// # Peer on the ephemeral surface — [`crate::ephemeral::EphemeralSpec::has_unique_missing_condition_kind`]
1476    ///
1477    /// Byte-identical signature `(&Self) -> bool`, byte-identical
1478    /// two-step short-circuit body composed against the ephemeral
1479    /// surface's own union primitive. Both methods compose against
1480    /// the SAME slice-level substrate primitive
1481    /// [`ConditionSliceExt::has_unique_missing_kind`] via the two-
1482    /// slice union — a regression at the per-slice near-saturation-
1483    /// endpoint walk fails at that primitive's tests rather than as
1484    /// silent drift at either struct-level near-saturation caller.
1485    ///
1486    /// # Compounding
1487    ///
1488    /// A future operator-facing "one kind away from saturated" gap-
1489    /// analysis diagnostic reads
1490    /// `boundary.has_unique_missing_condition_kind()` at ONE call site
1491    /// rather than restating either `boundary.missing_condition_kind_count() == 1`
1492    /// (which walks every slot to count) or
1493    /// `boundary.missing_condition_kinds().len() == 1` (which
1494    /// allocates the Vec). A `has-unique-missing-condition-kind`
1495    /// require-tag classifier arm reaches this primitive at ONE
1496    /// substrate call — byte-for-byte peer of the tagged-union
1497    /// `has-unique-missing-kind` classifier one struct-layer up.
1498    ///
1499    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition
1500    /// preserves proofs — the cardinality-mid-endpoint projection on
1501    /// the missing axis composes the SAME two-step short-circuit walk
1502    /// under a two-slice union negation on both this boundary surface
1503    /// and the ephemeral surface). THEORY.md §VI.1 (generation over
1504    /// composition — a new [`ConditionKind`] variant reaches both
1505    /// surfaces' cardinality-mid-endpoint triads mechanically through
1506    /// the delegated union primitive).
1507    #[must_use]
1508    pub fn has_unique_missing_condition_kind(&self) -> bool {
1509        let mut it = ConditionKind::ALL
1510            .iter()
1511            .copied()
1512            .filter(|k| !self.has_condition_kind(*k));
1513        it.next().is_some() && it.next().is_none()
1514    }
1515
1516    /// `true` iff [`Self::preconditions`] is MISSING EXACTLY ONE
1517    /// [`ConditionKind::ALL`] variant — the precondition-side arm of
1518    /// the (precondition, postcondition, condition-union) cardinality-
1519    /// mid-endpoint triad on [`Boundary`]. Thin typed delegate to
1520    /// [`ConditionSliceExt::has_unique_missing_kind`] over
1521    /// [`Self::preconditions`].
1522    ///
1523    /// Peer of [`Self::has_unique_missing_postcondition_kind`] on the
1524    /// (precondition, postcondition) partition of the boundary's two
1525    /// condition-vector slots; both peers compose against the SAME
1526    /// slice-level substrate primitive so a regression at the per-
1527    /// slice two-step short-circuit walk under negation fails at that
1528    /// primitive's tests rather than as silent drift at either
1529    /// struct-level arm.
1530    #[must_use]
1531    pub fn has_unique_missing_precondition_kind(&self) -> bool {
1532        self.preconditions.has_unique_missing_kind()
1533    }
1534
1535    /// `true` iff [`Self::postconditions`] is MISSING EXACTLY ONE
1536    /// [`ConditionKind::ALL`] variant — the postcondition-side arm of
1537    /// the (precondition, postcondition, condition-union) cardinality-
1538    /// mid-endpoint triad on [`Boundary`]. Thin typed delegate to
1539    /// [`ConditionSliceExt::has_unique_missing_kind`] over
1540    /// [`Self::postconditions`].
1541    ///
1542    /// Peer of [`Self::has_unique_missing_precondition_kind`]. See
1543    /// that method for the full rationale — the two methods share ONE
1544    /// lift motivation, ONE fail-before-pass-after composition-law
1545    /// pin, and ONE two-surface parity contract with the ephemeral
1546    /// sugar type via
1547    /// [`crate::ephemeral::EphemeralSpec::has_unique_missing_postcondition_kind`].
1548    #[must_use]
1549    pub fn has_unique_missing_postcondition_kind(&self) -> bool {
1550        self.postconditions.has_unique_missing_kind()
1551    }
1552
1553    /// `true` iff `preconditions ∪ postconditions` is MISSING AT
1554    /// LEAST TWO [`ConditionKind::ALL`] variants — the union arm of
1555    /// the (precondition, postcondition, condition-union) cardinality-
1556    /// many-arm triad on [`Boundary`] closing the "≥ 2 holes
1557    /// remaining" arm on the union of the two condition slots. The
1558    /// many-arm Boolean fast-path peer of
1559    /// [`Self::has_unique_missing_condition_kind`] (=1 arm) and
1560    /// [`Self::is_condition_kind_saturated`] (=0 arm) on the union
1561    /// axis, closing the {0, 1, ≥2} trichotomy at the union struct
1562    /// layer.
1563    ///
1564    /// Composed body: constructs a two-step-short-circuit walk over
1565    /// [`ConditionKind::ALL`] under the [`Self::has_condition_kind`]
1566    /// union primitive negated — pulls up to two hits off the
1567    /// filtered iterator; the primitive returns `true` iff BOTH the
1568    /// first and the second are [`Some`]. Byte-for-byte peer of
1569    /// [`ConditionSliceExt::has_multiple_missing_kinds`] one slice-
1570    /// layer down, lifted to compose against
1571    /// [`Self::has_condition_kind`]'s pre-OR-post union rather than
1572    /// against a single slice's `has_kind`. A regression at the union
1573    /// primitive fails at the slice-level substrate tests + the union
1574    /// composition-law tests rather than as silent drift here.
1575    ///
1576    /// # Peer on the ephemeral surface — [`crate::ephemeral::EphemeralSpec::has_multiple_missing_condition_kind`]
1577    ///
1578    /// Byte-identical signature `(&Self) -> bool`, byte-identical
1579    /// two-step short-circuit body composed against the ephemeral
1580    /// surface's own union primitive. Both methods compose against
1581    /// the SAME slice-level substrate primitive
1582    /// [`ConditionSliceExt::has_multiple_missing_kinds`] via the two-
1583    /// slice union — a regression at the per-slice many-arm walk
1584    /// fails at that primitive's tests rather than as silent drift at
1585    /// either struct-level many-missing caller.
1586    ///
1587    /// # Compounding
1588    ///
1589    /// A future operator-facing "≥ 2 dependencies still unfulfilled"
1590    /// gap-analysis diagnostic reads
1591    /// `boundary.has_multiple_missing_condition_kind()` at ONE call
1592    /// site rather than restating
1593    /// `boundary.missing_condition_kind_count() >= 2` (which walks
1594    /// every slot to count) or
1595    /// `boundary.missing_condition_kinds().len() >= 2` (which
1596    /// allocates the Vec). A `has-multiple-missing-condition-kind`
1597    /// require-tag classifier arm reaches this primitive at ONE
1598    /// substrate call — byte-for-byte peer of the tagged-union
1599    /// `has-multiple-missing-kinds` classifier one struct-layer up.
1600    ///
1601    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition
1602    /// preserves proofs — the cardinality-many-arm projection on the
1603    /// missing axis composes the SAME two-step short-circuit walk
1604    /// under a two-slice union negation on both this boundary surface
1605    /// and the ephemeral surface). THEORY.md §VI.1 (generation over
1606    /// composition — a new [`ConditionKind`] variant reaches both
1607    /// surfaces' cardinality-many-arm triads mechanically through the
1608    /// delegated union primitive).
1609    #[must_use]
1610    pub fn has_multiple_missing_condition_kind(&self) -> bool {
1611        let mut it = ConditionKind::ALL
1612            .iter()
1613            .copied()
1614            .filter(|k| !self.has_condition_kind(*k));
1615        it.next().is_some() && it.next().is_some()
1616    }
1617
1618    /// `true` iff [`Self::preconditions`] is MISSING AT LEAST TWO
1619    /// [`ConditionKind::ALL`] variants — the precondition-side arm of
1620    /// the (precondition, postcondition, condition-union) cardinality-
1621    /// many-arm triad on [`Boundary`]. Thin typed delegate to
1622    /// [`ConditionSliceExt::has_multiple_missing_kinds`] over
1623    /// [`Self::preconditions`].
1624    ///
1625    /// Peer of [`Self::has_multiple_missing_postcondition_kind`] on
1626    /// the (precondition, postcondition) partition of the boundary's
1627    /// two condition-vector slots; both peers compose against the
1628    /// SAME slice-level substrate primitive so a regression at the
1629    /// per-slice two-step short-circuit walk under negation fails at
1630    /// that primitive's tests rather than as silent drift at either
1631    /// struct-level arm.
1632    #[must_use]
1633    pub fn has_multiple_missing_precondition_kind(&self) -> bool {
1634        self.preconditions.has_multiple_missing_kinds()
1635    }
1636
1637    /// `true` iff [`Self::postconditions`] is MISSING AT LEAST TWO
1638    /// [`ConditionKind::ALL`] variants — the postcondition-side arm of
1639    /// the (precondition, postcondition, condition-union) cardinality-
1640    /// many-arm triad on [`Boundary`]. Thin typed delegate to
1641    /// [`ConditionSliceExt::has_multiple_missing_kinds`] over
1642    /// [`Self::postconditions`].
1643    ///
1644    /// Peer of [`Self::has_multiple_missing_precondition_kind`]. See
1645    /// that method for the full rationale — the two methods share ONE
1646    /// lift motivation, ONE fail-before-pass-after composition-law
1647    /// pin, and ONE two-surface parity contract with the ephemeral
1648    /// sugar type via
1649    /// [`crate::ephemeral::EphemeralSpec::has_multiple_missing_postcondition_kind`].
1650    #[must_use]
1651    pub fn has_multiple_missing_postcondition_kind(&self) -> bool {
1652        self.postconditions.has_multiple_missing_kinds()
1653    }
1654
1655    /// `true` iff `preconditions ∪ postconditions` is MISSING AT MOST
1656    /// ONE [`ConditionKind::ALL`] variant — the union arm of the
1657    /// (precondition, postcondition, condition-union) cardinality
1658    /// "≤ 1" triad on [`Boundary`] closing the "at most one hole
1659    /// remaining" arm on the union of the two condition slots. The
1660    /// Boolean cardinality "≤ 1" negation peer of
1661    /// [`Self::has_multiple_missing_condition_kind`] (≥ 2 many-arm)
1662    /// under the definitional negation
1663    /// `!has_multiple_missing_condition_kind`, and the trichotomy-
1664    /// union peer of [`Self::is_condition_kind_saturated`] (=0
1665    /// zero-arm) OR [`Self::has_unique_missing_condition_kind`] (=1
1666    /// mid-endpoint) — the arrangement space where the boundary is
1667    /// SATURATED-OR-NEAR-SATURATED (zero or exactly one kind missing
1668    /// across the union of the two slices).
1669    ///
1670    /// Composed body: `!self.has_multiple_missing_condition_kind()` —
1671    /// a definitional negation of the many-arm union primitive. Short-
1672    /// circuits transitively through
1673    /// [`Self::has_multiple_missing_condition_kind`]'s two-step short-
1674    /// circuit walk over [`ConditionKind::ALL`] under negated
1675    /// [`Self::has_condition_kind`] — returns `true` as soon as the
1676    /// many-arm walk stops with fewer than two missing hits, WITHOUT
1677    /// materializing [`Self::missing_condition_kinds`]'s `Vec` and
1678    /// WITHOUT walking every slot to build
1679    /// [`Self::missing_condition_kind_count`]'s scalar. Byte-for-byte
1680    /// peer of [`ConditionSliceExt::has_at_most_one_missing_kind`] one
1681    /// slice-layer down, lifted to compose against
1682    /// [`Self::has_condition_kind`]'s pre-OR-post union rather than
1683    /// against a single slice's `has_kind`. A regression at the union
1684    /// primitive fails at the slice-level substrate tests + the union
1685    /// composition-law tests rather than as silent drift here.
1686    ///
1687    /// # Peer on the ephemeral surface — [`crate::ephemeral::EphemeralSpec::has_at_most_one_missing_condition_kind`]
1688    ///
1689    /// Byte-identical signature `(&Self) -> bool`, byte-identical
1690    /// definitional-negation body composed against the ephemeral
1691    /// surface's own many-arm union primitive. Both methods compose
1692    /// against the SAME slice-level substrate primitive
1693    /// [`ConditionSliceExt::has_at_most_one_missing_kind`] via the
1694    /// two-slice union — a regression at the per-slice "≤ 1" negation
1695    /// fails at that primitive's tests rather than as silent drift at
1696    /// either struct-level near-saturation-or-saturated caller.
1697    ///
1698    /// # Compounding
1699    ///
1700    /// A future operator-facing "at most one dependency still
1701    /// unfulfilled" gap-analysis diagnostic reads
1702    /// `boundary.has_at_most_one_missing_condition_kind()` at ONE call
1703    /// site rather than restating
1704    /// `boundary.missing_condition_kind_count() <= 1` (which walks every
1705    /// slot to count) or `boundary.missing_condition_kinds().len() <= 1`
1706    /// (which allocates the Vec) or the union of the two Booleans
1707    /// `boundary.is_condition_kind_saturated() ||
1708    /// boundary.has_unique_missing_condition_kind()` (which walks the
1709    /// closed-set-complement scan twice). A `has-at-most-one-missing-
1710    /// condition-kind` require-tag classifier arm reaches this
1711    /// primitive at ONE substrate call — byte-for-byte peer of the
1712    /// tagged-union `has-at-most-one-missing-kind` classifier one
1713    /// struct-layer up, closing the {0, 1, ≥ 2, ≤ 1} cardinality-
1714    /// Boolean grid on the missing axis at the Boundary struct layer
1715    /// alongside its sibling `has-multiple-missing-condition-kind`
1716    /// under the Boolean negation axis.
1717    ///
1718    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition
1719    /// preserves proofs — the cardinality "≤ 1" projection on the
1720    /// missing axis composes the SAME definitional negation of the
1721    /// many-arm two-step short-circuit walk on both this boundary
1722    /// surface and the ephemeral surface). THEORY.md §VI.1 (generation
1723    /// over composition — a new [`ConditionKind`] variant reaches both
1724    /// surfaces' cardinality "≤ 1" triads mechanically through the
1725    /// delegated union primitive).
1726    #[must_use]
1727    pub fn has_at_most_one_missing_condition_kind(&self) -> bool {
1728        !self.has_multiple_missing_condition_kind()
1729    }
1730
1731    /// `true` iff [`Self::preconditions`] is MISSING AT MOST ONE
1732    /// [`ConditionKind::ALL`] variant — the precondition-side arm of
1733    /// the (precondition, postcondition, condition-union) cardinality
1734    /// "≤ 1" triad on [`Boundary`]. Thin typed delegate to
1735    /// [`ConditionSliceExt::has_at_most_one_missing_kind`] over
1736    /// [`Self::preconditions`].
1737    ///
1738    /// Peer of [`Self::has_at_most_one_missing_postcondition_kind`]
1739    /// on the (precondition, postcondition) partition of the boundary's
1740    /// two condition-vector slots; both peers compose against the SAME
1741    /// slice-level substrate primitive so a regression at the per-
1742    /// slice "≤ 1" negation of the many-arm walk fails at that
1743    /// primitive's tests rather than as silent drift at either
1744    /// struct-level arm.
1745    #[must_use]
1746    pub fn has_at_most_one_missing_precondition_kind(&self) -> bool {
1747        self.preconditions.has_at_most_one_missing_kind()
1748    }
1749
1750    /// `true` iff [`Self::postconditions`] is MISSING AT MOST ONE
1751    /// [`ConditionKind::ALL`] variant — the postcondition-side arm of
1752    /// the (precondition, postcondition, condition-union) cardinality
1753    /// "≤ 1" triad on [`Boundary`]. Thin typed delegate to
1754    /// [`ConditionSliceExt::has_at_most_one_missing_kind`] over
1755    /// [`Self::postconditions`].
1756    ///
1757    /// Peer of [`Self::has_at_most_one_missing_precondition_kind`].
1758    /// See that method for the full rationale — the two methods share
1759    /// ONE lift motivation, ONE fail-before-pass-after composition-
1760    /// law pin, and ONE two-surface parity contract with the
1761    /// ephemeral sugar type via
1762    /// [`crate::ephemeral::EphemeralSpec::has_at_most_one_missing_postcondition_kind`].
1763    #[must_use]
1764    pub fn has_at_most_one_missing_postcondition_kind(&self) -> bool {
1765        self.postconditions.has_at_most_one_missing_kind()
1766    }
1767
1768    /// `true` iff `preconditions ∪ postconditions` carries NO
1769    /// [`Condition`] with the given [`ConditionKind`] — the union arm
1770    /// of the (precondition, postcondition, condition-union)
1771    /// per-kind-complement triad on [`Boundary`], definitional
1772    /// negation of [`Self::has_condition_kind`].
1773    ///
1774    /// # Composed body
1775    ///
1776    /// `!self.has_condition_kind(kind)` — the definitional negation
1777    /// of the two-slice union primitive. Equivalent to the AND of the
1778    /// two half-slice per-kind-complement arms
1779    /// (`self.lacks_precondition_kind(k) && self.lacks_postcondition_kind(k)`),
1780    /// by the boolean identity `!(a || b) == !a && !b`. Both forms
1781    /// return `true` iff BOTH slices lack the addressed kind; the
1782    /// composed body chosen here short-circuits through the union
1783    /// primitive so a regression at the per-slice presence probe fails
1784    /// at that primitive's tests rather than as silent drift at either
1785    /// half-slice complement arm. Equivalent to
1786    /// `self.missing_condition_kinds().contains(&kind)` without
1787    /// materializing the closed-set-complement Vec at every callsite.
1788    ///
1789    /// # Peer on the ephemeral surface — [`crate::ephemeral::EphemeralSpec::lacks_condition_kind`]
1790    ///
1791    /// Byte-identical signature `(&Self, ConditionKind) -> bool`,
1792    /// byte-identical `!self.has_condition_kind(kind)` body, on the
1793    /// sugar-surface type whose pre/post condition vectors live
1794    /// directly on the struct. Both methods compose against the SAME
1795    /// slice-level substrate primitive
1796    /// [`ConditionSliceExt::lacks_kind`] via the two-slice union
1797    /// composed through [`Self::has_condition_kind`] — a regression
1798    /// at the per-slice negation fails at that primitive's tests
1799    /// rather than as silent drift at either struct-level complement
1800    /// caller.
1801    ///
1802    /// # Compounding
1803    ///
1804    /// A `lacks-<kind>` require-tag classifier arm — byte-for-byte
1805    /// peer of the tagged-union `lacks-<kind>` classifier one struct-
1806    /// layer up + the future `condition-<kind>` require-tag family's
1807    /// negated dual — reaches this primitive at ONE call site rather
1808    /// than negating `boundary.has_condition_kind(k)` at the callsite
1809    /// or restating `boundary.missing_condition_kinds().contains(&k)`
1810    /// with its allocation.
1811    ///
1812    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition
1813    /// preserves proofs — the per-kind closed-set-complement
1814    /// projection composes the SAME two-slice union negation on both
1815    /// this boundary surface and the slice-level substrate primitive
1816    /// under definitional negation). THEORY.md §VI.1 (generation over
1817    /// composition — a new [`ConditionKind`] variant reaches both
1818    /// surfaces' complement-triads mechanically through the delegated
1819    /// union primitive).
1820    #[must_use]
1821    pub fn lacks_condition_kind(&self, kind: ConditionKind) -> bool {
1822        !self.has_condition_kind(kind)
1823    }
1824
1825    /// `true` iff [`Self::preconditions`] carries NO [`Condition`]
1826    /// with the given [`ConditionKind`] — the precondition-side arm
1827    /// of the (precondition, postcondition, condition-union)
1828    /// per-kind-complement triad on [`Boundary`]. Thin typed delegate
1829    /// to [`ConditionSliceExt::lacks_kind`] over
1830    /// [`Self::preconditions`].
1831    ///
1832    /// Peer of [`Self::lacks_postcondition_kind`] on the (precondition,
1833    /// postcondition) partition of the boundary's two condition-vector
1834    /// slots; both peers compose against the SAME slice-level substrate
1835    /// primitive so a regression at the per-slice negation fails at
1836    /// that primitive's tests rather than as silent drift at either
1837    /// struct-level arm.
1838    #[must_use]
1839    pub fn lacks_precondition_kind(&self, kind: ConditionKind) -> bool {
1840        self.preconditions.lacks_kind(kind)
1841    }
1842
1843    /// `true` iff [`Self::postconditions`] carries NO [`Condition`]
1844    /// with the given [`ConditionKind`] — the postcondition-side arm
1845    /// of the (precondition, postcondition, condition-union)
1846    /// per-kind-complement triad on [`Boundary`]. Thin typed delegate
1847    /// to [`ConditionSliceExt::lacks_kind`] over
1848    /// [`Self::postconditions`].
1849    ///
1850    /// Peer of [`Self::lacks_precondition_kind`]. See that method for
1851    /// the full rationale — the two methods share ONE lift motivation,
1852    /// ONE fail-before-pass-after composition-law pin, and ONE
1853    /// two-surface parity contract with the ephemeral sugar type via
1854    /// [`crate::ephemeral::EphemeralSpec::lacks_postcondition_kind`].
1855    #[must_use]
1856    pub fn lacks_postcondition_kind(&self, kind: ConditionKind) -> bool {
1857        self.postconditions.lacks_kind(kind)
1858    }
1859}
1860
1861/// Slice-level `(ConditionKind, presence)` probe on any `&[Condition]`
1862/// — the ONE substrate primitive that owns the
1863/// `.iter().any(|c| c.kind == K)` walk shape both current production
1864/// sites hand-authored past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
1865/// threshold. Callers compose the two-half union at their site
1866/// ([`Boundary::has_condition_kind`] on `preconditions ∪
1867/// postconditions`) or on ONE half only (the ephemeral require-tag
1868/// classifier's `closed-loop-auth` arm on `spec.postconditions`) —
1869/// the primitive owns ONLY the per-slice walk, so the composition
1870/// choice stays typed at the caller.
1871///
1872/// # Why lift
1873///
1874/// Pre-lift the `.iter().any(|c| c.kind == K)` walk lived
1875/// hand-authored at THREE production sites: twice inside
1876/// [`Boundary::has_condition_kind`]'s union (pre + post), once at
1877/// `evaluate_ephemeral_require_tag`'s `closed-loop-auth` arm in
1878/// `tatara-reconciler::bin::tatara-check` (with `matches!` sugar
1879/// instead of `==`, but the same predicate). The (`&[Condition]`,
1880/// `ConditionKind`) → `bool` shape is the substrate primitive: a
1881/// future consumer that walks a `Vec<Condition>` (a coherence check
1882/// that verifies "every `ClosedLoopAuth` postcondition carries an
1883/// `issuer` param key", an editor completion listing which
1884/// [`ConditionKind`] arms appear on ONE side only, a hypothetical
1885/// `postcondition-<kind>` require-tag prefix family that dispatches
1886/// on `postconditions` alone — the peer of the existing
1887/// `condition-<kind>` family that dispatches on the pre ∪ post union
1888/// via [`Boundary::has_condition_kind`]) reaches this ONE primitive
1889/// through `slice.has_kind(k)` instead of restating the `.iter().any`
1890/// closure body.
1891///
1892/// # Sibling to [`Boundary::has_condition_kind`]
1893///
1894/// Same axis, one refinement lower: `Boundary::has_condition_kind` is
1895/// the two-slice-union probe; `has_kind` here is the one-slice probe
1896/// the union composes twice. A future normalization at the presence
1897/// probe shape (widening the return to `Option<&Condition>` for
1898/// deeper diagnostics, adding a debug-build assertion on redundant
1899/// duplicates, switching to a linear scan that also counts matches)
1900/// lands at ONE site here — both [`Boundary::has_condition_kind`] +
1901/// every downstream `slice.has_kind(K)` callsite pick it up
1902/// mechanically.
1903///
1904/// # Compounding
1905///
1906/// [`Self::find_kind`] is the widened primitive returning
1907/// `Option<&Condition>` that both `has_kind` (`self.find_kind(k).
1908/// is_some()`, the default body) and future diagnostic consumers
1909/// compose against. A `has_kind_matching(|&Condition| -> bool)`
1910/// predicate extension similarly lands as ONE new default method on
1911/// this trait — the closed-set discriminator case becomes `has_kind(k)
1912/// == self.has_kind_matching(|c| c.kind == k)` by construction, so a
1913/// regression that drifted one from the other becomes structurally
1914/// impossible past the trait boundary.
1915///
1916/// Theory anchor: THEORY.md §II.1 invariant 5 — composition preserves
1917/// proofs; the per-slice walk lives at ONE substrate site so the
1918/// two-half union in [`Boundary`] and the one-half probe on
1919/// [`crate::ephemeral::EphemeralSpec::postconditions`] compose
1920/// through the SAME primitive. THEORY.md §VI.1 — generation over
1921/// composition; a future `Vec<Condition>` consumer reaches the
1922/// primitive through `slice.has_kind(k)` with no per-caller
1923/// restatement of the `.iter().any(|c| c.kind == K)` closure body.
1924pub trait ConditionSliceExt {
1925    /// Returns an iterator yielding every [`Condition`] in this slice
1926    /// whose [`Condition::kind`] equals `kind`, in slice order — the
1927    /// ONE widened primitive on the slice-level presence-probe axis
1928    /// that both [`Self::find_kind`] (via the default
1929    /// `iter_kind(k).next()` body) and [`Self::has_kind`] (via the
1930    /// transitive `find_kind(k).is_some()` default) compose against.
1931    ///
1932    /// # Sibling to [`Self::find_kind`]
1933    ///
1934    /// One refinement wider: `find_kind` collapses the return to
1935    /// `Option<&Condition>` (yielding only the earliest match);
1936    /// `iter_kind` returns the whole match stream so callers can
1937    /// [`count`](Iterator::count) it, [`collect`](Iterator::collect)
1938    /// it into a `Vec<&Condition>`, ask for the
1939    /// [`nth`](Iterator::nth) element, or compose it with any other
1940    /// std iterator adaptor without re-walking the slice. The default
1941    /// body of `find_kind` is `self.iter_kind(kind).next()` — the
1942    /// two methods share ONE walk semantics by construction, so a
1943    /// regression that drifted the first-match probe from the
1944    /// widened stream becomes structurally impossible past the
1945    /// trait boundary.
1946    ///
1947    /// # Semantics
1948    ///
1949    /// Yields `&c` for each `c` in this slice with `c.kind == kind`,
1950    /// in slice order — a slice that carries multiple matches yields
1951    /// each in turn (the composition law
1952    /// `find_kind(k) == iter_kind(k).next()` binds the first match
1953    /// to the earliest position). An empty slice, or a slice with no
1954    /// matching kind, yields nothing. Byte-for-byte equivalent to
1955    /// `self.iter().filter(|c| c.kind == kind)`.
1956    ///
1957    /// # Compounding
1958    ///
1959    /// A future coherence check that verifies "each
1960    /// [`ConditionKind`] appears at most once per side" reads
1961    /// `slice.iter_kind(k).nth(1).is_none()` at ONE call site
1962    /// rather than restating the count-with-filter closure body.
1963    /// A future diagnostic that enumerates every match of a kind
1964    /// (an operator-facing "3 PromQL preconditions matched" message,
1965    /// an audit dump listing every match of a repeated kind) reaches
1966    /// this ONE primitive through `slice.iter_kind(k).collect()`
1967    /// rather than re-walking the slice with `.iter().filter(...)`
1968    /// at the callsite. The presence-probe axis now carries three
1969    /// refinements (bool via `has_kind`, `Option<&Condition>` via
1970    /// `find_kind`, `impl Iterator<Item = &Condition>` via
1971    /// `iter_kind`) at ONE typed algebra surface — every downstream
1972    /// consumer picks the coarsest one that answers its question and
1973    /// the coarser ones stay compositionally derived from this
1974    /// primitive.
1975    fn iter_kind(&self, kind: ConditionKind) -> KindMatches<'_>;
1976
1977    /// Returns the first [`Condition`] in this slice that carries the
1978    /// given [`ConditionKind`], or `None` if none matches. Default
1979    /// body: `self.iter_kind(kind).next()` — a thin projection of the
1980    /// widened primitive [`Self::iter_kind`] onto its first element.
1981    /// The composition law `find_kind(k) == iter_kind(k).next()`
1982    /// binds the first-match probe to the widened stream at the
1983    /// trait's default body.
1984    ///
1985    /// # Sibling to [`Self::has_kind`]
1986    ///
1987    /// One refinement wider: `has_kind` collapses the return to a
1988    /// `bool`; `find_kind` returns the matching `&Condition` so
1989    /// callers can read [`Condition::params`] without re-walking the
1990    /// slice. The default body of `has_kind` is
1991    /// `self.find_kind(kind).is_some()` — the two methods share ONE
1992    /// walk semantics by construction. Byte-for-byte equivalent to
1993    /// `self.iter().find(|c| c.kind == kind)`.
1994    fn find_kind(&self, kind: ConditionKind) -> Option<&Condition> {
1995        self.iter_kind(kind).next()
1996    }
1997
1998    /// True iff at least one [`Condition`] in this slice carries the
1999    /// given [`ConditionKind`]. Default body: `self.find_kind(kind).
2000    /// is_some()`. The single-slice presence probe both
2001    /// [`Boundary::has_condition_kind`] (twice, in a union) and the
2002    /// ephemeral `closed-loop-auth` require-tag arm (once, on
2003    /// postconditions only) compose against.
2004    fn has_kind(&self, kind: ConditionKind) -> bool {
2005        self.find_kind(kind).is_some()
2006    }
2007
2008    /// Number of [`Condition`]s in this slice carrying the given
2009    /// [`ConditionKind`] — the scalar cardinality refinement on the
2010    /// slice-level presence-probe axis. Default body:
2011    /// `self.iter_kind(kind).count()` — a thin projection of the
2012    /// widened primitive [`Self::iter_kind`] onto its cardinality.
2013    ///
2014    /// # Sibling to [`Self::iter_kind`] / [`Self::find_kind`] / [`Self::has_kind`]
2015    ///
2016    /// Fourth refinement on the presence-probe algebra: `iter_kind`
2017    /// yields the whole match stream, `find_kind` collapses it to the
2018    /// first match, `has_kind` collapses that to a `bool`, and
2019    /// `count_kind` collapses the stream to its cardinality without
2020    /// materializing any intermediate [`Vec`] or `Option`. The
2021    /// composition laws
2022    /// `count_kind(k) == iter_kind(k).count()`,
2023    /// `has_kind(k) == (count_kind(k) > 0)`, and
2024    /// `find_kind(k).is_some() == (count_kind(k) > 0)`
2025    /// share ONE walk semantics by construction; a regression that
2026    /// drifted the cardinality probe from the widened stream becomes
2027    /// structurally impossible past the trait boundary.
2028    ///
2029    /// # Semantics
2030    ///
2031    /// Returns `self.iter().filter(|c| c.kind == kind).count()` — a
2032    /// slice that carries multiple matches returns that count, an
2033    /// empty slice or a slice with no matching kind returns `0`.
2034    ///
2035    /// # Compounding
2036    ///
2037    /// A future coherence check that verifies "each [`ConditionKind`]
2038    /// appears at most once per side" now reads
2039    /// `slice.count_kind(k) <= 1` at ONE call site rather than
2040    /// restating either `slice.iter_kind(k).nth(1).is_none()` or the
2041    /// `iter_kind(k).count() <= 1` idiom. A future require-tag
2042    /// classifier arm that surfaces multiplicity to the operator
2043    /// (a hypothetical `condition-count-<kind>` prefix family that
2044    /// publishes the raw cardinality, an audit dump reporting "3
2045    /// PromQL preconditions matched") reaches this ONE primitive
2046    /// through `slice.count_kind(k)` rather than restating the
2047    /// `.iter_kind(k).count()` chain body at the callsite. The
2048    /// presence-probe axis now carries FOUR refinements at ONE typed
2049    /// algebra surface — every downstream consumer picks the coarsest
2050    /// one that answers its question and the coarser ones stay
2051    /// compositionally derived from [`Self::iter_kind`].
2052    fn count_kind(&self, kind: ConditionKind) -> usize {
2053        self.iter_kind(kind).count()
2054    }
2055
2056    /// The set of [`ConditionKind`] variants that appear at least once in
2057    /// this slice, projected in [`ConditionKind::ALL`] order — the
2058    /// closed-set-inversion refinement on the slice-level presence-probe
2059    /// axis. Default body: `ConditionKind::ALL.into_iter().filter(|k|
2060    /// self.has_kind(*k)).collect()` — a thin projection over the closed
2061    /// set that composes against [`Self::has_kind`] per variant.
2062    ///
2063    /// # Sibling to [`Self::has_kind`] / [`Self::find_kind`] / [`Self::iter_kind`] / [`Self::count_kind`]
2064    ///
2065    /// FIFTH refinement on the presence-probe algebra, distinct in axis
2066    /// from the other four: `has_kind` / `find_kind` / `iter_kind` /
2067    /// `count_kind` fix a [`ConditionKind`] and vary the return type
2068    /// (bool / `Option<&Condition>` / `impl Iterator<Item = &Condition>` /
2069    /// `usize`); this refinement INVERTS the axis by fixing the slice and
2070    /// varying over [`ConditionKind::ALL`], returning the SET of present
2071    /// kinds. The composition law
2072    /// `distinct_kinds().contains(&k) == has_kind(k)` for every
2073    /// `k ∈ ConditionKind::ALL` binds the closed-set-inversion probe to
2074    /// the point probe at the trait's default body.
2075    ///
2076    /// # Semantics — canonical subsequence of [`ConditionKind::ALL`]
2077    ///
2078    /// Returns a `Vec<ConditionKind>` whose elements appear in
2079    /// [`ConditionKind::ALL`] order with no duplicates. A slice that
2080    /// carries the same [`ConditionKind`] at multiple positions
2081    /// contributes ONE entry to the returned set (the closed-set
2082    /// projection collapses multiplicity — a caller that needs the
2083    /// per-kind cardinality reaches for [`Self::count_kind`]). An
2084    /// empty slice, or a slice with no matching kind under any
2085    /// [`ConditionKind::ALL`] variant, returns an empty vec.
2086    ///
2087    /// # Why closed-set-inversion is a distinct axis
2088    ///
2089    /// The other four refinements answer "for THIS kind, how does the
2090    /// slice populate the probe's return type?"; this refinement
2091    /// answers "for THIS slice, which kinds appear at least once?".
2092    /// A consumer that needs to enumerate every present kind for an
2093    /// audit dump (`"boundary carries [PromQL, ClosedLoopAuth]"`), a
2094    /// coherence check that verifies "every process's boundary carries
2095    /// at least ONE of {`JobAttested`, `ClosedLoopAuth`}", or a
2096    /// require-tag family that surfaces the distinct-set as a whole
2097    /// (`condition-kinds-distinct-count`) reaches this refinement
2098    /// rather than paying for a per-kind sweep with `has_kind` at the
2099    /// callsite. The point probe stays composable one axis over
2100    /// (`slice.has_kind(k)` for a fixed `k`); the aggregate refinement
2101    /// lives at the same trait, one axis away.
2102    ///
2103    /// # Compounding
2104    ///
2105    /// A future coherence check that enforces "every boundary carries
2106    /// at least ONE distinct kind" (a warning surfaced when
2107    /// `boundary.distinct_condition_kinds().is_empty()`) reaches this
2108    /// ONE primitive rather than paying for the eight-way
2109    /// `for k in ConditionKind::ALL { if boundary.has_condition_kind(k)
2110    /// { return true; } }` sweep at every callsite. A future require-
2111    /// tag classifier arm that publishes the distinct-set cardinality
2112    /// as a scalar (a hypothetical `condition-kinds-distinct-<n>`
2113    /// prefix family, an audit dump reporting "boundary carries N
2114    /// distinct kinds") reaches this ONE primitive through
2115    /// `boundary.distinct_condition_kinds().len()` rather than
2116    /// restating the closed-set-inverted `.iter().filter(...).count()`
2117    /// idiom at every callsite. The presence-probe axis now carries
2118    /// FIVE refinements at ONE typed algebra surface — the four point-
2119    /// probes fixing a kind AND the ONE closed-set-inversion probe
2120    /// fixing a slice — every downstream consumer picks the one that
2121    /// answers its question and the others stay compositionally
2122    /// derived from the single-source-of-truth widened primitive.
2123    ///
2124    /// # Theory grounding
2125    ///
2126    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2127    ///   The closed-set-inversion projection lives at ONE substrate
2128    ///   site as a typed projection of [`Self::has_kind`] over the
2129    ///   closed set [`ConditionKind::ALL`]. Every downstream aggregate
2130    ///   consumer binds through the SAME shape rather than restating
2131    ///   the ALL-filter closure body.
2132    /// - THEORY.md §VI.1 — generation over composition. A new
2133    ///   [`ConditionKind`] variant added to `ALL` reaches this
2134    ///   primitive mechanically (the closed-set walk picks up the new
2135    ///   entry) and every downstream consumer sees the wider set
2136    ///   without further per-caller edit.
2137    fn distinct_kinds(&self) -> Vec<ConditionKind> {
2138        ConditionKind::ALL
2139            .into_iter()
2140            .filter(|k| self.has_kind(*k))
2141            .collect()
2142    }
2143
2144    /// Scalar cardinality projection of [`Self::distinct_kinds`] onto
2145    /// its `.len()` — the number of [`ConditionKind`] variants that
2146    /// appear at least once in this slice. Default body:
2147    /// `ConditionKind::ALL.iter().filter(|k| self.has_kind(**k)).count()`
2148    /// — a closed-set walk that composes against [`Self::has_kind`] per
2149    /// variant WITHOUT materializing an intermediate `Vec<ConditionKind>`.
2150    /// A slice that carries the same [`ConditionKind`] at multiple
2151    /// positions contributes `1` to the count (the closed-set projection
2152    /// collapses multiplicity — a caller that needs the per-kind
2153    /// cardinality reaches for [`Self::count_kind`]).
2154    ///
2155    /// # Sibling to [`Self::distinct_kinds`]
2156    ///
2157    /// Scalar projection of the closed-set-inversion widened primitive
2158    /// — where `distinct_kinds` returns the SET (a `Vec<ConditionKind>`
2159    /// in canonical [`ConditionKind::ALL`] order), `distinct_kind_count`
2160    /// collapses that set to its cardinality. The composition law
2161    /// `distinct_kind_count() == distinct_kinds().len()` binds the
2162    /// scalar projection to the widened primitive at the trait's
2163    /// default body and is swept substrate-wide by
2164    /// [`assert_slice_refinement_composition_laws`] as its sixth arm.
2165    ///
2166    /// # Peer to [`crate::tagged_union::TaggedUnion::populated_kind_count`]
2167    ///
2168    /// Same shape at the peer axis one struct layer up: where
2169    /// `populated_kind_count` scalar-projects `populated_kinds` on the
2170    /// tagged-union parent-level closed-set-inversion axis,
2171    /// `distinct_kind_count` scalar-projects `distinct_kinds` on the
2172    /// slice-level closed-set-inversion axis. The two primitives close
2173    /// the scalar-cardinality refinement at two adjacent typescape
2174    /// sites — one per closed-set-addressed slice-level refinement,
2175    /// one per closed-set-addressed tagged-union parent-level
2176    /// refinement — through the SAME `ClosedSet::ALL`-walk shape.
2177    ///
2178    /// # Compounding future consumers
2179    ///
2180    /// - A future coherence check that enforces "every boundary carries
2181    ///   at least ONE distinct kind" now reads
2182    ///   `slice.distinct_kind_count() > 0` at ONE call site rather than
2183    ///   paying for `slice.distinct_kinds().len() > 0` (with its
2184    ///   intermediate heap allocation) or the eight-way sweep with
2185    ///   `has_kind` at the callsite.
2186    /// - A future require-tag classifier arm that surfaces the
2187    ///   distinct-set cardinality as a scalar (a hypothetical
2188    ///   `condition-kinds-distinct-<n>` prefix family named in
2189    ///   [`Self::distinct_kinds`]'s doc-comment as a compounding-future
2190    ///   consumer) reaches this ONE primitive without allocating.
2191    /// - A future audit dump reporting "boundary carries N distinct
2192    ///   kinds" reaches `slice.distinct_kind_count()` directly rather
2193    ///   than restating the `.iter().filter(...).count()` closure body.
2194    ///
2195    /// # Theory grounding
2196    ///
2197    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2198    ///   The scalar cardinality lives at ONE substrate site as a typed
2199    ///   projection of [`Self::distinct_kinds`] onto its `.len()`, and
2200    ///   the default body composes against [`Self::has_kind`] over the
2201    ///   closed set [`ConditionKind::ALL`] byte-identically to
2202    ///   `distinct_kinds` without the intermediate `Vec`. Every
2203    ///   downstream aggregate consumer binds through the SAME shape
2204    ///   rather than paying for the allocation to reach the
2205    ///   cardinality.
2206    /// - THEORY.md §VI.1 — generation over composition. A new
2207    ///   [`ConditionKind`] variant added to `ALL` reaches this
2208    ///   primitive mechanically (the closed-set walk picks up the new
2209    ///   entry) and every downstream consumer sees the wider
2210    ///   cardinality without further per-caller edit.
2211    fn distinct_kind_count(&self) -> usize {
2212        ConditionKind::ALL
2213            .iter()
2214            .filter(|k| self.has_kind(**k))
2215            .count()
2216    }
2217
2218    /// The set of [`ConditionKind`] variants that do NOT appear in this
2219    /// slice, projected in [`ConditionKind::ALL`] order — the closed-
2220    /// set-inversion COMPLEMENT of [`Self::distinct_kinds`]. Default
2221    /// body: `ConditionKind::ALL.into_iter().filter(|k|
2222    /// !self.has_kind(*k)).collect()` — a thin projection over the
2223    /// closed set that composes against [`Self::has_kind`] per variant
2224    /// under a negated predicate.
2225    ///
2226    /// # Sibling to [`Self::distinct_kinds`]
2227    ///
2228    /// Complement peer of the closed-set-inversion widened primitive on
2229    /// the slice-level presence-probe axis. Where `distinct_kinds`
2230    /// returns the SET of kinds that DO appear at least once,
2231    /// `missing_kinds` returns the SET of kinds that DO NOT appear.
2232    /// Both walk [`ConditionKind::ALL`] in canonical order and compose
2233    /// against the same [`Self::has_kind`] point probe. The two
2234    /// widened primitives PARTITION [`ConditionKind::ALL`]: their union
2235    /// equals `ConditionKind::ALL`, their intersection is empty, and
2236    /// their cardinalities sum to `ConditionKind::ALL.len()` — three
2237    /// composition laws pinned as the seventh, eighth, and ninth arms
2238    /// of the substrate testkit
2239    /// [`assert_slice_refinement_composition_laws`].
2240    ///
2241    /// # Peer to [`crate::tagged_union::TaggedUnion::populated_kinds`]'s
2242    /// hypothetical `unpopulated_kinds` complement
2243    ///
2244    /// Same shape at the peer axis one struct layer up: fixing the
2245    /// parent-side carrier and inverting the presence probe over the
2246    /// closed set. The two primitives close the "closed-set complement"
2247    /// refinement at two adjacent typescape sites — one per closed-set-
2248    /// addressed slice-level refinement (this primitive), one per
2249    /// closed-set-addressed tagged-union parent-level refinement (a
2250    /// symmetric future addition).
2251    ///
2252    /// # Semantics — canonical subsequence of [`ConditionKind::ALL`]
2253    ///
2254    /// Returns a `Vec<ConditionKind>` whose elements appear in
2255    /// [`ConditionKind::ALL`] order with no duplicates. An empty slice
2256    /// returns `ConditionKind::ALL.to_vec()` (every kind is missing).
2257    /// A slice that carries every variant returns an empty vec (no kind
2258    /// is missing). A slice that carries the same [`ConditionKind`] at
2259    /// multiple positions still contributes ZERO entries to the missing
2260    /// set at that kind (the closed-set complement is a SET operation —
2261    /// multiplicity on the present side is irrelevant to absence on the
2262    /// missing side).
2263    ///
2264    /// # Compounding future consumers
2265    ///
2266    /// - A future coherence check that enforces "every process boundary
2267    ///   carries a [`ConditionKind::JobAttested`] postcondition" now
2268    ///   surfaces the operator-facing diagnostic
2269    ///   `spec.boundary.postconditions.missing_kinds()` verbatim
2270    ///   (naming EVERY kind absent from postconditions in canonical
2271    ///   order) rather than reaching for `!has_kind(JobAttested)` at a
2272    ///   per-kind callsite and paying to re-author the diagnostic list.
2273    /// - An operator-facing "boundary is MISSING [JobAttested,
2274    ///   ClosedLoopAuth]" audit dump reads
2275    ///   `boundary.postconditions.missing_kinds()` directly at ONE call
2276    ///   site rather than restating the negated closed-set walk at
2277    ///   every consumer.
2278    /// - A fleet-wide gap analysis ("which processes are missing a
2279    ///   `ClosedLoopAuth` postcondition") reaches this ONE primitive
2280    ///   through `spec.boundary.postconditions.missing_kinds()
2281    ///   .contains(&ConditionKind::ClosedLoopAuth)` rather than paying
2282    ///   for the negated `.has_kind` sweep at every callsite.
2283    /// - A hypothetical `condition-kinds-missing-<n>` require-tag
2284    ///   classifier prefix family that publishes the missing-set
2285    ///   cardinality as a scalar reads
2286    ///   [`Self::missing_kind_count`] (the scalar-cardinality peer of
2287    ///   this widened primitive) without allocating.
2288    ///
2289    /// # Theory grounding
2290    ///
2291    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2292    ///   The closed-set complement lives at ONE substrate site as a
2293    ///   typed projection of [`Self::has_kind`] over the closed set
2294    ///   [`ConditionKind::ALL`] under negation. Every downstream gap-
2295    ///   analysis consumer binds through the SAME shape rather than
2296    ///   restating the negated ALL-filter closure body.
2297    /// - THEORY.md §VI.1 — generation over composition. A new
2298    ///   [`ConditionKind`] variant added to `ALL` reaches this
2299    ///   primitive mechanically (the closed-set walk picks up the new
2300    ///   entry on the missing side WITHOUT further per-caller edit —
2301    ///   any slice that doesn't yet populate the new kind sees it
2302    ///   listed as missing at every downstream callsite).
2303    fn missing_kinds(&self) -> Vec<ConditionKind> {
2304        ConditionKind::ALL
2305            .into_iter()
2306            .filter(|k| !self.has_kind(*k))
2307            .collect()
2308    }
2309
2310    /// Scalar cardinality projection of [`Self::missing_kinds`] onto its
2311    /// `.len()` — the number of [`ConditionKind`] variants that do NOT
2312    /// appear in this slice. Default body:
2313    /// `ConditionKind::ALL.iter().filter(|k| !self.has_kind(**k)).count()`
2314    /// — a closed-set walk composed against [`Self::has_kind`] per variant
2315    /// under a NEGATED point-probe, WITHOUT materializing the intermediate
2316    /// `Vec<ConditionKind>` a caller reaching only for the scalar
2317    /// cardinality otherwise pays for. An empty slice returns
2318    /// `ConditionKind::ALL.len()` (every kind is missing); a slice
2319    /// carrying every variant returns `0` (no kind is missing).
2320    ///
2321    /// # Sibling to [`Self::missing_kinds`] / [`Self::distinct_kind_count`]
2322    ///
2323    /// Scalar projection of the closed-set-complement widened primitive
2324    /// — where `missing_kinds` returns the SET (a `Vec<ConditionKind>`
2325    /// in canonical [`ConditionKind::ALL`] order), `missing_kind_count`
2326    /// collapses that set to its cardinality. The composition law
2327    /// `missing_kind_count() == missing_kinds().len()` binds the scalar
2328    /// projection to the widened primitive at the trait's default body
2329    /// and is swept substrate-wide by
2330    /// [`assert_slice_refinement_composition_laws`] as its scalar-
2331    /// cardinality-complement arm.
2332    ///
2333    /// Byte-for-byte peer of [`Self::distinct_kind_count`] one axis over
2334    /// (under a negated `has_kind` predicate): where `distinct_kind_count`
2335    /// scalar-projects the closed-set-INVERSION widened primitive
2336    /// `distinct_kinds`, this method scalar-projects the closed-set-
2337    /// COMPLEMENT widened primitive `missing_kinds`. The two scalar
2338    /// projections PARTITION the closed-set cardinality:
2339    /// `distinct_kind_count() + missing_kind_count() ==
2340    /// ConditionKind::ALL.len()` — the scalar consequence of the
2341    /// `(distinct_kinds, missing_kinds)` partition law that
2342    /// [`assert_slice_refinement_composition_laws`] pins at the
2343    /// widened-primitive layer.
2344    ///
2345    /// # Peer to [`crate::tagged_union::TaggedUnion::populated_kind_count`]'s
2346    /// hypothetical complement peer
2347    ///
2348    /// Same shape at the peer axis one struct layer up: fixing the
2349    /// slice-side carrier and inverting the presence probe over the
2350    /// closed set under a negated predicate. The two primitives close
2351    /// the "closed-set-complement scalar cardinality" refinement at
2352    /// two adjacent typescape sites — one per closed-set-addressed
2353    /// slice-level refinement (this primitive), one per closed-set-
2354    /// addressed tagged-union parent-level refinement (a symmetric
2355    /// future addition).
2356    ///
2357    /// # Compounding future consumers
2358    ///
2359    /// - A future coherence check that enforces "every process boundary
2360    ///   carries EVERY [`ConditionKind`] under some slot" now reads
2361    ///   `spec.boundary.postconditions.missing_kind_count() == 0` at
2362    ///   ONE call site rather than paying for
2363    ///   `spec.boundary.postconditions.missing_kinds().is_empty()`
2364    ///   (with its intermediate heap allocation) or the eight-way
2365    ///   negated sweep with `has_kind` at the callsite.
2366    /// - A future require-tag classifier arm that surfaces the missing-
2367    ///   set cardinality as a scalar (the exact
2368    ///   `condition-kinds-missing-<n>` require-tag classifier prefix
2369    ///   family called out in [`Self::missing_kinds`]'s doc-comment as
2370    ///   a hypothetical compounding-future consumer) reaches this ONE
2371    ///   primitive without allocating.
2372    /// - A future gap-analysis dashboard reporting "boundary is missing
2373    ///   N of {N_TOTAL} distinct kinds" reaches
2374    ///   `slice.missing_kind_count()` directly rather than restating the
2375    ///   negated `.iter().filter(...).count()` closure body.
2376    ///
2377    /// # Theory grounding
2378    ///
2379    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2380    ///   The scalar cardinality lives at ONE substrate site as a typed
2381    ///   projection of [`Self::missing_kinds`] onto its `.len()`, and
2382    ///   the default body composes against [`Self::has_kind`] over the
2383    ///   closed set [`ConditionKind::ALL`] under negation byte-
2384    ///   identically to `missing_kinds` without the intermediate `Vec`.
2385    ///   Every downstream aggregate consumer binds through the SAME
2386    ///   shape rather than paying for the allocation to reach the
2387    ///   cardinality.
2388    /// - THEORY.md §VI.1 — generation over composition. A new
2389    ///   [`ConditionKind`] variant added to `ALL` reaches this primitive
2390    ///   mechanically (the closed-set walk picks up the new entry on
2391    ///   the missing side WITHOUT further per-caller edit — any slice
2392    ///   that doesn't yet populate the new kind sees the cardinality
2393    ///   rise by one at every downstream callsite).
2394    fn missing_kind_count(&self) -> usize {
2395        ConditionKind::ALL
2396            .iter()
2397            .filter(|k| !self.has_kind(**k))
2398            .count()
2399    }
2400
2401    /// Short-circuiting `Option<ConditionKind>` peer of
2402    /// [`Self::distinct_kinds`] — the FIRST [`ConditionKind`] variant
2403    /// present in this slice, in canonical [`ConditionKind::ALL`] order,
2404    /// or `None` when the slice carries no matching kind. Default body:
2405    /// `ConditionKind::ALL.iter().copied().find(|k| self.has_kind(*k))`
2406    /// — a closed-set walk composed against [`Self::has_kind`] per
2407    /// variant that SHORT-CIRCUITS at the earliest match.
2408    ///
2409    /// # Sibling to [`Self::distinct_kinds`] / [`Self::distinct_kind_count`]
2410    ///
2411    /// Third refinement on the closed-set-inversion axis, `Option<ConditionKind>`-
2412    /// valued: `distinct_kinds` returns the SET, `distinct_kind_count`
2413    /// scalar-projects the cardinality, and `first_distinct_kind`
2414    /// scalar-projects the SET onto its earliest element. The composition
2415    /// law `first_distinct_kind() == distinct_kinds().first().copied()`
2416    /// binds the earliest-element projection to the widened primitive at
2417    /// the trait's default body — pinned substrate-wide by
2418    /// [`assert_slice_refinement_composition_laws`] as its
2419    /// earliest-element-inversion arm. Both coarser projections agree on
2420    /// emptiness: `first_distinct_kind().is_none() ==
2421    /// (distinct_kind_count() == 0)`.
2422    ///
2423    /// # Peer to [`crate::tagged_union::TaggedUnion::first_populated_kind`]
2424    ///
2425    /// Same shape at the peer axis one struct layer up: fixing the
2426    /// carrier and short-circuiting on the earliest [`ConditionKind::ALL`]
2427    /// hit under [`Self::has_kind`]. `TaggedUnion::first_populated_kind`
2428    /// walks the tagged-union parent's closed set; `first_distinct_kind`
2429    /// here walks [`ConditionKind::ALL`] on the slice-level presence-probe
2430    /// axis. The two primitives close the "earliest-element scalar-
2431    /// projection of the closed-set-inversion widened primitive"
2432    /// refinement at two adjacent typescape sites — one per closed-set-
2433    /// addressed slice-level refinement (this primitive), one per closed-
2434    /// set-addressed tagged-union parent-level refinement.
2435    ///
2436    /// # Semantics
2437    ///
2438    /// Returns `Some(k)` where `k` is the earliest [`ConditionKind::ALL`]
2439    /// entry with `self.has_kind(k) == true`, or `None` when no kind is
2440    /// present. An empty slice returns `None`. A slice carrying multiple
2441    /// variants returns the earliest one in [`ConditionKind::ALL`] order
2442    /// — a strictly more informative projection than
2443    /// `distinct_kinds().first().copied()` without materializing the
2444    /// intermediate `Vec<ConditionKind>` the widened primitive
2445    /// otherwise pays for.
2446    ///
2447    /// # Compounding future consumers
2448    ///
2449    /// - An operator-facing "first present kind" diagnostic on an audit
2450    ///   dump that names ONE kind rather than the full set reaches this
2451    ///   ONE substrate site rather than paying for
2452    ///   `slice.distinct_kinds().first().copied()` (with its
2453    ///   intermediate heap allocation).
2454    /// - A `first-distinct-<kind>` require-tag classifier arm reads this
2455    ///   primitive with no allocation, byte-for-byte symmetrical with
2456    ///   `slice.has_kind(kind)` under a closed-set-inversion projection.
2457    /// - A fast-path branch that discriminates "empty" from "any
2458    ///   populated" reads `slice.first_distinct_kind().is_some()` at ONE
2459    ///   call site rather than allocating a `Vec<ConditionKind>` through
2460    ///   `!distinct_kinds().is_empty()` or paying for the full
2461    ///   `distinct_kind_count() > 0` walk.
2462    ///
2463    /// # Theory grounding
2464    ///
2465    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
2466    ///   earliest-element projection lives at ONE substrate site as a
2467    ///   typed projection of [`Self::has_kind`] over the closed set
2468    ///   [`ConditionKind::ALL`] under short-circuit walk semantics.
2469    /// - THEORY.md §VI.1 — generation over composition. A new
2470    ///   [`ConditionKind`] variant added to `ALL` reaches this primitive
2471    ///   mechanically (the closed-set walk picks up the new entry) —
2472    ///   every downstream consumer sees the wider earliest-hit projection
2473    ///   without further per-caller edit.
2474    fn first_distinct_kind(&self) -> Option<ConditionKind> {
2475        ConditionKind::ALL
2476            .iter()
2477            .copied()
2478            .find(|k| self.has_kind(*k))
2479    }
2480
2481    /// Short-circuiting `Option<ConditionKind>` peer of
2482    /// [`Self::missing_kinds`] — the FIRST [`ConditionKind`] variant
2483    /// ABSENT from this slice, in canonical [`ConditionKind::ALL`] order,
2484    /// or `None` when the slice carries every variant. Default body:
2485    /// `ConditionKind::ALL.iter().copied().find(|k| !self.has_kind(*k))`
2486    /// — a closed-set walk composed against [`Self::has_kind`] per
2487    /// variant under NEGATION with SHORT-CIRCUIT at the earliest empty
2488    /// slot.
2489    ///
2490    /// # Sibling to [`Self::missing_kinds`] / [`Self::missing_kind_count`]
2491    ///
2492    /// Third refinement on the closed-set-complement axis,
2493    /// `Option<ConditionKind>`-valued: `missing_kinds` returns the SET,
2494    /// `missing_kind_count` scalar-projects the cardinality, and
2495    /// `first_missing_kind` scalar-projects the SET onto its earliest
2496    /// element. The composition law
2497    /// `first_missing_kind() == missing_kinds().first().copied()` binds
2498    /// the earliest-element projection to the widened primitive at the
2499    /// trait's default body — pinned substrate-wide by
2500    /// [`assert_slice_refinement_composition_laws`] as its
2501    /// earliest-element-complement arm. Both coarser projections agree
2502    /// on saturation: `first_missing_kind().is_none() ==
2503    /// (missing_kind_count() == 0)`.
2504    ///
2505    /// # Peer to [`Self::first_distinct_kind`]
2506    ///
2507    /// Closed-set-complement peer of the closed-set-inversion earliest-
2508    /// element primitive under a negated `has_kind` predicate. The two
2509    /// primitives PARTITION [`ConditionKind::ALL`]'s earliest-element
2510    /// projection: at least one of `first_distinct_kind()` and
2511    /// `first_missing_kind()` is `Some` on any non-degenerate closed set
2512    /// (both are `Some` iff `1 ≤ distinct_kind_count() <
2513    /// ConditionKind::ALL.len()`; only the distinct-side is `Some` on a
2514    /// saturated slice; only the missing-side is `Some` on an empty
2515    /// slice).
2516    ///
2517    /// # Peer to [`crate::tagged_union::TaggedUnion::first_missing_kind`]
2518    ///
2519    /// Same shape at the peer axis one struct layer up under a negated
2520    /// predicate. The two primitives close the "earliest-element scalar-
2521    /// projection of the closed-set-complement widened primitive"
2522    /// refinement at two adjacent typescape sites — one per closed-set-
2523    /// addressed slice-level refinement (this primitive), one per closed-
2524    /// set-addressed tagged-union parent-level refinement.
2525    ///
2526    /// # Semantics
2527    ///
2528    /// An empty slice returns `Some(ConditionKind::ALL[0])` (every kind
2529    /// missing, first hit is index 0). A slice populating exactly `k`
2530    /// returns `Some(ConditionKind::ALL[0])` if `k != ALL[0]`, else
2531    /// `Some(ALL[1])` (the earliest non-`k` entry). A saturated slice
2532    /// carrying every variant returns `None`.
2533    ///
2534    /// # Compounding future consumers
2535    ///
2536    /// - An operator-facing "first still-unfilled kind" diagnostic on a
2537    ///   partially-populated boundary reads
2538    ///   `boundary.postconditions.first_missing_kind()` at ONE substrate
2539    ///   site — a strictly-more-informative projection than
2540    ///   `!has_kind(JobAttested)` at a per-kind callsite for a fleet-wide
2541    ///   "which processes are missing at least one closed-loop kind"
2542    ///   audit.
2543    /// - A `first-missing-<kind>` require-tag classifier arm reads this
2544    ///   primitive with no allocation, byte-for-byte symmetrical with
2545    ///   `slice.first_distinct_kind()`.
2546    /// - A fast-path branch that discriminates "saturated" from "at least
2547    ///   one missing" reads `slice.first_missing_kind().is_some()` at ONE
2548    ///   call site rather than allocating through
2549    ///   `!missing_kinds().is_empty()` or paying for the full
2550    ///   `missing_kind_count() > 0` walk.
2551    ///
2552    /// # Theory grounding
2553    ///
2554    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
2555    ///   complement-earliest-element projection lives at ONE substrate
2556    ///   site as a typed projection of [`Self::has_kind`] over the
2557    ///   closed set [`ConditionKind::ALL`] under negation with short-
2558    ///   circuit walk semantics.
2559    /// - THEORY.md §VI.1 — generation over composition. A new
2560    ///   [`ConditionKind`] variant added to `ALL` reaches this primitive
2561    ///   mechanically (the closed-set walk picks up the new entry on the
2562    ///   missing side) — every downstream consumer sees the wider
2563    ///   complement's earliest hit without further per-caller edit.
2564    fn first_missing_kind(&self) -> Option<ConditionKind> {
2565        ConditionKind::ALL
2566            .iter()
2567            .copied()
2568            .find(|k| !self.has_kind(*k))
2569    }
2570
2571    /// Short-circuiting `Option<ConditionKind>` peer of
2572    /// [`Self::distinct_kinds`] — the LAST [`ConditionKind`] variant
2573    /// present in this slice, in canonical [`ConditionKind::ALL`]
2574    /// order, or `None` when the slice carries no variant. Default
2575    /// body: `ConditionKind::ALL.iter().rev().copied().find(|k|
2576    /// self.has_kind(*k))` — a REVERSED closed-set walk composed
2577    /// against [`Self::has_kind`] per variant that SHORT-CIRCUITS at
2578    /// the latest hit.
2579    ///
2580    /// # Sibling to [`Self::distinct_kinds`] /
2581    /// [`Self::distinct_kind_count`] / [`Self::first_distinct_kind`]
2582    ///
2583    /// Fourth refinement on the closed-set-inversion axis and second
2584    /// scalar `Option<ConditionKind>` projection: `distinct_kinds`
2585    /// returns the SET, `distinct_kind_count` scalar-projects the
2586    /// cardinality, `first_distinct_kind` scalar-projects the SET
2587    /// onto its earliest element, and `last_distinct_kind` scalar-
2588    /// projects the SET onto its latest element. The composition law
2589    /// `last_distinct_kind() == distinct_kinds().last().copied()`
2590    /// binds the latest-element projection to the widened primitive
2591    /// at the trait's default body — pinned substrate-wide by
2592    /// [`assert_slice_refinement_composition_laws`] as its
2593    /// latest-element-inversion arm. Both scalar projections agree on
2594    /// emptiness: `last_distinct_kind().is_none() ==
2595    /// first_distinct_kind().is_none() == distinct_kinds().is_empty()`.
2596    ///
2597    /// # Peer to [`Self::first_distinct_kind`]
2598    ///
2599    /// Time-reversed peer under the SAME `has_kind` predicate: where
2600    /// `first_distinct_kind` walks [`ConditionKind::ALL`] forward and
2601    /// SHORT-CIRCUITS at the earliest hit, this primitive walks the
2602    /// SAME closed set in reverse and SHORT-CIRCUITS at the latest
2603    /// hit. The two primitives close the "endpoint scalar-projection
2604    /// of the closed-set-inversion widened primitive" refinement pair
2605    /// at one substrate site — one per endpoint. On a slice with
2606    /// exactly one distinct kind both projections agree; on a slice
2607    /// with distinct-kind-count ≥ 2 they yield distinct results
2608    /// (the earliest and latest elements of the closed-set-inversion
2609    /// respectively).
2610    ///
2611    /// # Semantics
2612    ///
2613    /// An empty slice returns `None` (no kind present, no hit on any
2614    /// walk direction). A slice populating exactly `k` returns
2615    /// `Some(k)` (single hit; earliest = latest). A saturated slice
2616    /// carrying every variant returns `Some(ConditionKind::ALL.last()
2617    /// .unwrap())` (the last ALL entry hits at the earliest walk step
2618    /// of the reversed walk).
2619    ///
2620    /// # Compounding future consumers
2621    ///
2622    /// - A `last-distinct-<kind>` require-tag classifier arm reads
2623    ///   the latest-populated kind through this ONE substrate
2624    ///   primitive with no allocation, byte-for-byte symmetrical with
2625    ///   the earliest-hit `slice.first_distinct_kind()` peer.
2626    /// - A future coherence check that surfaces "boundary ends with
2627    ///   ClosedLoopAuth" reads
2628    ///   `spec.boundary.postconditions.last_distinct_kind() ==
2629    ///   Some(ConditionKind::ClosedLoopAuth)` at ONE call site rather
2630    ///   than paying for `spec.boundary.postconditions
2631    ///   .distinct_kinds().last() == Some(&…)` with its intermediate
2632    ///   heap allocation.
2633    /// - Combined with [`Self::first_distinct_kind`], operator
2634    ///   diagnostics that render a "populated-kind range" summary
2635    ///   (`first..=last` on the closed-set-inversion projection) read
2636    ///   the two endpoints through TWO substrate primitives at
2637    ///   symmetric shapes without allocating.
2638    ///
2639    /// # Theory grounding
2640    ///
2641    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2642    ///   The latest-element projection lives at ONE substrate site as
2643    ///   a typed projection of [`Self::has_kind`] over the closed set
2644    ///   [`ConditionKind::ALL`] under REVERSED short-circuit walk
2645    ///   semantics; byte-for-byte peer of the earliest-element
2646    ///   projection under FORWARD walk semantics.
2647    /// - THEORY.md §VI.1 — generation over composition. A new
2648    ///   [`ConditionKind`] variant added to `ALL` reaches this
2649    ///   primitive mechanically (the reversed closed-set walk picks
2650    ///   up the new entry at the appropriate position) — every
2651    ///   downstream consumer sees the wider latest-hit projection
2652    ///   without further per-caller edit.
2653    fn last_distinct_kind(&self) -> Option<ConditionKind> {
2654        ConditionKind::ALL
2655            .iter()
2656            .rev()
2657            .copied()
2658            .find(|k| self.has_kind(*k))
2659    }
2660
2661    /// Short-circuiting `Option<ConditionKind>` peer of
2662    /// [`Self::missing_kinds`] — the LAST [`ConditionKind`] variant
2663    /// ABSENT from this slice, in canonical [`ConditionKind::ALL`]
2664    /// order, or `None` when the slice carries every variant. Default
2665    /// body: `ConditionKind::ALL.iter().rev().copied().find(|k|
2666    /// !self.has_kind(*k))` — a REVERSED closed-set walk composed
2667    /// against [`Self::has_kind`] per variant under NEGATION with
2668    /// SHORT-CIRCUIT at the latest empty slot.
2669    ///
2670    /// # Sibling to [`Self::missing_kinds`] /
2671    /// [`Self::missing_kind_count`] / [`Self::first_missing_kind`]
2672    ///
2673    /// Fourth refinement on the closed-set-complement axis and second
2674    /// scalar `Option<ConditionKind>` projection: `missing_kinds`
2675    /// returns the SET, `missing_kind_count` scalar-projects the
2676    /// cardinality, `first_missing_kind` scalar-projects the SET onto
2677    /// its earliest element, and `last_missing_kind` scalar-projects
2678    /// the SET onto its latest element. The composition law
2679    /// `last_missing_kind() == missing_kinds().last().copied()` binds
2680    /// the latest-element projection to the widened primitive at the
2681    /// trait's default body — pinned substrate-wide by
2682    /// [`assert_slice_refinement_composition_laws`] as its
2683    /// latest-element-complement arm. Both scalar projections agree
2684    /// on saturation: `last_missing_kind().is_none() ==
2685    /// first_missing_kind().is_none() == missing_kinds().is_empty()`.
2686    ///
2687    /// # Peer to [`Self::first_missing_kind`]
2688    ///
2689    /// Time-reversed peer under the SAME negated `has_kind` predicate:
2690    /// where `first_missing_kind` walks [`ConditionKind::ALL`] forward
2691    /// under negation and SHORT-CIRCUITS at the earliest empty slot,
2692    /// this primitive walks the SAME closed set in reverse and SHORT-
2693    /// CIRCUITS at the latest empty slot. The two primitives close
2694    /// the "endpoint scalar-projection of the closed-set-complement
2695    /// widened primitive" refinement pair at one substrate site.
2696    ///
2697    /// # Peer to [`Self::last_distinct_kind`]
2698    ///
2699    /// Closed-set-complement peer of the closed-set-inversion latest-
2700    /// element primitive under a NEGATED `has_kind` predicate. Along
2701    /// with [`Self::first_distinct_kind`] and [`Self::first_missing_kind`]
2702    /// the four scalar-endpoint projections partition the endpoint
2703    /// axis into (present, absent) × (earliest, latest) — every
2704    /// endpoint-addressable coherence check reads ONE of the four at
2705    /// ONE call site, never the full `Vec<ConditionKind>` walk.
2706    ///
2707    /// # Semantics
2708    ///
2709    /// An empty slice returns `Some(ConditionKind::ALL.last().unwrap())`
2710    /// (every kind missing, latest hit is the last ALL entry). A slice
2711    /// populating exactly `k` returns `Some(ALL.last().unwrap())` if
2712    /// `k != ALL.last().unwrap()`, else `Some(ALL[ALL.len() - 2])` (the
2713    /// latest non-`k` entry). A saturated slice carrying every variant
2714    /// returns `None`.
2715    ///
2716    /// # Compounding future consumers
2717    ///
2718    /// - An operator-facing "last still-unfilled kind" diagnostic on a
2719    ///   partially-populated boundary reads
2720    ///   `boundary.postconditions.last_missing_kind()` at ONE substrate
2721    ///   site — a strictly-more-informative projection than
2722    ///   `!has_kind(ClosedLoopAuth)` at a per-kind callsite for a
2723    ///   fleet-wide "which processes are latest-missing a specific
2724    ///   closed-loop kind" audit.
2725    /// - A `last-missing-<kind>` require-tag classifier arm reads this
2726    ///   primitive with no allocation, byte-for-byte symmetrical with
2727    ///   the earliest-hit `slice.first_missing_kind()` peer.
2728    /// - Combined with [`Self::first_missing_kind`], a coherence check
2729    ///   that renders a "missing-kind range" summary reads the two
2730    ///   endpoints through TWO substrate primitives at symmetric
2731    ///   shapes without allocating through `missing_kinds()`.
2732    ///
2733    /// # Theory grounding
2734    ///
2735    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2736    ///   The complement-latest-element projection lives at ONE
2737    ///   substrate site as a typed projection of [`Self::has_kind`]
2738    ///   over the closed set [`ConditionKind::ALL`] under negation
2739    ///   with REVERSED short-circuit walk semantics; byte-for-byte
2740    ///   peer of the complement-earliest-element projection under
2741    ///   FORWARD walk semantics.
2742    /// - THEORY.md §VI.1 — generation over composition. A new
2743    ///   [`ConditionKind`] variant added to `ALL` reaches this
2744    ///   primitive mechanically (the reversed closed-set walk picks
2745    ///   up the new entry on the missing side at the appropriate
2746    ///   position) — every downstream consumer sees the wider
2747    ///   complement's latest hit without further per-caller edit.
2748    fn last_missing_kind(&self) -> Option<ConditionKind> {
2749        ConditionKind::ALL
2750            .iter()
2751            .rev()
2752            .copied()
2753            .find(|k| !self.has_kind(*k))
2754    }
2755
2756    /// Boolean saturation predicate on the closed-set-inversion axis —
2757    /// `true` iff EVERY [`ConditionKind::ALL`] variant appears at least
2758    /// once in this slice (equivalently, [`Self::missing_kinds`] is
2759    /// empty).
2760    ///
2761    /// Default body:
2762    /// `ConditionKind::ALL.iter().all(|k| self.has_kind(*k))` — a
2763    /// SHORT-CIRCUITING closed-set walk composed against [`Self::has_kind`]
2764    /// per variant that returns `false` at the FIRST missing kind,
2765    /// WITHOUT materializing [`Self::missing_kinds`]'s `Vec` and WITHOUT
2766    /// walking every entry to build [`Self::missing_kind_count`]'s
2767    /// scalar. Strictly cheaper than either widened primitive on every
2768    /// partially-populated arm (returns at the first empty slot rather
2769    /// than sweeping the full closed set).
2770    ///
2771    /// # Peer to [`crate::tagged_union::TaggedUnion::is_saturated`]
2772    ///
2773    /// Slice-level peer of the tagged-union parent-level saturation
2774    /// predicate one struct-layer up: where `is_saturated` names the
2775    /// tagged-union arm where every `<Self::Kind as ClosedSet>::ALL`
2776    /// slot is populated, `is_kind_saturated` names the slice arm where
2777    /// every [`ConditionKind::ALL`] variant appears at least once. Both
2778    /// short-circuit at the first missing entry under the SAME
2779    /// `<CLOSED_SET>::ALL.iter().all(has)` walk shape at two adjacent
2780    /// typescape sites.
2781    ///
2782    /// # Sibling to [`Self::missing_kind_count`] / [`Self::missing_kinds`]
2783    ///
2784    /// Boolean cardinality-endpoint peer of the scalar cardinality
2785    /// primitive on the closed-set-complement axis — where
2786    /// `missing_kind_count` returns the FULL scalar (any `usize` in
2787    /// `0..=ConditionKind::ALL.len()`), `is_kind_saturated` collapses
2788    /// that scalar to its zero-arm Boolean projection. The composition
2789    /// law `is_kind_saturated() == (missing_kind_count() == 0)` binds
2790    /// the Boolean projection to the scalar primitive at the trait's
2791    /// default body — swept substrate-wide by
2792    /// [`assert_slice_refinement_composition_laws`] as its
2793    /// saturation-endpoint arm.
2794    ///
2795    /// # Semantics
2796    ///
2797    /// An empty slice returns `false` (no kind is populated). A slice
2798    /// carrying a strict subset of [`ConditionKind::ALL`] returns
2799    /// `false`. A slice that carries every variant at least once
2800    /// (multiplicity is irrelevant) returns `true` — the SOLE arm
2801    /// where `is_kind_saturated` returns `true`.
2802    ///
2803    /// # Compounding future consumers
2804    ///
2805    /// - A future coherence check that enforces "every process boundary
2806    ///   exhaustively covers every [`ConditionKind`]" reads
2807    ///   `boundary.postconditions.is_kind_saturated()` at ONE call site
2808    ///   — one short-circuit walk, no allocation, no scalar equality
2809    ///   comparison against `ConditionKind::ALL.len()`.
2810    /// - An `is-kind-saturated` require-tag classifier arm reaches this
2811    ///   primitive with no allocation, byte-for-byte peer of the
2812    ///   tagged-union `is-saturated` classifier one struct-layer up.
2813    /// - A fleet-wide gap-analysis dashboard fast-path that discriminates
2814    ///   "boundary spans every kind" from "boundary is missing some
2815    ///   kind" reads `boundary.postconditions.is_kind_saturated()` at
2816    ///   ONE call site rather than restating either
2817    ///   `boundary.postconditions.missing_kind_count() == 0` (which
2818    ///   walks every slot to count) or
2819    ///   `boundary.postconditions.missing_kinds().is_empty()` (which
2820    ///   allocates the Vec before the emptiness check).
2821    ///
2822    /// # Theory grounding
2823    ///
2824    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2825    ///   The saturation-endpoint projection lives at ONE substrate
2826    ///   site as a typed short-circuiting closed-set walk
2827    ///   `ConditionKind::ALL.iter().all(has_kind)`. Every downstream
2828    ///   consumer binds through the SAME shape rather than restating
2829    ///   the `== ConditionKind::ALL.len()` scalar composition body.
2830    /// - THEORY.md §VI.1 — generation over composition. A new
2831    ///   [`ConditionKind`] variant added to `ALL` reaches this
2832    ///   primitive mechanically through the `all` short-circuit — a
2833    ///   slice that was previously saturated is no longer saturated
2834    ///   at every downstream callsite unless it also carries the new
2835    ///   variant.
2836    fn is_kind_saturated(&self) -> bool {
2837        ConditionKind::ALL.iter().all(|k| self.has_kind(*k))
2838    }
2839
2840    /// Boolean at-least-one halfspace peer of [`Self::is_kind_saturated`]
2841    /// on the closed-set-complement axis — `true` iff AT LEAST ONE
2842    /// [`ConditionKind::ALL`] variant appears zero times in this slice
2843    /// (equivalently, [`Self::missing_kinds`] is non-empty,
2844    /// [`Self::missing_kind_count`] `> 0`, [`Self::first_missing_kind`]
2845    /// is `Some`).
2846    ///
2847    /// Default body: `!self.is_kind_saturated()` — a definitional
2848    /// negation of the saturation-endpoint primitive. Short-circuits
2849    /// transitively through [`Self::is_kind_saturated`]'s
2850    /// `ConditionKind::ALL.iter().all(has_kind)` composition: the
2851    /// underlying `all` walk returns `false` at the FIRST missing kind
2852    /// (yielding `true` here) WITHOUT materializing
2853    /// [`Self::missing_kinds`]'s `Vec`, WITHOUT walking every slot to
2854    /// build [`Self::missing_kind_count`]'s scalar, and WITHOUT
2855    /// allocating the closed-set-complement scan. Strictly cheaper
2856    /// than either widened primitive on every partially-populated arm.
2857    ///
2858    /// # Peer to [`crate::tagged_union::TaggedUnion::has_any_missing_kind`]
2859    ///
2860    /// Slice-level peer of the tagged-union parent-level at-least-one
2861    /// halfspace predicate one struct-layer up: where
2862    /// [`crate::tagged_union::TaggedUnion::has_any_missing_kind`]
2863    /// answers "is ANY slot on the tagged-union parent empty?",
2864    /// `has_any_missing_kind` answers "does ANY kind appear in NO
2865    /// condition of the slice?". Both compose against their
2866    /// saturation-endpoint primitive under a definitional negation
2867    /// (`!is_saturated` / `!is_kind_saturated`) at two adjacent
2868    /// typescape sites — the two primitives close the at-least-one
2869    /// halfspace on the closed-set-complement axis at both struct
2870    /// layers under the SAME shape.
2871    ///
2872    /// # Sibling to [`Self::is_kind_saturated`]
2873    ///
2874    /// Boolean at-least-one halfspace peer of the zero-arm saturation-
2875    /// endpoint primitive on the closed-set-complement axis — where
2876    /// `is_kind_saturated` returns `true` iff `missing_kind_count == 0`,
2877    /// `has_any_missing_kind` returns its Boolean-negation: `true` iff
2878    /// `missing_kind_count >= 1`. Together the two Booleans partition
2879    /// the missing-cardinality closed set: exactly one of
2880    /// `is_kind_saturated()` and `has_any_missing_kind()` is `true`
2881    /// for every slice. The definitional negation law
2882    /// `has_any_missing_kind() == !is_kind_saturated()` is pinned as a
2883    /// first-class typed invariant by the trait's own default body and
2884    /// swept substrate-wide by
2885    /// [`assert_slice_refinement_composition_laws`] as its at-least-
2886    /// one halfspace arm.
2887    ///
2888    /// # Sibling to [`Self::missing_kinds`] / [`Self::missing_kind_count`]
2889    ///
2890    /// Boolean at-least-one halfspace peer of the widened + scalar
2891    /// closed-set-complement primitives — where `missing_kinds` returns
2892    /// the FULL missing SET (a `Vec<ConditionKind>` of every absent
2893    /// kind) and `missing_kind_count` returns its cardinality
2894    /// (a `usize` in `0..=ConditionKind::ALL.len()`),
2895    /// `has_any_missing_kind` collapses either the widened primitive
2896    /// to its non-emptiness Boolean or the scalar to its `>= 1`
2897    /// halfspace Boolean. The composition laws
2898    /// `has_any_missing_kind() == !missing_kinds().is_empty()` and
2899    /// `has_any_missing_kind() == (missing_kind_count() > 0)` bind
2900    /// this Boolean projection to the widened + scalar primitives at
2901    /// the trait's default body — strictly cheaper than either widened
2902    /// primitive on every partially-populated arm because the negation
2903    /// short-circuits at the first missing kind on the has-side walk
2904    /// rather than allocating the closed-set-complement scan or
2905    /// walking every slot to build the scalar cardinality.
2906    ///
2907    /// # Semantics
2908    ///
2909    /// An empty slice returns `true` (every kind is missing — the
2910    /// fully-missing endpoint). A slice carrying a strict subset of
2911    /// [`ConditionKind::ALL`] returns `true`. A saturated slice
2912    /// returns `false` — the SOLE arm on which `has_any_missing_kind`
2913    /// returns `false`, byte-for-byte peer of the SOLE arm on which
2914    /// `is_kind_saturated` returns `true`.
2915    ///
2916    /// # Compounding future consumers
2917    ///
2918    /// - A fleet-wide "gap present" fast-path that discriminates "some
2919    ///   kind is missing" from "every kind is present" reads
2920    ///   `boundary.postconditions.has_any_missing_kind()` at ONE call
2921    ///   site rather than negating `is_kind_saturated()` at the
2922    ///   callsite or restating `missing_kind_count() > 0` (which walks
2923    ///   every slot to count) or `!missing_kinds().is_empty()` (which
2924    ///   allocates the Vec before the negated emptiness check).
2925    /// - A `has-any-missing-kind` require-tag classifier arm reaches
2926    ///   this primitive with no allocation, byte-for-byte peer of the
2927    ///   tagged-union `has-any-missing-kind` classifier one struct-
2928    ///   layer up under the SAME `!is_saturated` definitional negation
2929    ///   shape.
2930    /// - A coherence check that flags "any process boundary with a
2931    ///   missing [`ConditionKind`]" reads
2932    ///   `boundary.postconditions.has_any_missing_kind()` at ONE
2933    ///   substrate primitive per test rather than restating the
2934    ///   negation body at every callsite.
2935    ///
2936    /// # Theory grounding
2937    ///
2938    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
2939    ///   The at-least-one halfspace projection lives at ONE substrate
2940    ///   site as a definitional negation of
2941    ///   [`Self::is_kind_saturated`]. Every downstream consumer whose
2942    ///   semantic reading is "at least one kind is absent" reads
2943    ///   through this primitive rather than negating `is_kind_saturated`
2944    ///   at every callsite or paying for the widened primitive's Vec
2945    ///   allocation.
2946    /// - THEORY.md §VI.1 — generation over composition. A new
2947    ///   [`ConditionKind`] variant added to `ALL` reaches this
2948    ///   primitive mechanically through the delegated
2949    ///   `is_kind_saturated` — a slice that was previously saturated
2950    ///   (returned `false` here) picks up the new missing variant and
2951    ///   returns `true` at every downstream `has-any-missing-kind`
2952    ///   callsite unless it also carries the new variant.
2953    fn has_any_missing_kind(&self) -> bool {
2954        !self.is_kind_saturated()
2955    }
2956
2957    /// Boolean cardinality-mid-endpoint peer of
2958    /// [`Self::has_any_missing_kind`] on the closed-set-complement
2959    /// axis — `true` iff EXACTLY ONE [`ConditionKind::ALL`] variant
2960    /// appears zero times in this slice (equivalently,
2961    /// [`Self::missing_kind_count`] `== 1`,
2962    /// [`Self::missing_kinds`]`.len() == 1`, and
2963    /// [`Self::first_missing_kind`] equals
2964    /// [`Self::last_missing_kind`] and is [`Some`]).
2965    ///
2966    /// Default body: a two-step-short-circuit closed-set walk over
2967    /// [`ConditionKind::ALL`] under a negated [`Self::has_kind`]
2968    /// predicate. Pulls up to two hits off the filtered iterator; the
2969    /// primitive returns `true` iff the first hit is [`Some`] and the
2970    /// second is [`None`], WITHOUT materializing
2971    /// [`Self::missing_kinds`]'s `Vec` and WITHOUT walking every slot
2972    /// to build [`Self::missing_kind_count`]'s scalar. Short-circuits
2973    /// at the SECOND missing kind — strictly cheaper than either
2974    /// widened primitive on every arm with `≥ 2` missing kinds.
2975    ///
2976    /// # Peer to [`crate::tagged_union::TaggedUnion::has_unique_missing_kind`]
2977    ///
2978    /// Slice-level peer of the tagged-union parent-level
2979    /// cardinality-mid-endpoint predicate one struct-layer up: where
2980    /// [`crate::tagged_union::TaggedUnion::has_unique_missing_kind`]
2981    /// answers "is EXACTLY ONE slot on the tagged-union parent
2982    /// empty?", `has_unique_missing_kind` answers "does EXACTLY ONE
2983    /// kind appear in NO condition of the slice?". Both compose
2984    /// against a two-step-short-circuit closed-set walk under a
2985    /// negated presence predicate (`!has(kind)` / `!has_kind(kind)`)
2986    /// at two adjacent typescape sites — the two primitives close the
2987    /// exactly-one-arm on the closed-set-complement axis at both
2988    /// struct layers under the SAME shape.
2989    ///
2990    /// # Sibling to the Boolean missing-cardinality trichotomy
2991    ///
2992    /// Second arm of the `{0, 1, ≥2}` cardinality trichotomy on the
2993    /// missing axis, closing the natural partition alongside
2994    /// [`Self::is_kind_saturated`] (zero-arm) and (once its slice-
2995    /// level peer lands) the many-arm predicate. Every slice
2996    /// satisfies EXACTLY ONE of the three Boolean projections — the
2997    /// three primitives partition `0..=ConditionKind::ALL.len()` at
2998    /// 0, 1, and ≥ 2 respectively. The composition law
2999    /// `has_unique_missing_kind() == (missing_kind_count() == 1)`
3000    /// binds the Boolean projection to the scalar primitive at the
3001    /// trait's default body — swept substrate-wide by
3002    /// [`assert_slice_refinement_composition_laws`] as its
3003    /// cardinality-mid-endpoint arm.
3004    ///
3005    /// # Semantics
3006    ///
3007    /// An empty slice returns `false` on any `N ≥ 2` closed set (every
3008    /// kind is missing — the fully-missing endpoint, `N` missing not
3009    /// `1`). A slice carrying `K` distinct kinds for `1 ≤ K ≤ N-2` on
3010    /// `N ≥ 3` closed sets returns `false` (`N - K ≥ 2` kinds missing).
3011    /// A slice at the near-saturation arm (carrying every kind except
3012    /// exactly one) returns `true` — the SOLE arrangement where
3013    /// `has_unique_missing_kind` returns `true`. A saturated slice
3014    /// returns `false` (zero missing).
3015    ///
3016    /// # Compounding future consumers
3017    ///
3018    /// - An operator-facing "one kind away from saturated" fast-path
3019    ///   discriminator on the near-saturation arm reads
3020    ///   `boundary.postconditions.has_unique_missing_kind()` at ONE
3021    ///   call site — one two-step short-circuit walk, no allocation,
3022    ///   no scalar equality against `1`, byte-for-byte peer of the
3023    ///   tagged-union `has-unique-missing-kind` classifier one struct-
3024    ///   layer up under the SAME two-step short-circuit shape.
3025    /// - A `has-unique-missing-kind` require-tag classifier arm
3026    ///   reaches this primitive with no allocation, byte-for-byte
3027    ///   peer of the tagged-union `has-unique-missing-kind` classifier
3028    ///   one struct-layer up.
3029    /// - A future gap-analysis diagnostic that prints "one remaining
3030    ///   ConditionKind not covered by this Boundary" pairs
3031    ///   `has_unique_missing_kind()` with
3032    ///   [`Self::first_missing_kind`] to name the SOLE remaining hole
3033    ///   without allocating [`Self::missing_kinds`]'s `Vec`.
3034    ///
3035    /// # Theory grounding
3036    ///
3037    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3038    ///   The cardinality-mid-endpoint projection on the missing axis
3039    ///   lives at ONE substrate site as a typed two-step-short-
3040    ///   circuit walk over [`ConditionKind::ALL`] under negated
3041    ///   [`Self::has_kind`] — byte-for-byte peer of
3042    ///   `missing_kind_count()` composed against `== 1`, but with a
3043    ///   second-missing-slot short-circuit that the scalar counter
3044    ///   primitive does not offer.
3045    /// - THEORY.md §VI.1 — generation over composition. A new
3046    ///   [`ConditionKind`] variant added to `ALL` reaches this
3047    ///   primitive mechanically through the short-circuit walk — a
3048    ///   slice previously at the near-saturation arm (returned `true`
3049    ///   here) that omits the new variant now has TWO missing kinds
3050    ///   and returns `false`; a slice previously at the
3051    ///   saturated-except-one-of-two arm on an `N == 2` closed set
3052    ///   remains at the near-saturation arm on `N ≥ 3` iff it
3053    ///   picks up every OTHER variant.
3054    fn has_unique_missing_kind(&self) -> bool {
3055        let mut it = ConditionKind::ALL
3056            .iter()
3057            .copied()
3058            .filter(|k| !self.has_kind(*k));
3059        it.next().is_some() && it.next().is_none()
3060    }
3061
3062    /// Boolean cardinality "≥ 2" many-arm peer of
3063    /// [`Self::has_unique_missing_kind`] on the closed-set-complement
3064    /// axis — `true` iff AT LEAST TWO [`ConditionKind::ALL`] variants
3065    /// appear zero times in this slice (equivalently,
3066    /// [`Self::missing_kind_count`] `>= 2` and
3067    /// [`Self::missing_kinds`]`.len() >= 2`).
3068    ///
3069    /// Default body: a two-step-short-circuit closed-set walk over
3070    /// [`ConditionKind::ALL`] under a negated [`Self::has_kind`]
3071    /// predicate. Pulls up to two hits off the filtered iterator; the
3072    /// primitive returns `true` iff BOTH the first and the second are
3073    /// [`Some`], WITHOUT materializing [`Self::missing_kinds`]'s `Vec`
3074    /// and WITHOUT walking every slot to build
3075    /// [`Self::missing_kind_count`]'s scalar. Short-circuits at the
3076    /// second missing kind — strictly cheaper than either widened
3077    /// primitive on every arm with `≥ 2` missing kinds. Byte-for-byte
3078    /// peer of [`crate::tagged_union::TaggedUnion::has_multiple_missing_kinds`]
3079    /// under the (populated, missing) complement axis one struct-
3080    /// layer up.
3081    ///
3082    /// # Peer to [`crate::tagged_union::TaggedUnion::has_multiple_missing_kinds`]
3083    ///
3084    /// Slice-level peer of the tagged-union parent-level cardinality
3085    /// many-arm predicate one struct-layer up: where
3086    /// [`crate::tagged_union::TaggedUnion::has_multiple_missing_kinds`]
3087    /// answers "are AT LEAST TWO slots on the tagged-union parent
3088    /// empty?", `has_multiple_missing_kinds` answers "do AT LEAST TWO
3089    /// kinds appear in NO condition of the slice?". Both compose
3090    /// against a two-step-short-circuit closed-set walk under a
3091    /// negated presence predicate (`!has(kind)` / `!has_kind(kind)`)
3092    /// at two adjacent typescape sites — the two primitives close the
3093    /// at-least-two arm on the closed-set-complement axis at both
3094    /// struct layers under the SAME shape.
3095    ///
3096    /// # Sibling to the Boolean missing-cardinality trichotomy
3097    ///
3098    /// Third and final arm of the `{0, 1, ≥2}` cardinality trichotomy
3099    /// on the missing axis at the slice level, closing the natural
3100    /// partition alongside [`Self::is_kind_saturated`] (zero-arm) and
3101    /// [`Self::has_unique_missing_kind`] (one-arm). Every slice
3102    /// satisfies EXACTLY ONE of the three Boolean projections — the
3103    /// three primitives partition `0..=ConditionKind::ALL.len()` at
3104    /// 0, 1, and ≥ 2 respectively. The composition law
3105    /// `has_multiple_missing_kinds() == (missing_kind_count() >= 2)`
3106    /// binds the Boolean projection to the scalar primitive at the
3107    /// trait's default body — swept substrate-wide by
3108    /// [`assert_slice_refinement_composition_laws`] as its
3109    /// cardinality-many-arm arm.
3110    ///
3111    /// # Semantics
3112    ///
3113    /// An empty slice returns `true` on any `N ≥ 2` closed set (every
3114    /// kind is missing — the fully-missing endpoint, `N ≥ 2` missing).
3115    /// A slice carrying `K` distinct kinds for `1 ≤ K ≤ N-2` on
3116    /// `N ≥ 3` closed sets returns `true` (`N - K ≥ 2` kinds missing).
3117    /// A slice at the near-saturation arm (carrying every kind except
3118    /// exactly one) returns `false` — the SOLE-missing arrangement
3119    /// where `has_multiple_missing_kinds` returns `false` (exactly
3120    /// one missing, not ≥ 2). A saturated slice returns `false`
3121    /// (zero missing).
3122    ///
3123    /// # Compounding future consumers
3124    ///
3125    /// - An operator-facing "≥ 2 dependencies still unfulfilled" fast-
3126    ///   path discriminator on the many-missing arm reads
3127    ///   `boundary.postconditions.has_multiple_missing_kinds()` at ONE
3128    ///   call site — one two-step short-circuit walk, no allocation,
3129    ///   no scalar comparison against `>= 2`, byte-for-byte peer of
3130    ///   the tagged-union `has-multiple-missing-kinds` classifier one
3131    ///   struct-layer up under the SAME two-step short-circuit shape.
3132    /// - A `has-multiple-missing-kinds` require-tag classifier arm
3133    ///   reaches this primitive with no allocation, byte-for-byte
3134    ///   peer of the tagged-union `has-multiple-missing-kinds`
3135    ///   classifier one struct-layer up.
3136    /// - A future coverage-gap diagnostic that says "≥ 2 remaining
3137    ///   ConditionKinds not covered by this Boundary" reads
3138    ///   `has_multiple_missing_kinds()` at ONE call site without
3139    ///   allocating [`Self::missing_kinds`]'s `Vec`.
3140    ///
3141    /// # Theory grounding
3142    ///
3143    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3144    ///   The cardinality-many-arm projection on the missing axis
3145    ///   lives at ONE substrate site as a typed two-step-short-
3146    ///   circuit walk over [`ConditionKind::ALL`] under negated
3147    ///   [`Self::has_kind`] — byte-for-byte peer of
3148    ///   `missing_kind_count()` composed against `>= 2`, but with a
3149    ///   second-missing-slot short-circuit that the scalar counter
3150    ///   primitive does not offer.
3151    /// - THEORY.md §VI.1 — generation over composition. A new
3152    ///   [`ConditionKind`] variant added to `ALL` reaches this
3153    ///   primitive mechanically through the short-circuit walk — a
3154    ///   slice previously at the near-saturation arm (returned
3155    ///   `false` here) that omits the new variant now has TWO missing
3156    ///   kinds and flips to `true`; a slice previously at the
3157    ///   saturated arm on an `N == 2` closed set that omits the new
3158    ///   variant flips from `false` to `true` (`1 ≥ 2` false → `1`
3159    ///   missing on `N == 3`, but this workspace has `N == 8`, so
3160    ///   the flip surfaces well before the endpoint).
3161    fn has_multiple_missing_kinds(&self) -> bool {
3162        let mut it = ConditionKind::ALL
3163            .iter()
3164            .copied()
3165            .filter(|k| !self.has_kind(*k));
3166        it.next().is_some() && it.next().is_some()
3167    }
3168
3169    /// Boolean cardinality "≤ 1" negation peer of
3170    /// [`Self::has_multiple_missing_kinds`] on the closed-set-complement
3171    /// axis — `true` iff AT MOST ONE [`ConditionKind::ALL`] variant
3172    /// appears zero times in this slice (equivalently,
3173    /// [`Self::missing_kind_count`] `<= 1` and
3174    /// [`Self::missing_kinds`]`.len() <= 1`). Names the arm where the
3175    /// slice is SATURATED-OR-NEAR-SATURATED (zero or exactly one kind
3176    /// missing).
3177    ///
3178    /// Default body: `!self.has_multiple_missing_kinds()` — a
3179    /// definitional Boolean negation of the many-arm primitive. Short-
3180    /// circuits transitively through
3181    /// [`Self::has_multiple_missing_kinds`]'s two-step short-circuit
3182    /// closed-set walk: returns `true` as soon as the many-arm walk
3183    /// stops with fewer than two missing hits, WITHOUT materializing
3184    /// [`Self::missing_kinds`]'s `Vec` and WITHOUT walking every slot to
3185    /// build [`Self::missing_kind_count`]'s scalar. Byte-for-byte peer
3186    /// of [`crate::tagged_union::TaggedUnion::has_at_most_one_missing_kind`]
3187    /// under the (populated, missing) complement axis one struct-layer
3188    /// up, both composed as the same definitional negation of their
3189    /// respective many-arm primitives.
3190    ///
3191    /// # Peer to [`crate::tagged_union::TaggedUnion::has_at_most_one_missing_kind`]
3192    ///
3193    /// Slice-level peer of the tagged-union parent-level cardinality
3194    /// "≤ 1" predicate one struct-layer up: where
3195    /// [`crate::tagged_union::TaggedUnion::has_at_most_one_missing_kind`]
3196    /// answers "does the tagged-union parent have AT MOST ONE empty
3197    /// slot?", `has_at_most_one_missing_kind` answers "do AT MOST ONE
3198    /// kind appear in NO condition of the slice?". Both compose as the
3199    /// definitional Boolean negation of their many-arm primitive
3200    /// (`!has_multiple_missing_kinds()`) at two adjacent typescape
3201    /// sites — the two primitives close the "≤ 1" arm on the closed-
3202    /// set-complement axis at both struct layers under the SAME shape.
3203    ///
3204    /// # Sibling to the Boolean missing-cardinality pentachotomy
3205    ///
3206    /// Fourth arm of the `{0, 1, ≥1, ≤1, ≥2}` Boolean-cardinality
3207    /// pentachotomy on the missing axis at the slice level, closing
3208    /// the Boolean-negation grid alongside
3209    /// [`Self::is_kind_saturated`] (=0 zero-arm),
3210    /// [`Self::has_unique_missing_kind`] (=1 mid-endpoint),
3211    /// [`Self::has_any_missing_kind`] (≥1 halfspace), and
3212    /// [`Self::has_multiple_missing_kinds`] (≥2 many-arm). The
3213    /// {≤1, ≥2} pair sit on the Boolean-negation axis:
3214    /// `has_at_most_one_missing_kind == !has_multiple_missing_kinds` on
3215    /// every arm. The {0, 1} union arm sits on the trichotomy-union
3216    /// axis: `has_at_most_one_missing_kind == is_kind_saturated ||
3217    /// has_unique_missing_kind` on every arm. Both composition laws
3218    /// bind the "≤ 1" Boolean projection to the sibling primitives at
3219    /// the trait's default body — swept substrate-wide by
3220    /// [`assert_slice_refinement_composition_laws`] as its "≤ 1" arm.
3221    ///
3222    /// # Semantics
3223    ///
3224    /// An empty slice returns `false` on any `N ≥ 2` closed set
3225    /// (every kind is missing — `N ≥ 2` missing, not `≤ 1`).
3226    /// A slice carrying `K` distinct kinds for `1 ≤ K ≤ N-2` on `N ≥ 3`
3227    /// closed sets returns `false` (`N - K ≥ 2` kinds missing).
3228    /// A slice at the near-saturation arm (carrying every kind except
3229    /// exactly one) returns `true` (exactly 1 missing, `≤ 1`). A
3230    /// saturated slice returns `true` (0 missing, `≤ 1`) — the union
3231    /// of the two "≤ 1" arms (`=0` and `=1`) is exactly the
3232    /// arrangement space where the primitive returns `true`.
3233    ///
3234    /// # Compounding future consumers
3235    ///
3236    /// - An operator-facing "at most one dependency still unfulfilled"
3237    ///   fast-path discriminator on the near-saturated / saturated
3238    ///   arms reads `boundary.postconditions.has_at_most_one_missing_kind()`
3239    ///   at ONE call site — one bit-flip on the many-arm's two-step
3240    ///   short-circuit walk, no allocation, no scalar comparison
3241    ///   against `<= 1`, byte-for-byte peer of the tagged-union
3242    ///   `has-at-most-one-missing-kind` classifier one struct-layer up
3243    ///   under the SAME `!has_multiple_missing_kinds` definitional
3244    ///   negation shape.
3245    /// - A `has-at-most-one-missing-kind` require-tag classifier arm
3246    ///   reaches this primitive with no allocation, closing the
3247    ///   {0, 1, ≥ 2, ≤ 1} cardinality-Boolean grid on the missing axis
3248    ///   at the slice level alongside its sibling
3249    ///   `has-multiple-missing-kinds` under the Boolean negation axis.
3250    /// - A future coverage-gap diagnostic that says "at most one
3251    ///   remaining ConditionKind not covered by this Boundary" reads
3252    ///   `has_at_most_one_missing_kind()` at ONE call site without
3253    ///   allocating [`Self::missing_kinds`]'s `Vec`.
3254    ///
3255    /// # Theory grounding
3256    ///
3257    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3258    ///   The cardinality "≤ 1" projection on the missing axis lives
3259    ///   at ONE substrate site as the definitional Boolean negation
3260    ///   of [`Self::has_multiple_missing_kinds`]; the three composition
3261    ///   forms (`!has_multiple_missing_kinds()`, `missing_kind_count() <= 1`,
3262    ///   and `is_kind_saturated() || has_unique_missing_kind()`)
3263    ///   compose through the SAME two-step-short-circuit walk shape
3264    ///   one negation up, byte-for-byte identical on every arm.
3265    /// - THEORY.md §VI.1 — generation over composition. A new
3266    ///   [`ConditionKind`] variant added to `ALL` reaches this
3267    ///   primitive mechanically through the delegated
3268    ///   [`Self::has_multiple_missing_kinds`] — a slice previously at
3269    ///   the near-saturation arm (returned `true` here) that omits the
3270    ///   new variant now has TWO missing kinds and flips to `false`.
3271    fn has_at_most_one_missing_kind(&self) -> bool {
3272        !self.has_multiple_missing_kinds()
3273    }
3274
3275    /// Boolean per-kind complement of [`Self::has_kind`] — `true` iff
3276    /// NO [`Condition`] in this slice carries the given
3277    /// [`ConditionKind`] (equivalently, the kind is a member of
3278    /// [`Self::missing_kinds`]).
3279    ///
3280    /// Default body: `!self.has_kind(kind)` — a definitional negation
3281    /// of the presence-probe primitive. Short-circuits transitively
3282    /// through [`Self::has_kind`]'s composition down to
3283    /// [`Self::iter_kind`]: `!self.find_kind(kind).is_some()` returns
3284    /// as soon as any match is found (yielding `false`) without
3285    /// walking the rest of the slice, WITHOUT materializing
3286    /// [`Self::missing_kinds`]'s `Vec` per-kind for a per-kind
3287    /// question, and WITHOUT allocating the closed-set-complement scan.
3288    ///
3289    /// # Peer to [`crate::tagged_union::TaggedUnion::lacks`]
3290    ///
3291    /// Slice-level peer of the tagged-union parent-level closed-set-
3292    /// complement predicate one struct-layer up: where
3293    /// [`crate::tagged_union::TaggedUnion::lacks`] answers "is THIS
3294    /// kind's slot on the tagged-union parent empty?", `lacks_kind`
3295    /// answers "does THIS kind appear in NO condition of the slice?".
3296    /// Both compose against their per-kind presence primitive under a
3297    /// definitional negation (`!has(kind)` / `!has_kind(kind)`) at two
3298    /// adjacent typescape sites — the two primitives close the
3299    /// closed-set-complement invariant on the per-kind axis at both
3300    /// struct layers under the SAME shape.
3301    ///
3302    /// # Sibling to [`Self::has_kind`]
3303    ///
3304    /// Boolean per-kind complement peer of the point-probe primitive
3305    /// on the closed-set-complement axis — where `has_kind` returns
3306    /// `true` iff the addressed kind appears at least once,
3307    /// `lacks_kind` returns its negation: `true` iff the addressed kind
3308    /// appears zero times. Together the two Booleans partition the
3309    /// (slice, kind) matrix at the slice-level presence-probe axis:
3310    /// exactly one of `has_kind(k)` and `lacks_kind(k)` is `true` for
3311    /// every `k ∈ ConditionKind::ALL`. The definitional complement law
3312    /// `lacks_kind(k) == !has_kind(k)` is pinned as a first-class typed
3313    /// invariant by the trait's own default body and swept substrate-
3314    /// wide by [`assert_slice_refinement_composition_laws`] as its
3315    /// per-kind-complement arm.
3316    ///
3317    /// # Sibling to [`Self::missing_kinds`] / [`Self::missing_kind_count`]
3318    ///
3319    /// Per-kind Boolean projection of the closed-set-complement
3320    /// widened + scalar primitives — where `missing_kinds` returns the
3321    /// FULL missing-set (a `Vec<ConditionKind>` of every absent kind)
3322    /// and `missing_kind_count` returns its cardinality (a `usize` in
3323    /// `0..=ConditionKind::ALL.len()`), `lacks_kind` collapses the
3324    /// missing-set to its per-kind membership Boolean for ONE
3325    /// addressed kind. The composition law
3326    /// `lacks_kind(k) == missing_kinds().contains(&k)` binds this
3327    /// Boolean projection to the widened closed-set-complement
3328    /// primitive at the trait's default body — strictly cheaper than
3329    /// the widened primitive on every per-kind question because the
3330    /// negation short-circuits at the first match on the has-side
3331    /// walk rather than allocating the closed-set-complement scan.
3332    ///
3333    /// # Semantics
3334    ///
3335    /// An empty slice returns `true` for every [`ConditionKind`] (no
3336    /// kind appears, so every kind is lacked). A slice carrying kind
3337    /// `k` at any position returns `false` for `lacks_kind(k)` and
3338    /// `true` for `lacks_kind(k')` for every `k' ≠ k` (single-kind
3339    /// coverage). A saturated slice (every kind appears at least once)
3340    /// returns `false` on every arm — the SOLE arrangement where the
3341    /// primitive returns `false` for every kind.
3342    ///
3343    /// # Compounding future consumers
3344    ///
3345    /// - A `lacks-<kind>` require-tag classifier arm reaches this
3346    ///   primitive with no allocation, byte-for-byte peer of the
3347    ///   tagged-union `lacks-<kind>` classifier one struct-layer up
3348    ///   under the SAME `!has(kind)` definitional negation shape.
3349    /// - A dependency-satisfaction coherence check that enforces "no
3350    ///   process boundary lacks a `ClosedLoopAuth` postcondition" reads
3351    ///   `boundary.postconditions.lacks_kind(ConditionKind::ClosedLoopAuth)`
3352    ///   at ONE call site rather than negating
3353    ///   `boundary.postconditions.has_kind(ConditionKind::ClosedLoopAuth)`
3354    ///   at the callsite or materializing the closed-set complement
3355    ///   with `missing_kinds().contains(&k)`.
3356    /// - A "still missing: <kind>" diagnostic that reports the FIRST
3357    ///   unmet postcondition kind reads `slice.lacks_kind(k)` inside a
3358    ///   `ConditionKind::ALL` fold at ONE substrate primitive per test
3359    ///   rather than restating the negation body at every callsite.
3360    ///
3361    /// # Theory grounding
3362    ///
3363    /// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
3364    ///   The per-kind closed-set-complement projection lives at ONE
3365    ///   substrate site as a definitional negation of [`Self::has_kind`].
3366    ///   Every downstream consumer whose semantic reading is "the
3367    ///   missing set contains THIS kind" reads through this primitive
3368    ///   rather than negating `has_kind` at every callsite or paying
3369    ///   for the closed-set-complement scan.
3370    /// - THEORY.md §VI.1 — generation over composition. A new
3371    ///   [`ConditionKind`] variant added to `ALL` reaches this
3372    ///   primitive mechanically through the delegated `has_kind` —
3373    ///   every downstream `lacks-<kind>` classifier arm sees the wider
3374    ///   kind set without further per-caller edit.
3375    fn lacks_kind(&self, kind: ConditionKind) -> bool {
3376        !self.has_kind(kind)
3377    }
3378}
3379
3380/// Iterator yielded by [`ConditionSliceExt::iter_kind`] — the widened
3381/// primitive on the slice-level presence-probe axis. Wraps a
3382/// [`std::slice::Iter`] over `Condition` values with a
3383/// [`ConditionKind`] discriminator; [`Iterator::next`] short-circuits
3384/// via [`std::iter::Iterator::find`] on the wrapped iterator so the
3385/// filter walk is byte-identical to `self.iter().filter(|c| c.kind ==
3386/// kind).next()` without paying for the anonymous-closure type
3387/// erasure a chained-adapter return position would carry.
3388///
3389/// # Why a named type
3390///
3391/// [`ConditionSliceExt::iter_kind`] returns this concrete type rather
3392/// than `impl Iterator<Item = &Condition>` so downstream consumers
3393/// (a fleet-wide audit dump that stores match streams in a struct
3394/// field, a coherence check that composes the iterator against
3395/// [`std::iter::Chain`] across pre-/post-conditions) name the
3396/// primitive's return without pulling in RPITIT's unnameable
3397/// per-callsite type. [`Boundary::iter_condition_kind`] and
3398/// [`crate::ephemeral::EphemeralSpec::iter_condition_kind`] chain two
3399/// [`KindMatches`] iterators via [`Iterator::chain`] — the resulting
3400/// [`std::iter::Chain<KindMatches<'_>, KindMatches<'_>>`] is itself
3401/// a standard nameable type.
3402pub struct KindMatches<'a> {
3403    inner: std::slice::Iter<'a, Condition>,
3404    kind: ConditionKind,
3405}
3406
3407impl<'a> Iterator for KindMatches<'a> {
3408    type Item = &'a Condition;
3409
3410    fn next(&mut self) -> Option<Self::Item> {
3411        self.inner.by_ref().find(|c| c.kind == self.kind)
3412    }
3413}
3414
3415impl ConditionSliceExt for [Condition] {
3416    fn iter_kind(&self, kind: ConditionKind) -> KindMatches<'_> {
3417        KindMatches {
3418            inner: self.iter(),
3419            kind,
3420        }
3421    }
3422}
3423
3424/// Generic slice-level substrate testkit — pins the FOUR composition
3425/// laws that bind the [`ConditionSliceExt`] refinement algebra
3426/// (`iter_kind` → `find_kind` → `has_kind` → `count_kind`) at ONE
3427/// call site per authored arrangement, sweeping [`ConditionKind::ALL`].
3428///
3429/// The [`ConditionSliceExt`] trait publishes four refinements on the
3430/// slice-level presence-probe axis:
3431///
3432/// | refinement | return type | default body                        |
3433/// |------------|-------------|-------------------------------------|
3434/// | `iter_kind`| [`KindMatches`]      | (widened primitive, required)      |
3435/// | `find_kind`| `Option<&Condition>` | `self.iter_kind(k).next()`         |
3436/// | `has_kind` | `bool`               | `self.find_kind(k).is_some()`      |
3437/// | `count_kind`| `usize`             | `self.iter_kind(k).count()`        |
3438///
3439/// The three coarser refinements are typed projections of the widened
3440/// primitive by construction. The composition laws that bind them
3441/// (and therefore surface any implementor that overrode a default
3442/// with a divergent walk shape — a stored-length cache that drifted,
3443/// a `.rev().find(...)` returning trailing-first, a `.step_by(2)`
3444/// artifact from a copy-paste of `iter_kind`) sweep at ONE typed
3445/// substrate site through this primitive:
3446///
3447/// 1. **`find ↔ iter`**: `find_kind(k) == iter_kind(k).next()` — the
3448///    first-match probe equals the widened stream's first yield.
3449/// 2. **`count ↔ iter`**: `count_kind(k) == iter_kind(k).count()` —
3450///    the cardinality probe equals the widened stream's yield count.
3451/// 3. **`has ↔ find`**: `has_kind(k) == find_kind(k).is_some()` —
3452///    the presence bit equals the first-match probe's `is_some()`.
3453/// 4. **`has ↔ count`**: `has_kind(k) == (count_kind(k) > 0)` — the
3454///    presence bit equals the cardinality's positivity test (the
3455///    dual composition path from `has` back to the widened primitive
3456///    that doesn't go through `find`).
3457///
3458/// Pre-lift each composition law lived at its own hand-authored
3459/// nested-`for` loop test in [`tatara_process::boundary`] tests
3460/// (`condition_slice_find_kind_equals_iter_kind_next`,
3461/// `condition_slice_count_kind_equals_iter_kind_count`,
3462/// `condition_slice_has_kind_equals_find_kind_is_some`,
3463/// `condition_slice_has_and_find_equal_count_greater_than_zero`) —
3464/// four sibling test bodies whose only per-law knobs were the
3465/// projection functions being bridged. Post-lift each authored
3466/// arrangement (empty, single-element, dual-populated, duplicate-
3467/// populated) pins ALL FOUR laws through ONE
3468/// `assert_slice_refinement_composition_laws(slice)` call whose body
3469/// is the substrate primitive's own sweep.
3470///
3471/// The primitive binds `<S: ConditionSliceExt + ?Sized>` so both a
3472/// bare `&[Condition]` and any future implementor of the trait
3473/// (a wrapper type with additional invariants, an alternative slice
3474/// projection over a builder's staging Vec) picks up the four-law
3475/// composition contract through ONE call site. `?Sized` lets the
3476/// caller pass `slice.as_slice()` or `&owned[..]` without an
3477/// intermediate reference dance.
3478///
3479/// # Compounding
3480///
3481/// A FIFTH refinement added to [`ConditionSliceExt`] (a hypothetical
3482/// `nth_kind(k, n) -> Option<&Condition>` for indexed match access,
3483/// a `distinct_kinds()` aggregate that returns which kinds appear at
3484/// least once, a `has_kind_matching(pred)` closure-based predicate
3485/// probe) lands its composition-law pins as ONE new arm inside this
3486/// primitive's sweep body. Every downstream test that already reaches
3487/// this primitive picks up the fifth-refinement pin mechanically —
3488/// no per-arrangement author-time enumeration of the new law across
3489/// the four sibling composition-law sites, no re-authored `for kind
3490/// in ConditionKind::ALL { … }` sweep at every consumer.
3491///
3492/// Symmetrical shape to
3493/// [`crate::tagged_union::assert_find_agrees_with_has`] on the
3494/// tagged-union parent axis: both project a widened-refinement /
3495/// coarser-refinement composition law contract onto ONE typed
3496/// substrate call site, both bind `<T: /* refinement carrier */>`
3497/// generically, both sweep the addressed closed set
3498/// ([`ConditionKind::ALL`] here, `<T::Kind as ClosedSet>::ALL`
3499/// there). The two primitives close the "refinement axis composes"
3500/// invariant at two adjacent typescape sites — one per closed-set-
3501/// addressed slice-level refinement, one per closed-set-addressed
3502/// tagged-union parent-level refinement.
3503///
3504/// Theory anchor: THEORY.md §II.1 invariant 5 — composition preserves
3505/// proofs. The four coarser refinements are typed projections of the
3506/// widened primitive, and this substrate primitive turns each
3507/// projection's composition law from doc-prose into a first-class
3508/// typed theorem provable generically over any
3509/// `S: ConditionSliceExt + ?Sized`. THEORY.md §VI.1 — generation over
3510/// composition; a new [`ConditionKind`] variant added to `ALL` reaches
3511/// every downstream composition-law consumer through the SAME
3512/// closed-set sweep with no per-caller edit.
3513#[track_caller]
3514pub fn assert_slice_refinement_composition_laws<S>(slice: &S)
3515where
3516    S: ConditionSliceExt + ?Sized,
3517{
3518    let distinct = slice.distinct_kinds();
3519    for kind in ConditionKind::ALL {
3520        let find_result = slice.find_kind(kind);
3521        let has_result = slice.has_kind(kind);
3522        let count_result = slice.count_kind(kind);
3523        let iter_next_kind = slice.iter_kind(kind).next().map(|c| c.kind);
3524        let iter_count = slice.iter_kind(kind).count();
3525
3526        // find ↔ iter
3527        assert_eq!(
3528            find_result.map(|c| c.kind),
3529            iter_next_kind,
3530            "find_kind({kind:?}) drifted from iter_kind({kind:?}).next()",
3531        );
3532        // count ↔ iter
3533        assert_eq!(
3534            count_result, iter_count,
3535            "count_kind({kind:?}) drifted from iter_kind({kind:?}).count()",
3536        );
3537        // has ↔ find
3538        assert_eq!(
3539            has_result,
3540            find_result.is_some(),
3541            "has_kind({kind:?}) drifted from find_kind({kind:?}).is_some()",
3542        );
3543        // has ↔ count
3544        assert_eq!(
3545            has_result,
3546            count_result > 0,
3547            "has_kind({kind:?}) drifted from (count_kind({kind:?}) > 0)",
3548        );
3549        // distinct ↔ has (per-kind membership on the closed-set-inversion axis)
3550        assert_eq!(
3551            distinct.contains(&kind),
3552            has_result,
3553            "distinct_kinds().contains({kind:?}) drifted from has_kind({kind:?})",
3554        );
3555    }
3556
3557    // distinct ↔ ALL-filter (canonical subsequence — closed-set-inversion
3558    // walks ConditionKind::ALL in order, filters by has_kind, dedups by
3559    // construction). A regression that (a) returned duplicates (a naive
3560    // `.iter().map(|c| c.kind).collect()` override that skipped dedup),
3561    // (b) drifted the walk order from ConditionKind::ALL to slice-encounter
3562    // order, or (c) returned a superset containing absent kinds surfaces
3563    // HERE at the substrate boundary.
3564    let canonical: Vec<ConditionKind> = ConditionKind::ALL
3565        .into_iter()
3566        .filter(|k| slice.has_kind(*k))
3567        .collect();
3568    assert_eq!(
3569        distinct, canonical,
3570        "distinct_kinds() must yield ConditionKind::ALL-ordered subsequence of kinds where has_kind is true (no duplicates, canonical order)",
3571    );
3572
3573    // distinct_kind_count ↔ distinct_kinds.len() — the scalar
3574    // cardinality projection of the closed-set-inversion widened
3575    // primitive. A regression that overrode `distinct_kind_count` to
3576    // skip a kind, double-count a slot, or drift the walk from
3577    // `ConditionKind::ALL` surfaces HERE at the substrate boundary,
3578    // not as silent drift at every downstream `distinct-count-<n>`
3579    // require-tag classifier or audit-dump callsite.
3580    assert_eq!(
3581        slice.distinct_kind_count(),
3582        distinct.len(),
3583        "distinct_kind_count() drifted from distinct_kinds().len()",
3584    );
3585
3586    // missing ↔ has (per-kind complement on the closed-set-inversion
3587    // axis). Byte-for-byte peer to the `distinct ↔ has` arm above: the
3588    // present-side widened primitive `distinct_kinds` binds to
3589    // `has_kind` via `contains(&k) == has_kind(k)`; the missing-side
3590    // widened primitive `missing_kinds` binds via
3591    // `contains(&k) == !has_kind(k)` — the SAME point-probe primitive
3592    // reached under a negated predicate. A regression that overrode
3593    // `missing_kinds` to omit the negation (returning `distinct_kinds`
3594    // instead), inverted the wrong side, or dropped a variant surfaces
3595    // HERE.
3596    let missing = slice.missing_kinds();
3597    for kind in ConditionKind::ALL {
3598        assert_eq!(
3599            missing.contains(&kind),
3600            !slice.has_kind(kind),
3601            "missing_kinds().contains({kind:?}) drifted from !has_kind({kind:?})",
3602        );
3603    }
3604
3605    // missing ↔ ALL-filter (canonical subsequence — closed-set
3606    // complement walks ConditionKind::ALL in order, filters by
3607    // !has_kind, dedups by construction). Peer to the `distinct ↔
3608    // ALL-filter` arm above; catches ordering + dedup drift on the
3609    // complement side that the per-kind membership arm cannot detect
3610    // on its own.
3611    let canonical_missing: Vec<ConditionKind> = ConditionKind::ALL
3612        .into_iter()
3613        .filter(|k| !slice.has_kind(*k))
3614        .collect();
3615    assert_eq!(
3616        missing, canonical_missing,
3617        "missing_kinds() must yield ConditionKind::ALL-ordered subsequence of kinds where has_kind is false (no duplicates, canonical order)",
3618    );
3619
3620    // (distinct, missing) partition ConditionKind::ALL — three peer
3621    // laws that bind the closed-set-inversion widened primitive
3622    // `distinct_kinds` to its complement peer `missing_kinds`:
3623    //
3624    // 1. Disjoint: every kind appears in AT MOST one of the two sets.
3625    // 2. Covering: every kind appears in AT LEAST one of the two sets
3626    //    (equivalent to the union covering ConditionKind::ALL).
3627    // 3. Cardinality partition: `distinct.len() + missing.len() ==
3628    //    ConditionKind::ALL.len()` — the scalar consequence of (1) +
3629    //    (2) that a caller reaching for the cardinality peer would
3630    //    otherwise pay for the two allocations at every callsite.
3631    for kind in ConditionKind::ALL {
3632        assert!(
3633            !(distinct.contains(&kind) && missing.contains(&kind)),
3634            "(distinct_kinds, missing_kinds) partition invariant violated — both contain {kind:?}",
3635        );
3636        assert!(
3637            distinct.contains(&kind) || missing.contains(&kind),
3638            "(distinct_kinds, missing_kinds) partition invariant violated — neither contains {kind:?}",
3639        );
3640    }
3641    assert_eq!(
3642        distinct.len() + missing.len(),
3643        ConditionKind::ALL.len(),
3644        "(distinct_kinds, missing_kinds) cardinality partition drift — sum {} ≠ ConditionKind::ALL.len() {}",
3645        distinct.len() + missing.len(),
3646        ConditionKind::ALL.len(),
3647    );
3648
3649    // missing_kind_count ↔ missing_kinds.len() — the scalar cardinality
3650    // projection of the closed-set-complement widened primitive. A
3651    // regression that overrode `missing_kind_count` to drop the
3652    // negation (returning `distinct_kind_count`), skip a kind, double-
3653    // count a slot, or drift the walk from `ConditionKind::ALL`
3654    // surfaces HERE at the substrate boundary, not as silent drift at
3655    // every downstream `condition-kinds-missing-<n>` require-tag
3656    // classifier or gap-analysis-dashboard callsite.
3657    assert_eq!(
3658        slice.missing_kind_count(),
3659        missing.len(),
3660        "missing_kind_count() drifted from missing_kinds().len()",
3661    );
3662
3663    // (distinct_kind_count, missing_kind_count) partition
3664    // ConditionKind::ALL's cardinality — the scalar consequence of the
3665    // widened-primitive partition law `distinct ∪ missing == ALL,
3666    // disjoint` above. A regression that (a) drifted the scalar
3667    // cardinality peer from the widened primitive on either side or
3668    // (b) drifted the partition invariant surfaces HERE at ONE typed
3669    // arm rather than as silent drift at every scalar-cardinality
3670    // callsite that reaches for the sum.
3671    assert_eq!(
3672        slice.distinct_kind_count() + slice.missing_kind_count(),
3673        ConditionKind::ALL.len(),
3674        "(distinct_kind_count, missing_kind_count) scalar partition drift — sum {} ≠ ConditionKind::ALL.len() {}",
3675        slice.distinct_kind_count() + slice.missing_kind_count(),
3676        ConditionKind::ALL.len(),
3677    );
3678
3679    // first_distinct_kind ↔ distinct_kinds.first().copied() — the
3680    // earliest-element scalar projection of the closed-set-inversion
3681    // widened primitive. Peer of `distinct_kind_count ↔ distinct_kinds
3682    // .len()` on the scalar-projection axis: where the cardinality peer
3683    // collapses the SET to its length, the earliest-element peer
3684    // collapses the SET to its first element. A regression that
3685    // overrode `first_distinct_kind` to skip a kind, drift the walk
3686    // from ConditionKind::ALL, forget the short-circuit (returning
3687    // the LAST hit), or diverge from the widened primitive's canonical
3688    // ordering surfaces HERE at the substrate boundary, not as silent
3689    // drift at every downstream `first-distinct-<kind>` require-tag
3690    // classifier callsite.
3691    assert_eq!(
3692        slice.first_distinct_kind(),
3693        distinct.first().copied(),
3694        "first_distinct_kind() drifted from distinct_kinds().first().copied()",
3695    );
3696
3697    // first_missing_kind ↔ missing_kinds.first().copied() — the
3698    // earliest-element scalar projection of the closed-set-complement
3699    // widened primitive. Byte-for-byte peer of `first_distinct_kind`
3700    // one axis over under a negated predicate: where
3701    // `first_distinct_kind` scalar-projects the closed-set-INVERSION
3702    // widened primitive onto its earliest element, this arm scalar-
3703    // projects the closed-set-COMPLEMENT widened primitive onto its
3704    // earliest element. A regression that overrode `first_missing_kind`
3705    // to drop the negation (returning `first_distinct_kind`), skip a
3706    // kind, drift the walk from ConditionKind::ALL, or forget the
3707    // short-circuit (returning the LAST missing hit) surfaces HERE at
3708    // the substrate boundary, not as silent drift at every downstream
3709    // `first-missing-<kind>` require-tag classifier callsite.
3710    assert_eq!(
3711        slice.first_missing_kind(),
3712        missing.first().copied(),
3713        "first_missing_kind() drifted from missing_kinds().first().copied()",
3714    );
3715
3716    // last_distinct_kind ↔ distinct_kinds.last().copied() — the
3717    // latest-element scalar projection of the closed-set-inversion
3718    // widened primitive. Time-reversed peer of `first_distinct_kind
3719    // ↔ distinct_kinds.first().copied()` under the SAME `has_kind`
3720    // predicate but with the closed-set walk reversed: where the
3721    // earliest-element peer picks the smallest ALL index that hits,
3722    // this arm picks the LARGEST. A regression that overrode
3723    // `last_distinct_kind` to skip a kind, drift the walk direction
3724    // (returning `first_distinct_kind`), forget the short-circuit
3725    // (returning `distinct_kinds().rev().next()` allocation), or
3726    // diverge from the widened primitive's canonical ordering
3727    // surfaces HERE at the substrate boundary, not as silent drift
3728    // at every downstream `last-distinct-<kind>` require-tag
3729    // classifier callsite.
3730    assert_eq!(
3731        slice.last_distinct_kind(),
3732        distinct.last().copied(),
3733        "last_distinct_kind() drifted from distinct_kinds().last().copied()",
3734    );
3735
3736    // last_missing_kind ↔ missing_kinds.last().copied() — the
3737    // latest-element scalar projection of the closed-set-complement
3738    // widened primitive. Byte-for-byte peer of `last_distinct_kind`
3739    // one axis over under a NEGATED predicate: where
3740    // `last_distinct_kind` scalar-projects the closed-set-INVERSION
3741    // widened primitive onto its LATEST element, this arm scalar-
3742    // projects the closed-set-COMPLEMENT widened primitive onto its
3743    // LATEST element. A regression that overrode `last_missing_kind`
3744    // to drop the negation (returning `last_distinct_kind`), reverse
3745    // the walk direction (returning `first_missing_kind`), skip a
3746    // kind, or forget the short-circuit surfaces HERE at the
3747    // substrate boundary, not as silent drift at every downstream
3748    // `last-missing-<kind>` require-tag classifier callsite.
3749    assert_eq!(
3750        slice.last_missing_kind(),
3751        missing.last().copied(),
3752        "last_missing_kind() drifted from missing_kinds().last().copied()",
3753    );
3754
3755    // is_kind_saturated ↔ (missing_kind_count == 0) — the Boolean
3756    // saturation-endpoint projection of the closed-set-complement
3757    // scalar cardinality. Peer of `first_missing_kind ↔ missing_kinds
3758    // .first().copied()` on the endpoint-projection axis: where the
3759    // earliest-element peer collapses the missing SET to its first
3760    // element, this Boolean peer collapses the missing scalar to its
3761    // zero-arm test. A regression that overrode `is_kind_saturated` to
3762    // drop the negation (returning `slice.is_empty()`), skip a kind,
3763    // or drift the walk from `ConditionKind::ALL` surfaces HERE at
3764    // the substrate boundary, not as silent drift at every downstream
3765    // `is-kind-saturated` require-tag classifier or fleet-wide gap-
3766    // analysis dashboard callsite. Byte-for-byte peer of
3767    // `crate::tagged_union::TaggedUnion::is_saturated` one struct-
3768    // layer up under the same `<CLOSED_SET>::ALL.iter().all(has)`
3769    // short-circuit shape.
3770    assert_eq!(
3771        slice.is_kind_saturated(),
3772        slice.missing_kind_count() == 0,
3773        "is_kind_saturated() drifted from (missing_kind_count() == 0)",
3774    );
3775    assert_eq!(
3776        slice.is_kind_saturated(),
3777        missing.is_empty(),
3778        "is_kind_saturated() drifted from missing_kinds().is_empty()",
3779    );
3780
3781    // has_any_missing_kind ↔ !is_kind_saturated — the Boolean at-
3782    // least-one halfspace projection of the closed-set-complement
3783    // scalar cardinality. Peer of `is_kind_saturated ↔
3784    // (missing_kind_count == 0)` on the Boolean-negation axis: where
3785    // the saturation-endpoint peer tests the zero-arm, this at-least-
3786    // one halfspace peer tests its negation. Together the two Booleans
3787    // partition the missing-cardinality closed set — exactly one is
3788    // `true` for every slice. A regression that overrode
3789    // `has_any_missing_kind` to drop the negation (returning
3790    // `is_kind_saturated`), skip a kind, or drift the walk from
3791    // `ConditionKind::ALL` surfaces HERE at the substrate boundary,
3792    // not as silent drift at every downstream `has-any-missing-kind`
3793    // require-tag classifier or fleet-wide gap-analysis dashboard
3794    // callsite. Byte-for-byte peer of
3795    // `crate::tagged_union::TaggedUnion::has_any_missing_kind` one
3796    // struct-layer up under the SAME `!is_saturated` definitional
3797    // negation shape. Also pins the widened composition laws
3798    // `has_any_missing_kind() == (missing_kind_count() > 0)` and
3799    // `has_any_missing_kind() == !missing_kinds().is_empty()` at every
3800    // slice — binds the at-least-one halfspace Boolean projection to
3801    // the widened + scalar closed-set-complement primitives without
3802    // paying for the Vec allocation.
3803    assert_eq!(
3804        slice.has_any_missing_kind(),
3805        !slice.is_kind_saturated(),
3806        "has_any_missing_kind() drifted from !is_kind_saturated()",
3807    );
3808    assert_eq!(
3809        slice.has_any_missing_kind(),
3810        slice.missing_kind_count() > 0,
3811        "has_any_missing_kind() drifted from (missing_kind_count() > 0)",
3812    );
3813    assert_eq!(
3814        slice.has_any_missing_kind(),
3815        !missing.is_empty(),
3816        "has_any_missing_kind() drifted from !missing_kinds().is_empty()",
3817    );
3818
3819    // has_unique_missing_kind ↔ (missing_kind_count == 1) — the
3820    // Boolean cardinality-mid-endpoint projection of the closed-set-
3821    // complement scalar cardinality. Peer of `has_any_missing_kind ↔
3822    // !is_kind_saturated` on the Boolean-projection axis: where the
3823    // at-least-one halfspace peer tests the ≥ 1 arm on the missing
3824    // scalar, this cardinality-mid-endpoint peer tests the exactly-
3825    // one arm. Together with `is_kind_saturated` (zero-arm) and the
3826    // future many-arm peer, the three Booleans partition the missing-
3827    // cardinality closed set at 0, 1, and ≥ 2 respectively. A
3828    // regression that overrode `has_unique_missing_kind` to drop the
3829    // second-slot short-circuit (returning any partial-populated
3830    // arm), skip a kind, drift the walk from `ConditionKind::ALL`, or
3831    // conflate with `is_kind_saturated` (the zero-arm) surfaces HERE
3832    // at the substrate boundary, not as silent drift at every
3833    // downstream `has-unique-missing-kind` require-tag classifier or
3834    // near-saturation-endpoint diagnostic callsite. Byte-for-byte
3835    // peer of `crate::tagged_union::TaggedUnion::has_unique_missing_kind`
3836    // one struct-layer up under the SAME two-step short-circuit
3837    // walk shape. Also pins the widened composition law
3838    // `has_unique_missing_kind() == (missing_kinds().len() == 1)` at
3839    // every slice — binds the cardinality-mid-endpoint Boolean
3840    // projection to the widened + scalar closed-set-complement
3841    // primitives without paying for the Vec allocation on the ≥ 2-
3842    // missing arms (where the short-circuit fires).
3843    assert_eq!(
3844        slice.has_unique_missing_kind(),
3845        slice.missing_kind_count() == 1,
3846        "has_unique_missing_kind() drifted from (missing_kind_count() == 1)",
3847    );
3848    assert_eq!(
3849        slice.has_unique_missing_kind(),
3850        missing.len() == 1,
3851        "has_unique_missing_kind() drifted from (missing_kinds().len() == 1)",
3852    );
3853
3854    // has_multiple_missing_kinds ↔ (missing_kind_count >= 2) — the
3855    // Boolean cardinality many-arm projection of the closed-set-
3856    // complement scalar cardinality. Peer of `has_any_missing_kind ↔
3857    // !is_kind_saturated` (≥ 1 halfspace) and `has_unique_missing_kind
3858    // ↔ (missing_kind_count == 1)` (= 1 mid-endpoint) on the Boolean-
3859    // projection axis: where those peers test the ≥ 1 and = 1 arms on
3860    // the missing scalar, this many-arm peer tests the ≥ 2 arm.
3861    // Together with `is_kind_saturated` (zero-arm) and
3862    // `has_unique_missing_kind` (one-arm), the three Booleans
3863    // partition the missing-cardinality closed set at 0, 1, and ≥ 2
3864    // respectively — every slice satisfies EXACTLY ONE of the three
3865    // projections. A regression that overrode `has_multiple_missing_kinds`
3866    // to drop the second-slot short-circuit (returning `true` on any
3867    // ≥ 1-missing arm), skip a kind, drift the walk from
3868    // `ConditionKind::ALL`, or conflate with `has_any_missing_kind`
3869    // (the ≥ 1 halfspace) surfaces HERE at the substrate boundary,
3870    // not as silent drift at every downstream
3871    // `has-multiple-missing-kinds` require-tag classifier or
3872    // coverage-gap diagnostic callsite. Byte-for-byte peer of
3873    // `crate::tagged_union::TaggedUnion::has_multiple_missing_kinds`
3874    // one struct-layer up under the SAME two-step short-circuit walk
3875    // shape. Also pins the widened composition law
3876    // `has_multiple_missing_kinds() == (missing_kinds().len() >= 2)`
3877    // at every slice — binds the cardinality-many-arm Boolean
3878    // projection to the widened + scalar closed-set-complement
3879    // primitives without paying for the Vec allocation on the ≥ 2-
3880    // missing arms (where the short-circuit fires) or the full-slot
3881    // walk on the scalar counter.
3882    assert_eq!(
3883        slice.has_multiple_missing_kinds(),
3884        slice.missing_kind_count() >= 2,
3885        "has_multiple_missing_kinds() drifted from (missing_kind_count() >= 2)",
3886    );
3887    assert_eq!(
3888        slice.has_multiple_missing_kinds(),
3889        missing.len() >= 2,
3890        "has_multiple_missing_kinds() drifted from (missing_kinds().len() >= 2)",
3891    );
3892
3893    // has_at_most_one_missing_kind ↔ !has_multiple_missing_kinds — the
3894    // Boolean cardinality "≤ 1" negation projection of the many-arm
3895    // primitive on the closed-set-complement axis. Peer of
3896    // `has_multiple_missing_kinds ↔ (missing_kind_count >= 2)` (≥ 2
3897    // many-arm) under the definitional Boolean negation
3898    // `!(≥ 2) == (≤ 1)`. Together with `is_kind_saturated` (=0
3899    // zero-arm) and `has_unique_missing_kind` (=1 mid-endpoint), the
3900    // "≤ 1" primitive collapses to the trichotomy-union
3901    // `is_kind_saturated() || has_unique_missing_kind()` — a
3902    // regression that overrode `has_at_most_one_missing_kind` to drop
3903    // the definitional negation (returning `has_multiple_missing_kinds`
3904    // itself), swap the wrong side, or drift the walk from the
3905    // many-arm primitive surfaces HERE at the substrate boundary, not
3906    // as silent drift at every downstream
3907    // `has-at-most-one-missing-kind` require-tag classifier or near-
3908    // saturation-or-saturated gap-analysis diagnostic callsite. Byte-
3909    // for-byte peer of
3910    // `crate::tagged_union::TaggedUnion::has_at_most_one_missing_kind`
3911    // one struct-layer up under the SAME `!has_multiple_missing_kinds`
3912    // definitional negation shape. Also pins the widened composition
3913    // laws
3914    // `has_at_most_one_missing_kind() == (missing_kind_count() <= 1)`
3915    // and `has_at_most_one_missing_kind() == (missing_kinds().len() <= 1)`
3916    // at every slice — binds the "≤ 1" Boolean projection to the
3917    // widened + scalar closed-set-complement primitives without paying
3918    // for the Vec allocation on the ≤ 1-missing arms (where the
3919    // negated short-circuit fires immediately after the many-arm walk
3920    // stops) or the full-slot walk on the scalar counter. Also pins
3921    // the trichotomy-union composition law
3922    // `has_at_most_one_missing_kind() == is_kind_saturated() ||
3923    // has_unique_missing_kind()` at every slice — surfaces any
3924    // implementor that drifted the trichotomy union operator from
3925    // `||` to `&&` or that broke one of the two arm primitives while
3926    // leaving the "≤ 1" negation of the many-arm intact.
3927    assert_eq!(
3928        slice.has_at_most_one_missing_kind(),
3929        !slice.has_multiple_missing_kinds(),
3930        "has_at_most_one_missing_kind() drifted from !has_multiple_missing_kinds()",
3931    );
3932    assert_eq!(
3933        slice.has_at_most_one_missing_kind(),
3934        slice.missing_kind_count() <= 1,
3935        "has_at_most_one_missing_kind() drifted from (missing_kind_count() <= 1)",
3936    );
3937    assert_eq!(
3938        slice.has_at_most_one_missing_kind(),
3939        missing.len() <= 1,
3940        "has_at_most_one_missing_kind() drifted from (missing_kinds().len() <= 1)",
3941    );
3942    assert_eq!(
3943        slice.has_at_most_one_missing_kind(),
3944        slice.is_kind_saturated() || slice.has_unique_missing_kind(),
3945        "has_at_most_one_missing_kind() drifted from (is_kind_saturated() || has_unique_missing_kind())",
3946    );
3947
3948    // lacks_kind ↔ !has_kind — the Boolean per-kind complement
3949    // projection on the closed-set-complement axis. Peer of
3950    // `is_kind_saturated ↔ (missing_kind_count == 0)` on the Boolean-
3951    // projection axis: where the saturation-endpoint peer collapses
3952    // the whole missing scalar to its zero-arm test, this per-kind
3953    // peer collapses the whole missing SET to its per-kind membership
3954    // Boolean for ONE addressed kind. A regression that overrode
3955    // `lacks_kind` to drop the negation (returning `has_kind`), swap
3956    // the wrong side, or drift the walk from `has_kind` surfaces HERE
3957    // at the substrate boundary, not as silent drift at every
3958    // downstream `lacks-<kind>` require-tag classifier or
3959    // dependency-satisfaction coherence check callsite. Byte-for-byte
3960    // peer of `crate::tagged_union::TaggedUnion::lacks` one struct-
3961    // layer up under the SAME `!has(kind)` definitional negation
3962    // shape. Also pins the widened composition law
3963    // `lacks_kind(k) == missing_kinds().contains(&k)` at every arm —
3964    // binds the per-kind Boolean projection to the widened closed-set-
3965    // complement primitive without paying for the Vec allocation.
3966    for kind in ConditionKind::ALL {
3967        assert_eq!(
3968            slice.lacks_kind(kind),
3969            !slice.has_kind(kind),
3970            "lacks_kind({kind:?}) drifted from !has_kind({kind:?})",
3971        );
3972        assert_eq!(
3973            slice.lacks_kind(kind),
3974            missing.contains(&kind),
3975            "lacks_kind({kind:?}) drifted from missing_kinds().contains(&{kind:?})",
3976        );
3977    }
3978}
3979
3980/// Substrate testkit macro — pins the FOUR union composition laws that
3981/// bind the (precondition, postcondition, union) refinement triads on
3982/// any authored surface exposing the 12-method (has / find / iter /
3983/// count) × (pre / post / union) `_kind` matrix. Sweeps
3984/// [`ConditionKind::ALL`] at ONE call site per authored arrangement.
3985///
3986/// # The four surface-level union composition laws
3987///
3988/// Where the slice-level substrate primitive
3989/// [`assert_slice_refinement_composition_laws`] pins the algebra that
3990/// binds the four refinements *on a single slice* (`iter_kind` →
3991/// `find_kind` → `has_kind` → `count_kind`), this macro pins the peer
3992/// algebra one struct-layer up: each refinement's union arm on a
3993/// two-slice surface (a [`Boundary`] with `preconditions` +
3994/// `postconditions`, an [`crate::ephemeral::EphemeralSpec`] with the
3995/// same eponymous field pair) composes from its two half-slice arms
3996/// through a specific monoid operator baked into the refinement's return
3997/// type:
3998///
3999/// | refinement | half-slice arms                             | union composition                     |
4000/// |------------|---------------------------------------------|---------------------------------------|
4001/// | `has_*_kind`   | `has_precondition_kind`, `has_postcondition_kind`     | `pre \|\| post` (bool OR)             |
4002/// | `find_*_kind`  | `find_precondition_kind`, `find_postcondition_kind`   | `pre.or(post)` (first-Some)           |
4003/// | `iter_*_kind`  | `iter_precondition_kind`, `iter_postcondition_kind`   | `pre.chain(post)` (stream concat)     |
4004/// | `count_*_kind` | `count_precondition_kind`, `count_postcondition_kind` | `pre + post` (cardinality SUM)        |
4005///
4006/// # Why lift
4007///
4008/// Pre-lift each surface-level union composition law lived at its own
4009/// hand-authored nested-`for` loop test on each of the two surfaces —
4010/// EIGHT sibling test bodies (`boundary_has_condition_kind_composes_precondition_and_postcondition_arms`,
4011/// `find_condition_kind_triad_delegates_to_slice_find_kind`,
4012/// `iter_condition_kind_triad_delegates_to_slice_iter_kind`,
4013/// `boundary_count_condition_kind_triad_delegates_and_sums_slice_count_kind`
4014/// on the [`Boundary`] surface, byte-for-byte peers on the
4015/// [`crate::ephemeral::EphemeralSpec`] surface) whose only per-law knobs
4016/// were the projection functions being bridged and the composition
4017/// operator (`\|\|` / `Option::or` / `Iterator::chain` / `+`) applied
4018/// on top. Post-lift each authored `(preconditions, postconditions)`
4019/// arrangement pins ALL FOUR union composition laws through ONE
4020/// `assert_surface_union_composition_laws!(surface)` call whose body
4021/// is the substrate primitive's own sweep, no per-surface author-time
4022/// enumeration.
4023///
4024/// # Why a macro rather than a `pub fn`
4025///
4026/// [`Boundary`] and [`crate::ephemeral::EphemeralSpec`] expose the
4027/// twelve methods as *inherent* methods with matching signatures. A
4028/// generic `pub fn assert_surface_union_composition_laws<B: T>(&B)`
4029/// would need a trait `T` publishing those same twelve methods, and
4030/// implementing that trait on either surface would collide with the
4031/// eponymous inherent methods at method resolution — the trait
4032/// impl would either duplicate the inherent-method bodies verbatim
4033/// (defeating the lift) or require renaming the trait methods with a
4034/// `_ext` suffix (introducing a parallel API surface). A macro
4035/// duck-types at expansion time and hits the inherent methods
4036/// directly, so both surfaces stay bound through the SAME
4037/// `_kind`-suffixed method names their non-generic callers already
4038/// reach for, and the pattern generalizes to any future surface that
4039/// grows the same twelve-method matrix (an `AplicacaoBoundary` typed
4040/// wrapper, a `PoolBoundary` gate-carrier at
4041/// [`crate::pool`], the boundary slot on a
4042/// hypothetical `AttestationBoundary` receipt-envelope surface) with
4043/// ONE macro invocation per authored arrangement rather than a per-
4044/// surface re-authored sweep over the four laws.
4045///
4046/// # Compounding
4047///
4048/// A FIFTH union refinement added to the (has, find, iter, count)
4049/// tetrad (a hypothetical `first_params_of_kind(k) -> Option<&Value>`
4050/// projection combining `find_condition_kind(k).map(|c| &c.params)` at
4051/// real reconciler callsites, a `distinct_kinds() -> impl Iterator<Item
4052/// = ConditionKind>` aggregate returning which kinds appear at least
4053/// once on either side, a `has_kind_matching(pred)` closure-based
4054/// predicate probe) lands its composition-law pin as ONE new arm
4055/// inside this macro's body. Every downstream test that already reaches
4056/// this macro picks up the fifth-refinement pin mechanically — no per-
4057/// arrangement author-time enumeration of the new law across the four
4058/// sibling composition-law sites on each of the two surfaces, no
4059/// re-authored `for kind in ConditionKind::ALL { … }` sweep at every
4060/// consumer.
4061///
4062/// Symmetrical shape to [`assert_slice_refinement_composition_laws`]
4063/// one layer below: both project a widened-refinement / coarser-
4064/// refinement composition law contract onto ONE typed substrate call
4065/// site, both sweep the addressed closed set [`ConditionKind::ALL`],
4066/// both surface any implementor that overrode the union arm with a
4067/// divergent composition operator (an `&&` inlined where `\|\|` is
4068/// required, a `pre - post` inlined where `pre + post` is required,
4069/// a `zip` inlined where `chain` is required, a `and_then` inlined
4070/// where `or_else` is required) as a first-class typed test failure
4071/// rather than as silent operator-facing drift at the
4072/// `condition-<kind>` / `precondition-<kind>` / `postcondition-<kind>`
4073/// require-tag classifier surfaces downstream.
4074///
4075/// # Theory grounding
4076///
4077/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. Each
4078///   union arm is a typed projection of its two half-slice peers via
4079///   a specific monoid operator, and this substrate macro turns each
4080///   projection's composition law from doc-prose into a first-class
4081///   typed theorem provable against any surface exposing the twelve
4082///   `_kind`-suffixed inherent methods.
4083/// - THEORY.md §VI.1 — generation over composition. A new
4084///   [`ConditionKind`] variant added to `ALL` reaches every downstream
4085///   union-composition-law consumer through the SAME closed-set sweep
4086///   with no per-caller edit; a new surface (a typed wrapper carrying
4087///   the same twelve methods) picks up all four union composition-law
4088///   pins through ONE macro invocation per authored arrangement.
4089///
4090/// # Usage
4091///
4092/// ```ignore
4093/// // Point surface.
4094/// let mut b = Boundary::default();
4095/// b.preconditions.push(condition_with(ConditionKind::PromQL));
4096/// b.postconditions.push(condition_with(ConditionKind::ClosedLoopAuth));
4097/// assert_surface_union_composition_laws!(b);
4098///
4099/// // Ephemeral surface (peer, same primitive).
4100/// let mut spec = empty_ephemeral();
4101/// spec.postconditions.push(cond(ConditionKind::JobAttested));
4102/// assert_surface_union_composition_laws!(spec);
4103/// ```
4104#[macro_export]
4105macro_rules! assert_surface_union_composition_laws {
4106    ($surface:expr) => {{
4107        let __surface = &$surface;
4108        // Hoist distinct_* out of the per-kind loop — closed-set-inversion
4109        // refinements return the WHOLE distinct-set per call, so a single
4110        // computation per surface backs the per-kind membership arm inside
4111        // the loop AND the canonical-order equality after it.
4112        let __distinct_pre_kinds = __surface.distinct_precondition_kinds();
4113        let __distinct_post_kinds = __surface.distinct_postcondition_kinds();
4114        let __distinct_union_kinds = __surface.distinct_condition_kinds();
4115        let __missing_pre_kinds = __surface.missing_precondition_kinds();
4116        let __missing_post_kinds = __surface.missing_postcondition_kinds();
4117        let __missing_union_kinds = __surface.missing_condition_kinds();
4118        for __kind in $crate::boundary::ConditionKind::ALL {
4119            // has: union == pre || post (bool OR)
4120            let __has_via_arms =
4121                __surface.has_precondition_kind(__kind) || __surface.has_postcondition_kind(__kind);
4122            ::core::assert_eq!(
4123                __surface.has_condition_kind(__kind),
4124                __has_via_arms,
4125                "surface union has arm drifted from OR of half-slice arms for {:?}",
4126                __kind,
4127            );
4128            // find: union == pre.or(post) (first-Some, kind projection)
4129            let __find_via_arms = __surface
4130                .find_precondition_kind(__kind)
4131                .or(__surface.find_postcondition_kind(__kind))
4132                .map(|c| c.kind);
4133            ::core::assert_eq!(
4134                __surface.find_condition_kind(__kind).map(|c| c.kind),
4135                __find_via_arms,
4136                "surface union find arm drifted from precondition.or(postcondition) for {:?}",
4137                __kind,
4138            );
4139            // iter: union == chain(pre, post) (stream concat, kind projection)
4140            let __iter_via_arms: ::std::vec::Vec<_> = __surface
4141                .iter_precondition_kind(__kind)
4142                .chain(__surface.iter_postcondition_kind(__kind))
4143                .map(|c| c.kind)
4144                .collect();
4145            let __iter_via_union: ::std::vec::Vec<_> = __surface
4146                .iter_condition_kind(__kind)
4147                .map(|c| c.kind)
4148                .collect();
4149            ::core::assert_eq!(
4150                __iter_via_union,
4151                __iter_via_arms,
4152                "surface union iter arm drifted from chain(pre, post) for {:?}",
4153                __kind,
4154            );
4155            // count: union == pre + post (cardinality SUM)
4156            ::core::assert_eq!(
4157                __surface.count_condition_kind(__kind),
4158                __surface.count_precondition_kind(__kind)
4159                    + __surface.count_postcondition_kind(__kind),
4160                "surface union count arm drifted from SUM of half-slice arms for {:?}",
4161                __kind,
4162            );
4163            // distinct: union.contains(k) == pre.contains(k) || post.contains(k)
4164            // (set-union membership per kind on the closed-set-inversion axis)
4165            ::core::assert_eq!(
4166                __distinct_union_kinds.contains(&__kind),
4167                __distinct_pre_kinds.contains(&__kind)
4168                    || __distinct_post_kinds.contains(&__kind),
4169                "surface distinct union arm drifted from OR-membership of half-slice distinct arms for {:?}",
4170                __kind,
4171            );
4172            // missing: union.contains(k) == pre.contains(k) && post.contains(k)
4173            // (set-INTERSECTION membership per kind — a kind is missing
4174            // from the union iff it is missing from BOTH half-slices,
4175            // dual of the distinct-set OR composition).
4176            ::core::assert_eq!(
4177                __missing_union_kinds.contains(&__kind),
4178                __missing_pre_kinds.contains(&__kind)
4179                    && __missing_post_kinds.contains(&__kind),
4180                "surface missing union arm drifted from AND-membership of half-slice missing arms for {:?}",
4181                __kind,
4182            );
4183            // missing ↔ has: union.contains(k) == !has_condition_kind(k)
4184            // — binds the missing-set primitive to the point-probe
4185            // primitive on the surface under a negated predicate.
4186            ::core::assert_eq!(
4187                __missing_union_kinds.contains(&__kind),
4188                !__surface.has_condition_kind(__kind),
4189                "surface missing union arm drifted from !has_condition_kind for {:?}",
4190                __kind,
4191            );
4192            // lacks: union == pre && post (bool AND — dual of `has`'s
4193            // `pre || post` OR under `!(a || b) == !a && !b`). A kind is
4194            // lacked from the union iff BOTH half-slices lack it — the
4195            // per-kind Boolean-projection peer of the missing-set
4196            // intersection membership arm above (which composes the SAME
4197            // AND over the closed-set-complement Vecs); this arm
4198            // composes it over the per-slice per-kind negation
4199            // primitives without materializing either side's missing-
4200            // set Vec. A regression that (a) drifted the union operator
4201            // to `||` (widening the intersection to a union),
4202            // (b) dropped the negation on one side, or (c) inverted the
4203            // wrong slice on the point probe surfaces HERE at the
4204            // substrate boundary, not as silent drift at every
4205            // downstream `lacks-<kind>` require-tag classifier callsite.
4206            let __lacks_via_arms =
4207                __surface.lacks_precondition_kind(__kind) && __surface.lacks_postcondition_kind(__kind);
4208            ::core::assert_eq!(
4209                __surface.lacks_condition_kind(__kind),
4210                __lacks_via_arms,
4211                "surface union lacks arm drifted from AND of half-slice lacks arms for {:?}",
4212                __kind,
4213            );
4214            // lacks ↔ has: union == !has_condition_kind(k) — the
4215            // definitional complement law binds the per-kind Boolean-
4216            // complement primitive on the surface to the point-probe
4217            // primitive under negation. Peer of the `missing ↔ has`
4218            // arm above one refinement lower: the closed-set-complement
4219            // Vec's per-kind membership equals the per-kind Boolean
4220            // complement, both equal `!has_condition_kind(k)`. A
4221            // regression that overrode `lacks_condition_kind` to drop
4222            // the negation, drift the underlying union primitive, or
4223            // return `has_condition_kind` surfaces HERE.
4224            ::core::assert_eq!(
4225                __surface.lacks_condition_kind(__kind),
4226                !__surface.has_condition_kind(__kind),
4227                "surface union lacks arm drifted from !has_condition_kind for {:?}",
4228                __kind,
4229            );
4230        }
4231        // distinct: union == canonical(pre ∪ post) — closed-set-inversion
4232        // set-union projected in ConditionKind::ALL order. A regression that
4233        // (a) reversed the walk order (post-then-pre), (b) preserved
4234        // slice-encounter order rather than ConditionKind::ALL order, or
4235        // (c) narrowed the union to an intersection surfaces HERE at the
4236        // substrate boundary (the per-kind membership arm above catches
4237        // membership drift; this arm catches ordering + dedup drift the
4238        // membership arm cannot detect on its own).
4239        let __expected_distinct_union: ::std::vec::Vec<_> =
4240            $crate::boundary::ConditionKind::ALL
4241                .into_iter()
4242                .filter(|__k| {
4243                    __distinct_pre_kinds.contains(__k)
4244                        || __distinct_post_kinds.contains(__k)
4245                })
4246                .collect();
4247        ::core::assert_eq!(
4248            __distinct_union_kinds, __expected_distinct_union,
4249            "surface distinct union arm drifted from canonical ConditionKind::ALL-ordered set-union of half-slice distinct arms",
4250        );
4251        // missing: union == canonical(pre ∩ post) — closed-set-inversion
4252        // set-INTERSECTION projected in ConditionKind::ALL order. Dual
4253        // of the distinct union canonical-order arm above. A regression
4254        // that (a) reversed the walk order, (b) widened the intersection
4255        // to a union (returning kinds missing from either side rather
4256        // than both), or (c) preserved slice-encounter order rather
4257        // than ConditionKind::ALL order surfaces HERE at the substrate
4258        // boundary.
4259        let __expected_missing_union: ::std::vec::Vec<_> =
4260            $crate::boundary::ConditionKind::ALL
4261                .into_iter()
4262                .filter(|__k| {
4263                    __missing_pre_kinds.contains(__k)
4264                        && __missing_post_kinds.contains(__k)
4265                })
4266                .collect();
4267        ::core::assert_eq!(
4268            __missing_union_kinds, __expected_missing_union,
4269            "surface missing union arm drifted from canonical ConditionKind::ALL-ordered set-INTERSECTION of half-slice missing arms",
4270        );
4271    }};
4272}
4273
4274/// A single boundary predicate.
4275#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
4276#[serde(rename_all = "camelCase")]
4277pub struct Condition {
4278    pub kind: ConditionKind,
4279    /// Kind-specific payload (free-form JSON).
4280    #[serde(default)]
4281    #[schemars(schema_with = "crate::schema_helpers::preserve_unknown_object")]
4282    pub params: serde_json::Value,
4283}
4284
4285#[derive(
4286    Clone,
4287    Copy,
4288    Debug,
4289    PartialEq,
4290    Eq,
4291    Hash,
4292    Serialize,
4293    Deserialize,
4294    JsonSchema,
4295    tatara_closed_set::DeriveClosedSet,
4296)]
4297#[serde(rename_all = "PascalCase")]
4298#[closed_set(via = "as_str", display, generate_unknown)]
4299pub enum ConditionKind {
4300    /// Another Process must be in a given phase.
4301    /// `params`: `{ "processRef": "...", "namespace": "...", "phase": "Attested" }`
4302    ProcessPhase,
4303    /// FluxCD `Kustomization.status.conditions[type=Ready]` must be `True`.
4304    /// `params`: `{ "name": "...", "namespace": "flux-system" }`
4305    KustomizationHealthy,
4306    /// FluxCD `HelmRelease.status.conditions[type=Ready]` must be `True`.
4307    /// `params`: `{ "name": "...", "namespace": "..." }`
4308    HelmReleaseReleased,
4309    /// Prometheus query — truthy scalar required.
4310    /// `params`: `{ "query": "..." }`
4311    PromQL,
4312    /// CEL expression over a scoped object set.
4313    /// `params`: `{ "expression": "..." }`
4314    Cel,
4315    /// Nix evaluation equality check.
4316    /// `params`: `{ "flakeRef": "...", "attribute": "...", "expect": "..." }`
4317    NixEval,
4318    /// A Kubernetes Job must complete successfully and its emitted BLAKE3
4319    /// receipt must verify.
4320    /// `params`: `{ "name": "...", "namespace": "...", "expectReceipt": true }`
4321    JobAttested,
4322    /// Closed-loop authentication probe — the canonical postcondition for
4323    /// any system that can produce credentials for its own client under
4324    /// test. The probe Job (rendered by the VERIFY handler) fetches a
4325    /// fresh secret from `issuer` (a Service inside the same namespace),
4326    /// presents it to `consumer` (another Service in the same namespace),
4327    /// and verifies that `consumer` authenticated successfully against
4328    /// `jwk_source` (the issuer's published JWK endpoint).
4329    ///
4330    /// The Job emits a three-pillar BLAKE3 receipt that the reconciler
4331    /// chains into `status.attestation`. This turns "the gateway↔SaaS
4332    /// loop holds" from an assertion into a theorem provable for every
4333    /// ephemeral run.
4334    ///
4335    /// `params`:
4336    /// ```json
4337    /// {
4338    ///   "issuer":   { "service": "demo-app-issuer",
4339    ///                 "port": 8080,
4340    ///                 "secretPath": "/v2/get-secret-value" },
4341    ///   "consumer": { "service": "demo-app-gateway",
4342    ///                 "port": 8000,
4343    ///                 "authPath": "/api/v3/auth" },
4344    ///   "jwkSource":{ "service": "demo-app-issuer",
4345    ///                 "port": 8080,
4346    ///                 "path": "/.well-known/jwks.json" },
4347    ///   "probeImage": "ghcr.io/pleme-io/closed-loop-probe:0.1.0",
4348    ///   "timeoutSeconds": 120
4349    /// }
4350    /// ```
4351    ClosedLoopAuth,
4352}
4353
4354impl ConditionKind {
4355    /// The closed set of boundary-condition kinds the reconciler honors.
4356    /// Single source of truth that drives the `as_str` / Display /
4357    /// `FromStr` triad on this enum and the `stub_message` lift of the
4358    /// "not yet implemented" arms the reconciler used to hand-roll three
4359    /// times. Adding a 9th variant lands at one `ALL` entry + one `as_str`
4360    /// arm + one `stub_message` arm — exhaustively checked by the
4361    /// compiler (the array literal forces arity).
4362    ///
4363    /// Sibling closed-set lifts: [`crate::phase::ProcessPhase::ALL`],
4364    /// [`crate::signal::ProcessSignal::ALL`], [`crate::intent::IntentKind::ALL`],
4365    /// [`crate::lifetime::LifetimeKind::ALL`].
4366    pub const ALL: [Self; 8] = [
4367        Self::ProcessPhase,
4368        Self::KustomizationHealthy,
4369        Self::HelmReleaseReleased,
4370        Self::PromQL,
4371        Self::Cel,
4372        Self::NixEval,
4373        Self::JobAttested,
4374        Self::ClosedLoopAuth,
4375    ];
4376
4377    /// Canonical PascalCase wire-format projection — matches the serde
4378    /// `rename_all = "PascalCase"` output verbatim. Used by Display
4379    /// (single source of truth), by `FromStr` to identify the variant
4380    /// from its annotation / status-field representation, and by
4381    /// operator-facing diagnostics that need the kind name without
4382    /// re-serializing the enum through serde_json. Pinned by
4383    /// `condition_kind_as_str_matches_serde`.
4384    pub const fn as_str(self) -> &'static str {
4385        match self {
4386            Self::ProcessPhase => "ProcessPhase",
4387            Self::KustomizationHealthy => "KustomizationHealthy",
4388            Self::HelmReleaseReleased => "HelmReleaseReleased",
4389            Self::PromQL => "PromQL",
4390            Self::Cel => "Cel",
4391            Self::NixEval => "NixEval",
4392            Self::JobAttested => "JobAttested",
4393            Self::ClosedLoopAuth => "ClosedLoopAuth",
4394        }
4395    }
4396
4397    /// The operator-facing "evaluator not yet implemented" message for
4398    /// stub kinds — `Some` iff this kind has no live evaluator wired in
4399    /// `tatara-reconciler::boundary`. ONE site owns the per-kind stub
4400    /// string; the reconciler's dispatch reaches for this projection
4401    /// instead of hand-rolling three parallel `Unknown(...)` strings.
4402    ///
4403    /// A future variant added as a live evaluator returns `None`; a
4404    /// future variant added as a stub returns `Some("<kind> evaluator
4405    /// not yet implemented")` — both reachable through one match
4406    /// instead of three identical-shape arms drifting in parallel.
4407    pub const fn stub_message(self) -> Option<&'static str> {
4408        match self {
4409            Self::PromQL => Some("PromQL evaluator not yet implemented"),
4410            Self::Cel => Some("CEL evaluator not yet implemented"),
4411            Self::NixEval => Some("NixEval evaluator not yet implemented"),
4412            Self::ProcessPhase
4413            | Self::KustomizationHealthy
4414            | Self::HelmReleaseReleased
4415            | Self::JobAttested
4416            | Self::ClosedLoopAuth => None,
4417        }
4418    }
4419
4420    /// True iff this kind has no live evaluator (its [`Self::stub_message`]
4421    /// is `Some`). Pairs with the reconciler's `evaluate` dispatch — a
4422    /// stub kind unconditionally yields `Satisfaction::Unknown`.
4423    pub const fn is_stub(self) -> bool {
4424        self.stub_message().is_some()
4425    }
4426
4427    /// The [`FluxResource`] variant this condition kind fetches from
4428    /// the K8s API server, or `None` for non-Flux-fetching kinds — the
4429    /// typed projection owning the (ConditionKind → FluxResource)
4430    /// association every reconciler `evaluate` dispatch arm and every
4431    /// future coherence check binds through.
4432    ///
4433    /// Pre-lift the association was open-coded at TWO adjacent
4434    /// `evaluate` arms in `tatara-reconciler::boundary::evaluate` past
4435    /// the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold — each arm
4436    /// hand-authored a `(FluxResource::X.api_version(),
4437    /// FluxResource::X.kind())` pair as the two `&str` slots the
4438    /// pre-lift `evaluate_flux_ready(api_version: &str, kind: &str)`
4439    /// signature required. Post-lift the mapping lives at ONE typed
4440    /// projection here, the callee accepts a typed
4441    /// [`FluxResource`] slot (invalid `(apiVersion, kind)` pairings
4442    /// like Kustomization's apiVersion paired with HelmRelease's kind
4443    /// become unrepresentable), and the two `evaluate` arms collapse
4444    /// onto ONE `KustomizationHealthy | HelmReleaseReleased` OR-arm
4445    /// that reads the FluxResource variant from `.flux_resource()`.
4446    ///
4447    /// A future ConditionKind that fetches a fourth Flux resource
4448    /// variant (a hypothetical `BucketSynced` kind against a Flux
4449    /// `Bucket` source) lands as ONE new arm here + ONE new variant
4450    /// on [`FluxResource`] + ONE OR-pattern extension at the
4451    /// reconciler dispatch — no hand-authored `(apiVersion, kind)`
4452    /// pair at the callsite, no widening of the callee's signature.
4453    ///
4454    /// The three current non-Flux-fetching arms return `None`:
4455    /// - `ProcessPhase` fetches a tatara `Process` (through its own
4456    ///   [`crate::api_version`] + [`crate::PROCESS_KIND`] pair, not
4457    ///   a Flux `(apiVersion, kind)`).
4458    /// - `JobAttested` / `ClosedLoopAuth` fetch a `batch/v1::Job` +
4459    ///   an optional receipt `v1::ConfigMap`, both K8s built-ins
4460    ///   (not Flux resources).
4461    /// - `PromQL` / `Cel` / `NixEval` are stub evaluators
4462    ///   ([`Self::is_stub`]) — no cluster fetch at all.
4463    ///
4464    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition
4465    /// preserves proofs — the (ConditionKind → FluxResource)
4466    /// association lives at ONE typed algebra projection here, not
4467    /// at every reconciler dispatch arm).
4468    pub const fn flux_resource(self) -> Option<FluxResource> {
4469        match self {
4470            Self::KustomizationHealthy => Some(FluxResource::Kustomization),
4471            Self::HelmReleaseReleased => Some(FluxResource::HelmRelease),
4472            Self::ProcessPhase
4473            | Self::PromQL
4474            | Self::Cel
4475            | Self::NixEval
4476            | Self::JobAttested
4477            | Self::ClosedLoopAuth => None,
4478        }
4479    }
4480}
4481
4482// `impl fmt::Display for ConditionKind` + `impl FromStr for
4483// ConditionKind` + `impl tatara_lisp::ClosedSet for ConditionKind` +
4484// `pub struct UnknownConditionKind(pub String)` are generated by
4485// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(via =
4486// "as_str", display, generate_unknown)]` on the enum declaration above.
4487// The auto-derived label `"condition kind"` matches the prior hand-
4488// rolled `#[error("unknown condition kind: {0}")]` verbatim. The
4489// inherent `as_str` projection stays load-bearing — the PascalCase
4490// wire-format that matches the serde rename + the CRD `enum:` listing
4491// verbatim (notably preserving `PromQL`'s consecutive caps that heck
4492// would have lowercased) — while the trait method `label` gives
4493// generic consumers a STABLE name across the 36+ workspace-wide
4494// closed-set implementors.
4495
4496#[cfg(test)]
4497mod tests {
4498    use super::*;
4499    use serde_json::json;
4500
4501    #[test]
4502    fn serde_process_phase_condition() {
4503        let c = Condition {
4504            kind: ConditionKind::ProcessPhase,
4505            params: json!({ "processRef": "secret-injection", "phase": "Attested" }),
4506        };
4507        let yaml = serde_yaml::to_string(&c).unwrap();
4508        assert!(yaml.contains("kind: ProcessPhase"));
4509        assert!(yaml.contains("processRef: secret-injection"));
4510    }
4511
4512    #[test]
4513    fn serde_closed_loop_auth_condition() {
4514        let c = Condition {
4515            kind: ConditionKind::ClosedLoopAuth,
4516            params: json!({
4517                "issuer":   { "service": "demo-app-issuer", "port": 8080 },
4518                "consumer": { "service": "demo-app-gateway", "port": 8000 },
4519                "probeImage": "ghcr.io/pleme-io/closed-loop-probe:0.1.0",
4520            }),
4521        };
4522        let yaml = serde_yaml::to_string(&c).unwrap();
4523        assert!(yaml.contains("kind: ClosedLoopAuth"));
4524        assert!(yaml.contains("probeImage: ghcr.io/pleme-io/closed-loop-probe:0.1.0"));
4525        let back: Condition = serde_yaml::from_str(&yaml).unwrap();
4526        assert_eq!(back.kind, ConditionKind::ClosedLoopAuth);
4527    }
4528
4529    #[test]
4530    fn serde_job_attested_condition() {
4531        let c = Condition {
4532            kind: ConditionKind::JobAttested,
4533            params: json!({ "name": "seed-job", "namespace": "demo-test" }),
4534        };
4535        let yaml = serde_yaml::to_string(&c).unwrap();
4536        assert!(yaml.contains("kind: JobAttested"));
4537    }
4538
4539    // ── closed-set algebra contracts (ALL × as_str × FromStr × stub_message) ─
4540
4541    /// Structural well-formedness of [`ConditionKind`] as a
4542    /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
4543    /// testkit lift that pins all three structural invariants (`ALL`
4544    /// is non-empty, every variant round-trips through `label ↔
4545    /// parse_label`, labels are pairwise distinct, `""` is outside the
4546    /// closed set) at ONE call site. Replaces the hand-derived
4547    /// `condition_kind_all_is_unique_and_complete` +
4548    /// `condition_kind_roundtrip_via_as_str` + the empty-input arm of
4549    /// `unknown_condition_kind_errors`. `FromStr` delegates to
4550    /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this helper
4551    /// exercises the same code path the reconciler hits when parsing a
4552    /// CRD `enum:`-validated value back to the typed kind.
4553    #[test]
4554    fn condition_kind_is_well_formed_closed_set() {
4555        tatara_closed_set::assert_closed_set_well_formed::<ConditionKind>();
4556    }
4557
4558    /// CANONICAL-KEY CONTRACT: `as_str` matches serde's PascalCase
4559    /// output verbatim for every variant. A future variant rename
4560    /// (or an `as_str` arm typo) lands here at one site. The probe
4561    /// confirmed `PromQL` survives `rename_all = "PascalCase"` as
4562    /// `"PromQL"` (heck preserves consecutive caps in the leading
4563    /// word), so this contract is the operator-facing pin.
4564    #[test]
4565    fn condition_kind_as_str_matches_serde() {
4566        crate::tagged_union::assert_label_matches_serde_serialization::<ConditionKind>();
4567    }
4568
4569    /// The Display impl IS `as_str` — pinning this lets future
4570    /// callers reach for either projection without drift. If a
4571    /// reviewer accidentally re-introduces an inline match in
4572    /// Display, this fails the moment a variant rename touches one
4573    /// site but not the other.
4574    #[test]
4575    fn condition_kind_display_matches_as_str() {
4576        crate::tagged_union::assert_display_matches_label::<ConditionKind>();
4577    }
4578
4579    /// `FromStr` rejects strings that aren't in the canonical
4580    /// projection — lowercased / typo / unrelated — and the error
4581    /// echoes the input verbatim so the operator-facing diagnostic
4582    /// carries the offending value, not a normalized form. The
4583    /// empty-input arm is pinned by
4584    /// [`condition_kind_is_well_formed_closed_set`] via the
4585    /// `tatara_lisp::ClosedSet` testkit; the cases here pin the
4586    /// verbatim-echo contract on the [`UnknownConditionKind`]
4587    /// newtype, which the trait's `make_unknown` can't see.
4588    #[test]
4589    fn unknown_condition_kind_errors() {
4590        use std::str::FromStr;
4591        for bad in ["processPhase", "PROMQL", "Promql", "Bogus"] {
4592            let err = ConditionKind::from_str(bad).unwrap_err();
4593            assert_eq!(err.0, bad, "error payload should echo input verbatim");
4594        }
4595    }
4596
4597    /// STUB CONTRACT: the three placeholder evaluators
4598    /// (PromQL / Cel / NixEval) are exactly the set whose
4599    /// `stub_message` is `Some`. The five live evaluators return
4600    /// `None`. A future variant promoted from stub → live must drop
4601    /// its `stub_message` arm; a new stub must add one. Both
4602    /// transitions land at this test by sweeping ALL.
4603    #[test]
4604    fn condition_kind_stub_set_matches_stubs() {
4605        use ConditionKind::*;
4606        for kind in ConditionKind::ALL {
4607            let expected_is_stub = matches!(kind, PromQL | Cel | NixEval);
4608            assert_eq!(
4609                kind.is_stub(),
4610                expected_is_stub,
4611                "is_stub disagreed for {kind:?}",
4612            );
4613            assert_eq!(
4614                kind.stub_message().is_some(),
4615                expected_is_stub,
4616                "stub_message disagreed for {kind:?}",
4617            );
4618        }
4619    }
4620
4621    /// Pin the exact stub strings so a rename of the operator-facing
4622    /// "not yet implemented" message lands at one site (here) instead
4623    /// of three parallel inline strings in the reconciler.
4624    #[test]
4625    fn condition_kind_stub_messages_are_pinned() {
4626        assert_eq!(
4627            ConditionKind::PromQL.stub_message(),
4628            Some("PromQL evaluator not yet implemented"),
4629        );
4630        assert_eq!(
4631            ConditionKind::Cel.stub_message(),
4632            Some("CEL evaluator not yet implemented"),
4633        );
4634        assert_eq!(
4635            ConditionKind::NixEval.stub_message(),
4636            Some("NixEval evaluator not yet implemented"),
4637        );
4638    }
4639
4640    // ── (ConditionKind → FluxResource) typed projection contracts ────
4641
4642    /// The two Flux-fetching kinds project to their canonical
4643    /// [`FluxResource`] variants. A future ConditionKind rename or
4644    /// FluxResource variant rename that skewed the projection at ONE
4645    /// arm surfaces here.
4646    #[test]
4647    fn kustomization_healthy_projects_to_flux_resource_kustomization() {
4648        assert_eq!(
4649            ConditionKind::KustomizationHealthy.flux_resource(),
4650            Some(FluxResource::Kustomization),
4651        );
4652    }
4653
4654    #[test]
4655    fn helm_release_released_projects_to_flux_resource_helm_release() {
4656        assert_eq!(
4657            ConditionKind::HelmReleaseReleased.flux_resource(),
4658            Some(FluxResource::HelmRelease),
4659        );
4660    }
4661
4662    /// The six non-Flux-fetching kinds project to `None`. Sweeps
4663    /// `ConditionKind::ALL` filtering by `flux_resource().is_none()`
4664    /// so a new variant added without a `flux_resource` arm surfaces
4665    /// at rustc's non-exhaustive-match gate BEFORE this test even
4666    /// runs; a new variant added with a hand-coded `Some(...)` arm
4667    /// that shouldn't fetch Flux surfaces here.
4668    #[test]
4669    fn non_flux_fetching_kinds_project_to_none() {
4670        use ConditionKind::*;
4671        let non_flux: Vec<_> = ConditionKind::ALL
4672            .iter()
4673            .copied()
4674            .filter(|k| k.flux_resource().is_none())
4675            .collect();
4676        assert_eq!(
4677            non_flux,
4678            vec![
4679                ProcessPhase,
4680                PromQL,
4681                Cel,
4682                NixEval,
4683                JobAttested,
4684                ClosedLoopAuth
4685            ],
4686        );
4687    }
4688
4689    /// Every variant of [`ConditionKind`] whose `flux_resource()` is
4690    /// `Some` uniquely names its FluxResource variant (no two
4691    /// ConditionKind arms may fetch the SAME FluxResource — that
4692    /// would signal a redundant closed-set entry). Peers the
4693    /// `every_variants_api_version_and_kind_are_distinct_across_the_closed_set`
4694    /// pin on the sibling [`FluxResource`] closed set.
4695    #[test]
4696    fn flux_resource_projection_is_injective_on_the_some_arms() {
4697        let mut seen = std::collections::HashSet::new();
4698        for k in ConditionKind::ALL {
4699            if let Some(fr) = k.flux_resource() {
4700                assert!(
4701                    seen.insert(fr),
4702                    "duplicate FluxResource projection at {k:?}: {fr:?}",
4703                );
4704            }
4705        }
4706    }
4707
4708    /// `flux_resource` is `const fn` — the projection is reachable
4709    /// at compile time. A regression that dropped the `const`
4710    /// qualifier would fail-loudly here rather than as a wrong-slot
4711    /// runtime dispatch at every consumer callsite.
4712    #[test]
4713    fn flux_resource_projection_is_const_fn_reachable() {
4714        const K: Option<FluxResource> = ConditionKind::KustomizationHealthy.flux_resource();
4715        const H: Option<FluxResource> = ConditionKind::HelmReleaseReleased.flux_resource();
4716        const P: Option<FluxResource> = ConditionKind::ProcessPhase.flux_resource();
4717        assert_eq!(K, Some(FluxResource::Kustomization));
4718        assert_eq!(H, Some(FluxResource::HelmRelease));
4719        assert_eq!(P, None);
4720    }
4721
4722    // ── Boundary::has_condition_kind substrate pins ──────────────────
4723    //
4724    // Fail-before-pass-after granularity: `Boundary::has_condition_kind`
4725    // did not exist before this commit — the (preconditions +
4726    // postconditions .iter().any(|c| c.kind == K)) union-probe shape
4727    // lived hand-authored inline at the ephemeral require-tag surface
4728    // (`spec.postconditions.iter().any(|c| matches!(c.kind, K))`, sans
4729    // the pre-condition side). The lift places the closed-set-driven
4730    // presence probe on ONE substrate site so the point-domain
4731    // `condition-<kind>` prefix family in `tatara-check` composes it
4732    // through `strip_and_classify_prefixed_kind` byte-for-byte
4733    // symmetrical with `intent-<kind>` (via `Intent::has`) +
4734    // `lifetime-<kind>` (via `Lifetime::has`) — third instance in the
4735    // workspace closed-set-driven presence-probe algebra.
4736
4737    fn condition_with(kind: ConditionKind) -> Condition {
4738        Condition {
4739            kind,
4740            params: json!({}),
4741        }
4742    }
4743
4744    /// EMPTY-BOUNDARY pin — a default [`Boundary`] (no preconditions,
4745    /// no postconditions) returns `false` for EVERY [`ConditionKind`].
4746    /// Sweep `ConditionKind::ALL` so a new variant added without a
4747    /// matching arm in the presence probe surfaces at rustc's
4748    /// exhaustiveness gate on the ALL literal (arity forced by
4749    /// `[Self; 8]`) rather than as a silent false-positive at every
4750    /// downstream `condition-<kind>` require-tag callsite.
4751    #[test]
4752    fn has_condition_kind_returns_false_on_empty_boundary_for_every_kind() {
4753        let b = Boundary::default();
4754        for kind in ConditionKind::ALL {
4755            assert!(
4756                !b.has_condition_kind(kind),
4757                "default boundary must return false for {kind:?}",
4758            );
4759        }
4760    }
4761
4762    /// POSTCONDITION-only pin — a boundary that carries the kind on
4763    /// ONLY postconditions returns `true` for that kind, `false` for
4764    /// every other variant. Sweep the ALL × ALL cross so a regression
4765    /// that (a) hard-coded the arm to a single kind (silently
4766    /// returning true for every populated boundary regardless of
4767    /// which kind was queried), (b) skipped the postcondition side of
4768    /// the union (silently returning false when the kind lived
4769    /// post-only), or (c) matched on Condition::params instead of
4770    /// Condition::kind fails HERE at the substrate primitive.
4771    #[test]
4772    fn has_condition_kind_reads_postconditions_per_kind() {
4773        for populated in ConditionKind::ALL {
4774            let mut b = Boundary::default();
4775            b.postconditions.push(condition_with(populated));
4776            for query in ConditionKind::ALL {
4777                let expected = query == populated;
4778                assert_eq!(
4779                    b.has_condition_kind(query),
4780                    expected,
4781                    "postcondition populated={populated:?}: query {query:?} drifted",
4782                );
4783            }
4784        }
4785    }
4786
4787    /// PRECONDITION-only pin — mirrors the postcondition sweep on the
4788    /// other half of the union. Locks the union semantics on both
4789    /// halves separately so a regression that dropped the
4790    /// pre-condition side of the OR fails here even though the
4791    /// postcondition-side pin above passes.
4792    #[test]
4793    fn has_condition_kind_reads_preconditions_per_kind() {
4794        for populated in ConditionKind::ALL {
4795            let mut b = Boundary::default();
4796            b.preconditions.push(condition_with(populated));
4797            for query in ConditionKind::ALL {
4798                let expected = query == populated;
4799                assert_eq!(
4800                    b.has_condition_kind(query),
4801                    expected,
4802                    "precondition populated={populated:?}: query {query:?} drifted",
4803                );
4804            }
4805        }
4806    }
4807
4808    /// UNION pin — a kind that appears on preconditions returns
4809    /// `true` even when postconditions carries a DIFFERENT kind, and
4810    /// vice versa. Pins the OR-composition of the two halves so a
4811    /// regression that collapsed the union to an intersection (AND)
4812    /// silently reclassifies pre-only or post-only kinds as absent.
4813    #[test]
4814    fn has_condition_kind_unions_pre_and_post_condition_arms() {
4815        let mut b = Boundary::default();
4816        b.preconditions
4817            .push(condition_with(ConditionKind::KustomizationHealthy));
4818        b.postconditions
4819            .push(condition_with(ConditionKind::ClosedLoopAuth));
4820        assert!(
4821            b.has_condition_kind(ConditionKind::KustomizationHealthy),
4822            "pre-only kind must resolve through the union",
4823        );
4824        assert!(
4825            b.has_condition_kind(ConditionKind::ClosedLoopAuth),
4826            "post-only kind must resolve through the union",
4827        );
4828        assert!(
4829            !b.has_condition_kind(ConditionKind::PromQL),
4830            "an absent kind must return false even with populated halves",
4831        );
4832    }
4833
4834    // ── ConditionSliceExt::has_kind substrate pins ────────────────────
4835    //
4836    // Fail-before-pass-after granularity: `ConditionSliceExt::has_kind`
4837    // did not exist before this commit — the `(&[Condition],
4838    // ConditionKind) -> bool` walk shape lived hand-authored inline at
4839    // THREE production sites (twice inside `Boundary::has_condition_kind`
4840    // on `preconditions` ∪ `postconditions`, once at the ephemeral
4841    // require-tag classifier's `closed-loop-auth` arm on
4842    // `spec.postconditions` in `tatara-reconciler::bin::tatara-check`,
4843    // with `matches!` sugar instead of `==` but the same predicate).
4844    // The lift places the per-slice presence probe on ONE substrate site
4845    // so the two-half union at `Boundary` and the one-half probe at the
4846    // ephemeral surface compose against the SAME primitive rather than
4847    // restating the `.iter().any(|c| c.kind == K)` closure body.
4848
4849    /// EMPTY-SLICE pin — an empty `&[Condition]` returns `false` for
4850    /// EVERY [`ConditionKind`]. Sweep `ConditionKind::ALL` so a new
4851    /// variant added without a matching arm in the primitive surfaces
4852    /// at rustc's exhaustiveness gate on the ALL literal (arity forced
4853    /// by `[Self; 8]`) rather than as a silent false-positive at every
4854    /// downstream callsite composing this primitive.
4855    #[test]
4856    fn condition_slice_has_kind_returns_false_on_empty_slice_for_every_kind() {
4857        let empty: &[Condition] = &[];
4858        for kind in ConditionKind::ALL {
4859            assert!(
4860                !empty.has_kind(kind),
4861                "empty slice must return false for {kind:?}",
4862            );
4863        }
4864    }
4865
4866    /// PER-VARIANT pin — a single-element slice returns `true` for
4867    /// exactly the kind it carries, `false` for every other variant.
4868    /// Sweep the ALL × ALL cross so a regression that (a) hard-coded
4869    /// the arm to a single kind (silently returning true for every
4870    /// populated slice regardless of query kind), or (b) matched on
4871    /// [`Condition::params`] instead of [`Condition::kind`] fails HERE
4872    /// at the substrate primitive.
4873    #[test]
4874    fn condition_slice_has_kind_reads_kind_field_per_variant() {
4875        for populated in ConditionKind::ALL {
4876            let slice = [condition_with(populated)];
4877            for query in ConditionKind::ALL {
4878                let expected = query == populated;
4879                assert_eq!(
4880                    slice.has_kind(query),
4881                    expected,
4882                    "populated={populated:?}: query {query:?} drifted",
4883                );
4884            }
4885        }
4886    }
4887
4888    /// MULTI-ENTRY pin — a slice with multiple entries returns `true`
4889    /// for every kind that appears at any position (existential
4890    /// quantifier over the slice), `false` for kinds that appear at
4891    /// no position. Locks the `any` semantics so a regression that
4892    /// collapsed to a `first`-only probe (`slice.first().map_or(false,
4893    /// |c| c.kind == kind)`) fails here even though the single-element
4894    /// per-variant pin above passes.
4895    #[test]
4896    fn condition_slice_has_kind_scans_beyond_the_first_position() {
4897        let slice = [
4898            condition_with(ConditionKind::KustomizationHealthy),
4899            condition_with(ConditionKind::ClosedLoopAuth),
4900            condition_with(ConditionKind::JobAttested),
4901        ];
4902        for present in [
4903            ConditionKind::KustomizationHealthy,
4904            ConditionKind::ClosedLoopAuth,
4905            ConditionKind::JobAttested,
4906        ] {
4907            assert!(
4908                slice.has_kind(present),
4909                "kind at any position must resolve true: {present:?}",
4910            );
4911        }
4912        for absent in [
4913            ConditionKind::ProcessPhase,
4914            ConditionKind::HelmReleaseReleased,
4915            ConditionKind::PromQL,
4916            ConditionKind::Cel,
4917            ConditionKind::NixEval,
4918        ] {
4919            assert!(
4920                !slice.has_kind(absent),
4921                "kind absent from the slice must resolve false: {absent:?}",
4922            );
4923        }
4924    }
4925
4926    /// COMPOSITION pin — [`Boundary::has_condition_kind`] equals the OR
4927    /// of the two half-slice probes at EVERY (populated arrangement,
4928    /// query) pair on `ConditionKind::ALL`. Locks the (union-probe =
4929    /// pre.has_kind ∨ post.has_kind) composition contract at ONE test
4930    /// so a regression that (a) dropped the `||` (silently narrowing
4931    /// the union to an intersection, or to one side only), or
4932    /// (b) hand-authored the union with a divergent walk shape (e.g.
4933    /// summing counts, comparing lengths) surfaces HERE at the
4934    /// composition boundary rather than as silent classifier drift at
4935    /// every downstream `condition-<kind>` require-tag callsite.
4936    #[test]
4937    fn boundary_has_condition_kind_equals_or_of_half_slice_probes() {
4938        for pre_kind in ConditionKind::ALL {
4939            for post_kind in ConditionKind::ALL {
4940                let mut b = Boundary::default();
4941                b.preconditions.push(condition_with(pre_kind));
4942                b.postconditions.push(condition_with(post_kind));
4943                for query in ConditionKind::ALL {
4944                    let expected =
4945                        b.preconditions.has_kind(query) || b.postconditions.has_kind(query);
4946                    assert_eq!(
4947                        b.has_condition_kind(query),
4948                        expected,
4949                        "union drifted: pre={pre_kind:?} post={post_kind:?} query={query:?}",
4950                    );
4951                }
4952            }
4953        }
4954    }
4955
4956    // ── Boundary::has_(pre|post)condition_kind substrate pins ────────
4957    //
4958    // Fail-before-pass-after granularity: the two half-slice arms did
4959    // not exist before this commit — the point-domain `precondition-
4960    // <kind>` and `postcondition-<kind>` require-tag classifiers in
4961    // `tatara-reconciler::bin::tatara-check` reached the two condition
4962    // slices through direct field access
4963    // (`spec.boundary.preconditions.has_kind(k)`), bypassing the named
4964    // [`Boundary`] primitive surface that the union-probe
4965    // [`Boundary::has_condition_kind`] already routed through. The
4966    // lift closes the (precondition, postcondition, union) triad on
4967    // ONE typed algebra surface so a future normalization at the
4968    // presence-probe shape lands at ONE site for all three arms.
4969
4970    /// EMPTY-BOUNDARY pin (precondition arm) — a default [`Boundary`]
4971    /// returns `false` for EVERY [`ConditionKind`] on the precondition
4972    /// side. Sweep `ConditionKind::ALL` so a new variant added without
4973    /// a matching arm on the probe surfaces at rustc's exhaustiveness
4974    /// gate on the ALL literal (arity forced by `[Self; 8]`) rather
4975    /// than as a silent false-positive at every downstream
4976    /// `precondition-<kind>` require-tag callsite.
4977    #[test]
4978    fn has_precondition_kind_returns_false_on_empty_boundary_for_every_kind() {
4979        let b = Boundary::default();
4980        for kind in ConditionKind::ALL {
4981            assert!(
4982                !b.has_precondition_kind(kind),
4983                "default boundary must return false on precondition arm for {kind:?}",
4984            );
4985        }
4986    }
4987
4988    /// EMPTY-BOUNDARY pin (postcondition arm) — sibling of the
4989    /// precondition-arm empty pin above on the other half of the
4990    /// (precondition, postcondition) partition. Locks the empty-slice
4991    /// arm return on the postcondition side so a regression that
4992    /// wired the postcondition arm to the precondition slice surfaces
4993    /// HERE at fail-before-pass-after granularity.
4994    #[test]
4995    fn has_postcondition_kind_returns_false_on_empty_boundary_for_every_kind() {
4996        let b = Boundary::default();
4997        for kind in ConditionKind::ALL {
4998            assert!(
4999                !b.has_postcondition_kind(kind),
5000                "default boundary must return false on postcondition arm for {kind:?}",
5001            );
5002        }
5003    }
5004
5005    /// SLICE-SELECTIVITY pin (precondition arm) — a boundary with a
5006    /// kind on the precondition side ONLY resolves `true` at
5007    /// `has_precondition_kind` and `false` at `has_postcondition_kind`.
5008    /// Locks the (side-select, kind-select) partition so a regression
5009    /// that pointed the precondition arm at `self.postconditions` (a
5010    /// copy-paste from the sibling arm) surfaces HERE rather than as
5011    /// silent classifier drift at every downstream
5012    /// `precondition-<kind>` require-tag callsite.
5013    #[test]
5014    fn has_precondition_kind_reads_preconditions_slice_only() {
5015        for populated in ConditionKind::ALL {
5016            let mut b = Boundary::default();
5017            b.preconditions.push(condition_with(populated));
5018            for query in ConditionKind::ALL {
5019                let expected_pre = query == populated;
5020                assert_eq!(
5021                    b.has_precondition_kind(query),
5022                    expected_pre,
5023                    "precondition-only populated={populated:?}: query {query:?} drifted \
5024                     on precondition arm",
5025                );
5026                assert!(
5027                    !b.has_postcondition_kind(query),
5028                    "precondition-only populated={populated:?}: query {query:?} must \
5029                     return false on postcondition arm (postconditions is empty)",
5030                );
5031            }
5032        }
5033    }
5034
5035    /// SLICE-SELECTIVITY pin (postcondition arm) — mirror of the
5036    /// precondition-only sweep on the other half. Locks the sibling
5037    /// arm's binding to `self.postconditions` so a regression that
5038    /// pointed the postcondition arm at `self.preconditions` fails
5039    /// HERE even though the precondition-arm pin above passes.
5040    #[test]
5041    fn has_postcondition_kind_reads_postconditions_slice_only() {
5042        for populated in ConditionKind::ALL {
5043            let mut b = Boundary::default();
5044            b.postconditions.push(condition_with(populated));
5045            for query in ConditionKind::ALL {
5046                let expected_post = query == populated;
5047                assert_eq!(
5048                    b.has_postcondition_kind(query),
5049                    expected_post,
5050                    "postcondition-only populated={populated:?}: query {query:?} \
5051                     drifted on postcondition arm",
5052                );
5053                assert!(
5054                    !b.has_precondition_kind(query),
5055                    "postcondition-only populated={populated:?}: query {query:?} must \
5056                     return false on precondition arm (preconditions is empty)",
5057                );
5058            }
5059        }
5060    }
5061
5062    /// COMPOSITION-LAW pin — [`Boundary::has_condition_kind`] equals
5063    /// `has_precondition_kind(k) || has_postcondition_kind(k)` at
5064    /// EVERY (pre-populated, post-populated, query) triple on
5065    /// `ConditionKind::ALL`. This is the load-bearing invariant that
5066    /// makes the (precondition, postcondition, union) triad on
5067    /// [`Boundary`] a first-class typed algebra rather than a
5068    /// per-caller discipline: the two half-slice arms + the union arm
5069    /// compose exactly as `union == pre ∨ post`, and every downstream
5070    /// `condition-<K> = precondition-<K> ∨ postcondition-<K>` classifier
5071    /// invariant on `tatara-reconciler::bin::tatara-check` inherits it
5072    /// mechanically. A regression that (a) dropped the composition (by
5073    /// re-inlining `.has_kind(kind)` bodies on the union arm), or
5074    /// (b) drifted ONE of the two half-slice arms without updating the
5075    /// other, surfaces HERE rather than as silent per-side classifier
5076    /// drift at the require-tag surfaces.
5077    #[test]
5078    fn boundary_has_condition_kind_composes_precondition_and_postcondition_arms() {
5079        for pre_kind in ConditionKind::ALL {
5080            for post_kind in ConditionKind::ALL {
5081                let mut b = Boundary::default();
5082                b.preconditions.push(condition_with(pre_kind));
5083                b.postconditions.push(condition_with(post_kind));
5084                for query in ConditionKind::ALL {
5085                    let via_arms =
5086                        b.has_precondition_kind(query) || b.has_postcondition_kind(query);
5087                    assert_eq!(
5088                        b.has_condition_kind(query),
5089                        via_arms,
5090                        "union arm drifted from OR of half-slice arms: \
5091                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5092                    );
5093                }
5094            }
5095        }
5096    }
5097
5098    /// SUBSTRATE-DELEGATION pin — the two half-slice arms delegate
5099    /// verbatim to [`ConditionSliceExt::has_kind`] on the underlying
5100    /// [`Vec<Condition>`] slice, no inline reimplementation. Sweep the
5101    /// full `ConditionKind::ALL` × `ConditionKind::ALL` cross so a
5102    /// regression that inlined a divergent walk (`.iter().find(_).
5103    /// is_some()`, an `.any(|c| matches!(c.kind, K))` that missed a
5104    /// variant) at either arm surfaces HERE at the substrate
5105    /// boundary rather than as silent skew between the struct-level
5106    /// arm and the slice-level primitive downstream consumers reach
5107    /// through.
5108    #[test]
5109    fn has_precondition_and_postcondition_kind_delegate_to_slice_has_kind() {
5110        for populated in ConditionKind::ALL {
5111            let mut b = Boundary::default();
5112            b.preconditions.push(condition_with(populated));
5113            b.postconditions.push(condition_with(populated));
5114            for query in ConditionKind::ALL {
5115                assert_eq!(
5116                    b.has_precondition_kind(query),
5117                    b.preconditions.has_kind(query),
5118                    "precondition arm must delegate to preconditions.has_kind: \
5119                     populated={populated:?} query={query:?}",
5120                );
5121                assert_eq!(
5122                    b.has_postcondition_kind(query),
5123                    b.postconditions.has_kind(query),
5124                    "postcondition arm must delegate to postconditions.has_kind: \
5125                     populated={populated:?} query={query:?}",
5126                );
5127            }
5128        }
5129    }
5130
5131    // ── ConditionSliceExt::find_kind substrate pins + widened triad ──
5132    //
5133    // Fail-before-pass-after granularity: `ConditionSliceExt::find_kind`
5134    // + its three struct-level peers (`Boundary::find_(pre|post)?
5135    // condition_kind`) did not exist before this commit — the existing
5136    // `has_*_kind` triad collapses the return to `bool`, losing the
5137    // matching `&Condition` a future diagnostic consumer (an operator-
5138    // facing "found on {pre|post}conditions at param.probeImage=X"
5139    // message, a coherence check verifying "every ClosedLoopAuth
5140    // postcondition carries a non-empty probeImage", an editor
5141    // completion listing params-keys per present kind) needs. The lift
5142    // widens the primitive to `Option<&Condition>` and re-anchors
5143    // `has_kind` as a default composed from it, so the two refinements
5144    // share ONE walk semantics by construction.
5145
5146    /// EMPTY-SLICE pin — an empty `&[Condition]` returns `None` from
5147    /// `find_kind` for EVERY [`ConditionKind`]. Sweep
5148    /// `ConditionKind::ALL` so a new variant added without a matching
5149    /// arm in the primitive surfaces at rustc's exhaustiveness gate on
5150    /// the ALL literal (arity forced by `[Self; 8]`) rather than as a
5151    /// silent false-`Some` at every downstream widened callsite.
5152    #[test]
5153    fn condition_slice_find_kind_returns_none_on_empty_slice_for_every_kind() {
5154        let empty: &[Condition] = &[];
5155        for kind in ConditionKind::ALL {
5156            assert!(
5157                empty.find_kind(kind).is_none(),
5158                "empty slice must return None for {kind:?}",
5159            );
5160        }
5161    }
5162
5163    /// PER-VARIANT pin — a single-element slice returns `Some` with
5164    /// the matching kind for exactly the kind it carries, `None` for
5165    /// every other variant. Sweep the ALL × ALL cross so a regression
5166    /// that (a) hard-coded the arm to a single kind (silently returning
5167    /// `Some` for every populated slice regardless of query kind), or
5168    /// (b) matched on [`Condition::params`] instead of [`Condition::kind`]
5169    /// fails HERE at the substrate primitive.
5170    #[test]
5171    fn condition_slice_find_kind_reads_kind_field_per_variant() {
5172        for populated in ConditionKind::ALL {
5173            let slice = [condition_with(populated)];
5174            for query in ConditionKind::ALL {
5175                let hit = slice.find_kind(query);
5176                if query == populated {
5177                    assert_eq!(
5178                        hit.map(|c| c.kind),
5179                        Some(populated),
5180                        "populated={populated:?}: query {query:?} must return Some",
5181                    );
5182                } else {
5183                    assert!(
5184                        hit.is_none(),
5185                        "populated={populated:?}: query {query:?} must return None",
5186                    );
5187                }
5188            }
5189        }
5190    }
5191
5192    /// FIRST-MATCH pin — a slice with the same kind at MULTIPLE
5193    /// positions returns the earliest by position. Locks the `.iter().
5194    /// find(...)` semantics so a regression that collapsed to a
5195    /// `.last()` walk (returning the trailing match) or a `.rev().
5196    /// find(...)` walk (returning the last-inserted match) surfaces
5197    /// HERE, since diagnostic consumers reading `find_kind(K).unwrap().
5198    /// params` expect the FIRST occurrence's params-payload not the
5199    /// last.
5200    #[test]
5201    fn condition_slice_find_kind_returns_first_position_on_duplicate_kinds() {
5202        // Two ClosedLoopAuth entries with distinct params — a first-
5203        // match walk resolves to the leading entry's params-payload.
5204        let first = Condition {
5205            kind: ConditionKind::ClosedLoopAuth,
5206            params: json!({ "probeImage": "first" }),
5207        };
5208        let second = Condition {
5209            kind: ConditionKind::ClosedLoopAuth,
5210            params: json!({ "probeImage": "second" }),
5211        };
5212        let slice = [first, second];
5213        let hit = slice
5214            .find_kind(ConditionKind::ClosedLoopAuth)
5215            .expect("populated slice must resolve Some on the matching kind");
5216        assert_eq!(
5217            hit.params
5218                .get("probeImage")
5219                .and_then(serde_json::Value::as_str),
5220            Some("first"),
5221            "find_kind must return the FIRST position's Condition on duplicate kinds",
5222        );
5223    }
5224
5225    /// SLICE-LEVEL DELEGATION pin (has ↔ find) — [`ConditionSliceExt::has_kind`]
5226    /// equals `find_kind(k).is_some()` at EVERY (populated arrangement,
5227    /// query) pair on `ConditionKind::ALL`. Turns the trait doc's
5228    /// "compounding" note ("the closed-set discriminator case becomes
5229    /// `has_kind(k) == self.find_kind(k).is_some()` by construction")
5230    /// into a first-class typed test invariant: a future consumer
5231    /// that overrode the default `has_kind` body with a divergent walk
5232    /// shape (a `.iter().any(...)` that missed a variant, a `.count() >
5233    /// 0` predicate on a filtered clone) surfaces HERE at the substrate
5234    /// boundary rather than as silent skew between the two refinements
5235    /// downstream consumers reach through.
5236    #[test]
5237    fn condition_slice_has_kind_equals_find_kind_is_some() {
5238        for pre_kind in ConditionKind::ALL {
5239            for post_kind in ConditionKind::ALL {
5240                let slice = [condition_with(pre_kind), condition_with(post_kind)];
5241                for query in ConditionKind::ALL {
5242                    assert_eq!(
5243                        slice.has_kind(query),
5244                        slice.find_kind(query).is_some(),
5245                        "slice-level has/find refinement bridge drifted: \
5246                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5247                    );
5248                }
5249            }
5250        }
5251    }
5252
5253    /// SUBSTRATE-DELEGATION pin (find-triad) — the three widened
5254    /// `find_*_kind` methods on [`Boundary`] delegate verbatim to
5255    /// [`ConditionSliceExt::find_kind`] on the underlying
5256    /// [`Vec<Condition>`] slices, no inline reimplementation. The
5257    /// `find_condition_kind` union walks preconditions first then
5258    /// postconditions via `Option::or_else`. Sweep
5259    /// `ConditionKind::ALL × ConditionKind::ALL × ConditionKind::ALL`
5260    /// so a regression that (a) inlined a divergent walk at either
5261    /// half-slice arm, (b) reversed the union walk order (postcondition
5262    /// first), or (c) collapsed `or_else` to `and_then` (silently
5263    /// narrowing the union to an intersection) surfaces HERE at the
5264    /// substrate boundary rather than as silent skew between the
5265    /// struct-level widened arms and the slice-level primitive.
5266    #[test]
5267    fn find_condition_kind_triad_delegates_to_slice_find_kind() {
5268        for pre_kind in ConditionKind::ALL {
5269            for post_kind in ConditionKind::ALL {
5270                let mut b = Boundary::default();
5271                b.preconditions.push(condition_with(pre_kind));
5272                b.postconditions.push(condition_with(post_kind));
5273                for query in ConditionKind::ALL {
5274                    let via_pre = b.preconditions.find_kind(query);
5275                    let via_post = b.postconditions.find_kind(query);
5276                    assert_eq!(
5277                        b.find_precondition_kind(query).map(|c| c.kind),
5278                        via_pre.map(|c| c.kind),
5279                        "precondition find arm must delegate to preconditions.find_kind: \
5280                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5281                    );
5282                    assert_eq!(
5283                        b.find_postcondition_kind(query).map(|c| c.kind),
5284                        via_post.map(|c| c.kind),
5285                        "postcondition find arm must delegate to postconditions.find_kind: \
5286                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5287                    );
5288                    let expected_union = via_pre.or(via_post).map(|c| c.kind);
5289                    assert_eq!(
5290                        b.find_condition_kind(query).map(|c| c.kind),
5291                        expected_union,
5292                        "union find arm must equal precondition.or_else(postcondition): \
5293                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5294                    );
5295                }
5296            }
5297        }
5298    }
5299
5300    /// PRECONDITION-PRECEDENCE pin — a kind authored on BOTH sides
5301    /// returns the precondition-side [`Condition`] from
5302    /// `find_condition_kind`. Uses two params-distinguishable
5303    /// [`Condition`]s so a regression that reversed the walk order
5304    /// (postcondition first) surfaces at the returned params payload
5305    /// rather than silently at the presence bit (which is `true` on
5306    /// both walk orders).
5307    #[test]
5308    fn find_condition_kind_returns_precondition_side_on_dual_populated() {
5309        let mut b = Boundary::default();
5310        b.preconditions.push(Condition {
5311            kind: ConditionKind::ClosedLoopAuth,
5312            params: json!({ "side": "pre" }),
5313        });
5314        b.postconditions.push(Condition {
5315            kind: ConditionKind::ClosedLoopAuth,
5316            params: json!({ "side": "post" }),
5317        });
5318        let hit = b
5319            .find_condition_kind(ConditionKind::ClosedLoopAuth)
5320            .expect("dual-populated boundary must resolve Some");
5321        assert_eq!(
5322            hit.params.get("side").and_then(serde_json::Value::as_str),
5323            Some("pre"),
5324            "find_condition_kind must walk preconditions first: dual-populated kind \
5325             returned postcondition-side Condition rather than precondition-side",
5326        );
5327    }
5328
5329    /// STRUCT-LEVEL DELEGATION pin (has ↔ find) — the three
5330    /// [`Boundary`] `has_*_kind` arms equal their widened peers'
5331    /// `.is_some()` projection at EVERY (pre-populated, post-populated,
5332    /// query) triple on `ConditionKind::ALL`. The three widened
5333    /// `find_*_kind` arms are the load-bearing primitives; the three
5334    /// `has_*_kind` arms are their bool projections. Byte-for-byte
5335    /// re-anchors the composition-law pin
5336    /// `boundary_has_condition_kind_composes_precondition_and_postcondition_arms`
5337    /// through the widened axis so a future consumer that reads
5338    /// `has_condition_kind` as sugar for `find_condition_kind(k).
5339    /// is_some()` (rather than as `has_precondition_kind ||
5340    /// has_postcondition_kind`) stays typed against the SAME truth
5341    /// table.
5342    #[test]
5343    fn boundary_has_triad_equals_find_triad_is_some_projection() {
5344        for pre_kind in ConditionKind::ALL {
5345            for post_kind in ConditionKind::ALL {
5346                let mut b = Boundary::default();
5347                b.preconditions.push(condition_with(pre_kind));
5348                b.postconditions.push(condition_with(post_kind));
5349                for query in ConditionKind::ALL {
5350                    assert_eq!(
5351                        b.has_precondition_kind(query),
5352                        b.find_precondition_kind(query).is_some(),
5353                        "precondition has/find bridge drifted: \
5354                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5355                    );
5356                    assert_eq!(
5357                        b.has_postcondition_kind(query),
5358                        b.find_postcondition_kind(query).is_some(),
5359                        "postcondition has/find bridge drifted: \
5360                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5361                    );
5362                    assert_eq!(
5363                        b.has_condition_kind(query),
5364                        b.find_condition_kind(query).is_some(),
5365                        "union has/find bridge drifted: \
5366                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5367                    );
5368                }
5369            }
5370        }
5371    }
5372
5373    // ── ConditionSliceExt::iter_kind substrate pins + widened triad ──
5374    //
5375    // Fail-before-pass-after granularity: `ConditionSliceExt::iter_kind`
5376    // + its three struct-level peers (`Boundary::iter_(pre|post|)?
5377    // condition_kind`) did not exist before this commit — the existing
5378    // `find_*_kind` triad collapses the return to `Option<&Condition>`
5379    // (yielding only the FIRST match), losing the full match stream a
5380    // future coherence check ("each ConditionKind appears at most
5381    // once per side" — `iter_kind(k).nth(1).is_none()`) or diagnostic
5382    // consumer ("N ClosedLoopAuth postconditions matched, listing
5383    // every param.probeImage" — `iter_kind(k).collect()`) needs. The
5384    // lift widens the primitive to `KindMatches<'_>` (a named
5385    // Iterator<Item = &Condition>) and re-anchors `find_kind` as a
5386    // default composed from it (`self.iter_kind(kind).next()`), so
5387    // the three refinements share ONE walk semantics by construction.
5388
5389    /// EMPTY-SLICE pin (iter) — an empty `&[Condition]` yields
5390    /// nothing from `iter_kind` for EVERY [`ConditionKind`]. Sweep
5391    /// `ConditionKind::ALL` so a new variant added without a matching
5392    /// arm in the primitive surfaces at rustc's exhaustiveness gate
5393    /// on the ALL literal rather than as a silent phantom-yield at
5394    /// every downstream widened callsite.
5395    #[test]
5396    fn condition_slice_iter_kind_yields_nothing_on_empty_slice_for_every_kind() {
5397        let empty: &[Condition] = &[];
5398        for kind in ConditionKind::ALL {
5399            assert_eq!(
5400                empty.iter_kind(kind).count(),
5401                0,
5402                "empty slice must yield nothing on iter_kind for {kind:?}",
5403            );
5404        }
5405    }
5406
5407    /// PER-VARIANT pin (iter) — a single-element slice yields exactly
5408    /// that element on the matching kind and nothing on every other
5409    /// kind. Sweep the ALL × ALL cross so a regression that (a)
5410    /// hard-coded the filter predicate to a single kind (silently
5411    /// yielding on every populated slice regardless of query kind),
5412    /// or (b) matched on [`Condition::params`] instead of
5413    /// [`Condition::kind`] fails HERE at the substrate primitive.
5414    #[test]
5415    fn condition_slice_iter_kind_reads_kind_field_per_variant() {
5416        for populated in ConditionKind::ALL {
5417            let slice = [condition_with(populated)];
5418            for query in ConditionKind::ALL {
5419                let collected: Vec<_> = slice.iter_kind(query).map(|c| c.kind).collect();
5420                if query == populated {
5421                    assert_eq!(
5422                        collected,
5423                        vec![populated],
5424                        "populated={populated:?}: query {query:?} must yield [populated]",
5425                    );
5426                } else {
5427                    assert!(
5428                        collected.is_empty(),
5429                        "populated={populated:?}: query {query:?} must yield nothing",
5430                    );
5431                }
5432            }
5433        }
5434    }
5435
5436    /// ALL-MATCHES pin — a slice with the same kind at MULTIPLE
5437    /// positions yields EVERY match in slice order (not just the
5438    /// first). Uses params-distinguishable [`Condition`]s so a
5439    /// regression that (a) collapsed to a single-match walk
5440    /// (`.iter().find(...)` yielding only the earliest and
5441    /// terminating), (b) reversed the yield order (`.rev().filter`
5442    /// yielding trailing-first), or (c) de-duplicated by kind (an
5443    /// erroneous `HashSet::insert`-gated walk) surfaces HERE at the
5444    /// params payload rather than silently at a downstream
5445    /// count-based coherence check.
5446    #[test]
5447    fn condition_slice_iter_kind_yields_every_match_in_slice_order_on_duplicates() {
5448        let first = Condition {
5449            kind: ConditionKind::ClosedLoopAuth,
5450            params: json!({ "probeImage": "first" }),
5451        };
5452        let middle = Condition {
5453            kind: ConditionKind::PromQL,
5454            params: json!({ "query": "up" }),
5455        };
5456        let second_cla = Condition {
5457            kind: ConditionKind::ClosedLoopAuth,
5458            params: json!({ "probeImage": "second" }),
5459        };
5460        let slice = [first, middle, second_cla];
5461        let hits: Vec<_> = slice
5462            .iter_kind(ConditionKind::ClosedLoopAuth)
5463            .map(|c| {
5464                c.params
5465                    .get("probeImage")
5466                    .and_then(serde_json::Value::as_str)
5467                    .unwrap_or_default()
5468                    .to_owned()
5469            })
5470            .collect();
5471        assert_eq!(
5472            hits,
5473            vec!["first".to_owned(), "second".to_owned()],
5474            "iter_kind must yield every match in slice order (not just the first)",
5475        );
5476        // The interleaved non-matching kind is skipped: two hits, not three.
5477        assert_eq!(
5478            slice.iter_kind(ConditionKind::ClosedLoopAuth).count(),
5479            2,
5480            "iter_kind must skip non-matching kinds, not include them in the stream",
5481        );
5482    }
5483
5484    /// SLICE-LEVEL DELEGATION pin (find ↔ iter) — the trait's default
5485    /// `find_kind` body equals `iter_kind(k).next()` at EVERY
5486    /// (populated arrangement, query) pair on `ConditionKind::ALL`.
5487    /// Turns the trait doc's composition-law note
5488    /// ("`find_kind(k) == iter_kind(k).next()` by construction")
5489    /// into a first-class typed test invariant: a future implementor
5490    /// that overrode the default `find_kind` body with a divergent
5491    /// walk shape (a `.iter().rev().find(...)` returning trailing-
5492    /// first, a hand-rolled loop that walked past the first match)
5493    /// surfaces HERE at the substrate boundary rather than as silent
5494    /// skew between the two refinements downstream consumers reach
5495    /// through.
5496    #[test]
5497    fn condition_slice_find_kind_equals_iter_kind_next() {
5498        for pre_kind in ConditionKind::ALL {
5499            for post_kind in ConditionKind::ALL {
5500                let slice = [condition_with(pre_kind), condition_with(post_kind)];
5501                for query in ConditionKind::ALL {
5502                    assert_eq!(
5503                        slice.find_kind(query).map(|c| c.kind),
5504                        slice.iter_kind(query).next().map(|c| c.kind),
5505                        "slice-level find/iter refinement bridge drifted: \
5506                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5507                    );
5508                }
5509            }
5510        }
5511    }
5512
5513    /// SUBSTRATE-DELEGATION pin (Boundary iter-triad) — the three
5514    /// widened `iter_*_kind` methods on [`Boundary`] delegate verbatim
5515    /// to [`ConditionSliceExt::iter_kind`] on the underlying
5516    /// [`Vec<Condition>`] slices, no inline reimplementation. The
5517    /// `iter_condition_kind` union chains preconditions first then
5518    /// postconditions via [`Iterator::chain`]. Sweep
5519    /// `ConditionKind::ALL × ConditionKind::ALL × ConditionKind::ALL`
5520    /// so a regression that (a) inlined a divergent walk at either
5521    /// half-slice arm, (b) reversed the chain order (postcondition
5522    /// first — walk-order regression on the union), or (c) collapsed
5523    /// the chain to a `.zip(...)` (silently narrowing the union to
5524    /// an intersection-by-position) surfaces HERE at the substrate
5525    /// boundary rather than as silent skew between the struct-level
5526    /// widened arms and the slice-level primitive.
5527    #[test]
5528    fn iter_condition_kind_triad_delegates_to_slice_iter_kind() {
5529        for pre_kind in ConditionKind::ALL {
5530            for post_kind in ConditionKind::ALL {
5531                let mut b = Boundary::default();
5532                b.preconditions.push(condition_with(pre_kind));
5533                b.postconditions.push(condition_with(post_kind));
5534                for query in ConditionKind::ALL {
5535                    let via_pre: Vec<_> =
5536                        b.preconditions.iter_kind(query).map(|c| c.kind).collect();
5537                    let via_post: Vec<_> =
5538                        b.postconditions.iter_kind(query).map(|c| c.kind).collect();
5539                    assert_eq!(
5540                        b.iter_precondition_kind(query)
5541                            .map(|c| c.kind)
5542                            .collect::<Vec<_>>(),
5543                        via_pre,
5544                        "precondition iter arm must delegate to preconditions.iter_kind: \
5545                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5546                    );
5547                    assert_eq!(
5548                        b.iter_postcondition_kind(query)
5549                            .map(|c| c.kind)
5550                            .collect::<Vec<_>>(),
5551                        via_post,
5552                        "postcondition iter arm must delegate to postconditions.iter_kind: \
5553                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5554                    );
5555                    let mut expected_union = via_pre.clone();
5556                    expected_union.extend(via_post.iter().copied());
5557                    assert_eq!(
5558                        b.iter_condition_kind(query)
5559                            .map(|c| c.kind)
5560                            .collect::<Vec<_>>(),
5561                        expected_union,
5562                        "union iter arm must chain precondition ⨟ postcondition: \
5563                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5564                    );
5565                }
5566            }
5567        }
5568    }
5569
5570    /// STRUCT-LEVEL DELEGATION pin (find ↔ iter on Boundary) — the
5571    /// three [`Boundary`] `find_*_kind` arms equal their widened
5572    /// peers' `.next()` projection at EVERY (pre-populated,
5573    /// post-populated, query) triple on `ConditionKind::ALL`. Byte-
5574    /// for-byte re-anchors the composition-law pin
5575    /// `find_condition_kind == iter_condition_kind.next()` through
5576    /// the widened axis on the parent surface — a future consumer
5577    /// that reads `find_condition_kind(k)` as sugar for
5578    /// `iter_condition_kind(k).next()` stays typed against the SAME
5579    /// truth table on both the slice-level and struct-level layers.
5580    #[test]
5581    fn boundary_find_triad_equals_iter_triad_next_projection() {
5582        for pre_kind in ConditionKind::ALL {
5583            for post_kind in ConditionKind::ALL {
5584                let mut b = Boundary::default();
5585                b.preconditions.push(condition_with(pre_kind));
5586                b.postconditions.push(condition_with(post_kind));
5587                for query in ConditionKind::ALL {
5588                    assert_eq!(
5589                        b.find_precondition_kind(query).map(|c| c.kind),
5590                        b.iter_precondition_kind(query).next().map(|c| c.kind),
5591                        "precondition find/iter bridge drifted: \
5592                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5593                    );
5594                    assert_eq!(
5595                        b.find_postcondition_kind(query).map(|c| c.kind),
5596                        b.iter_postcondition_kind(query).next().map(|c| c.kind),
5597                        "postcondition find/iter bridge drifted: \
5598                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5599                    );
5600                    assert_eq!(
5601                        b.find_condition_kind(query).map(|c| c.kind),
5602                        b.iter_condition_kind(query).next().map(|c| c.kind),
5603                        "union find/iter bridge drifted: \
5604                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5605                    );
5606                }
5607            }
5608        }
5609    }
5610
5611    /// PRECONDITION-PRECEDENCE pin (iter) — a kind authored on BOTH
5612    /// sides yields precondition-side matches FIRST in the union
5613    /// chain. Uses params-distinguishable [`Condition`]s so a
5614    /// regression that (a) reversed the chain order on the widened
5615    /// axis (postcondition first), (b) interleaved the two sides,
5616    /// or (c) collapsed the chain to a `.zip(...)` fails at the
5617    /// returned params-payload sequence rather than silently at the
5618    /// count.
5619    #[test]
5620    fn iter_condition_kind_yields_preconditions_before_postconditions_on_dual_populated() {
5621        let mut b = Boundary::default();
5622        b.preconditions.push(Condition {
5623            kind: ConditionKind::ClosedLoopAuth,
5624            params: json!({ "side": "pre-1" }),
5625        });
5626        b.preconditions.push(Condition {
5627            kind: ConditionKind::ClosedLoopAuth,
5628            params: json!({ "side": "pre-2" }),
5629        });
5630        b.postconditions.push(Condition {
5631            kind: ConditionKind::ClosedLoopAuth,
5632            params: json!({ "side": "post-1" }),
5633        });
5634        let sides: Vec<_> = b
5635            .iter_condition_kind(ConditionKind::ClosedLoopAuth)
5636            .map(|c| {
5637                c.params
5638                    .get("side")
5639                    .and_then(serde_json::Value::as_str)
5640                    .unwrap_or_default()
5641                    .to_owned()
5642            })
5643            .collect();
5644        assert_eq!(
5645            sides,
5646            vec!["pre-1".to_owned(), "pre-2".to_owned(), "post-1".to_owned(),],
5647            "iter_condition_kind must yield every precondition-side match before any \
5648             postcondition-side match (chain order pinned by two-surface parity contract)",
5649        );
5650    }
5651
5652    // ----- count_kind — scalar cardinality refinement --------------------
5653    //
5654    // The `count_kind` fourth refinement collapses the widened
5655    // `iter_kind` stream to its cardinality without materializing an
5656    // intermediate `Vec` or `Option`. Distinct composition law from the
5657    // three prior refinements: `count_condition_kind` SUMS pre + post
5658    // (rather than OR-ing them via `has`, or_else-ing them via `find`,
5659    // or Chain-ing them via `iter`). The tests below pin (a) the default
5660    // trait body against the primitive `iter_kind(k).count()`, (b) the
5661    // slice-level composition laws `has_kind(k) == (count_kind(k) > 0)`
5662    // and `find_kind(k).is_some() == (count_kind(k) > 0)`, (c) the
5663    // struct-level SUM composition on both `Boundary` half-slice arms,
5664    // and (d) the two-surface parity contract with
5665    // `EphemeralSpec::count_(pre|post|)condition_kind` (in ephemeral.rs).
5666
5667    /// EMPTY-SLICE pin (count) — an empty `&[Condition]` returns `0`
5668    /// from `count_kind` for EVERY [`ConditionKind`]. Sweep
5669    /// `ConditionKind::ALL` so a new variant added without a matching
5670    /// arm surfaces at rustc's exhaustiveness gate on the ALL literal
5671    /// rather than as silent phantom-cardinality at every downstream
5672    /// count callsite.
5673    #[test]
5674    fn condition_slice_count_kind_returns_zero_on_empty_slice_for_every_kind() {
5675        let empty: &[Condition] = &[];
5676        for kind in ConditionKind::ALL {
5677            assert_eq!(
5678                empty.count_kind(kind),
5679                0,
5680                "empty slice must count 0 for {kind:?}",
5681            );
5682        }
5683    }
5684
5685    /// PER-VARIANT pin (count) — a single-element slice returns `1`
5686    /// on the matching kind and `0` on every other kind. Sweep ALL ×
5687    /// ALL so a regression that (a) hard-coded the filter predicate
5688    /// to a single kind (silently counting every populated slice
5689    /// regardless of query), or (b) matched on [`Condition::params`]
5690    /// instead of [`Condition::kind`] fails HERE at the substrate
5691    /// primitive.
5692    #[test]
5693    fn condition_slice_count_kind_reads_kind_field_per_variant() {
5694        for populated in ConditionKind::ALL {
5695            let slice = [condition_with(populated)];
5696            for query in ConditionKind::ALL {
5697                let expected = if query == populated { 1 } else { 0 };
5698                assert_eq!(
5699                    slice.count_kind(query),
5700                    expected,
5701                    "populated={populated:?} query={query:?} \
5702                     must count {expected}",
5703                );
5704            }
5705        }
5706    }
5707
5708    /// DUPLICATES pin (count) — a slice with the same kind at
5709    /// MULTIPLE positions returns the exact match count (not `1`, not
5710    /// a de-duplicated `1`). A regression that (a) short-circuited on
5711    /// the first match (an `.iter().find(...)` yielding `0`/`1` sugar
5712    /// on the count arm), or (b) de-duplicated by kind (an erroneous
5713    /// `HashSet::insert`-gated walk that swallowed repeats) surfaces
5714    /// HERE at the cardinality boundary rather than silently at a
5715    /// downstream count-based coherence check.
5716    #[test]
5717    fn condition_slice_count_kind_counts_every_match_on_duplicates() {
5718        let slice = [
5719            Condition {
5720                kind: ConditionKind::ClosedLoopAuth,
5721                params: json!({ "probeImage": "first" }),
5722            },
5723            Condition {
5724                kind: ConditionKind::PromQL,
5725                params: json!({ "query": "up" }),
5726            },
5727            Condition {
5728                kind: ConditionKind::ClosedLoopAuth,
5729                params: json!({ "probeImage": "second" }),
5730            },
5731        ];
5732        assert_eq!(slice.count_kind(ConditionKind::ClosedLoopAuth), 2);
5733        assert_eq!(slice.count_kind(ConditionKind::PromQL), 1);
5734        for kind in ConditionKind::ALL {
5735            if matches!(kind, ConditionKind::ClosedLoopAuth | ConditionKind::PromQL) {
5736                continue;
5737            }
5738            assert_eq!(
5739                slice.count_kind(kind),
5740                0,
5741                "non-populated kind {kind:?} must count 0",
5742            );
5743        }
5744    }
5745
5746    /// SLICE-LEVEL DELEGATION pin (count ↔ iter) — the trait's
5747    /// default `count_kind` body equals `iter_kind(k).count()` at
5748    /// EVERY (populated arrangement, query) pair on
5749    /// `ConditionKind::ALL`. Turns the trait doc's composition-law
5750    /// note (`count_kind(k) == iter_kind(k).count()` by construction)
5751    /// into a first-class typed invariant: a future implementor that
5752    /// overrode the default `count_kind` body with a divergent walk
5753    /// shape (a stored-length cache that drifted, a `.step_by(2)`
5754    /// artefact from a copy-paste of `iter_kind`) surfaces HERE.
5755    #[test]
5756    fn condition_slice_count_kind_equals_iter_kind_count() {
5757        for pre_kind in ConditionKind::ALL {
5758            for post_kind in ConditionKind::ALL {
5759                let slice = [condition_with(pre_kind), condition_with(post_kind)];
5760                for query in ConditionKind::ALL {
5761                    assert_eq!(
5762                        slice.count_kind(query),
5763                        slice.iter_kind(query).count(),
5764                        "count/iter bridge drifted: pre={pre_kind:?} \
5765                         post={post_kind:?} query={query:?}",
5766                    );
5767                }
5768            }
5769        }
5770    }
5771
5772    /// SLICE-LEVEL DELEGATION pin (count ↔ has ↔ find) — the two
5773    /// composition laws
5774    /// `has_kind(k) == (count_kind(k) > 0)` and
5775    /// `find_kind(k).is_some() == (count_kind(k) > 0)`
5776    /// hold at every (populated, populated, query) triple on
5777    /// `ConditionKind::ALL`. Sweeps both refinement bridges at ONE
5778    /// site so a regression at the count primitive that drifted from
5779    /// the presence bit or the first-match probe surfaces HERE.
5780    #[test]
5781    fn condition_slice_has_and_find_equal_count_greater_than_zero() {
5782        for pre_kind in ConditionKind::ALL {
5783            for post_kind in ConditionKind::ALL {
5784                let slice = [condition_with(pre_kind), condition_with(post_kind)];
5785                for query in ConditionKind::ALL {
5786                    let count = slice.count_kind(query);
5787                    assert_eq!(
5788                        slice.has_kind(query),
5789                        count > 0,
5790                        "has/count bridge drifted: pre={pre_kind:?} \
5791                         post={post_kind:?} query={query:?}",
5792                    );
5793                    assert_eq!(
5794                        slice.find_kind(query).is_some(),
5795                        count > 0,
5796                        "find/count bridge drifted: pre={pre_kind:?} \
5797                         post={post_kind:?} query={query:?}",
5798                    );
5799                }
5800            }
5801        }
5802    }
5803
5804    /// SUBSTRATE-DELEGATION pin (Boundary count-triad) — the three
5805    /// widened `count_*_kind` methods on [`Boundary`] delegate
5806    /// verbatim to [`ConditionSliceExt::count_kind`] on the
5807    /// underlying [`Vec<Condition>`] slices. The
5808    /// `count_condition_kind` union SUMS preconditions and
5809    /// postconditions (distinct from the `iter_condition_kind`
5810    /// [`Chain`](std::iter::Chain), `find_condition_kind`
5811    /// [`Option::or_else`], and `has_condition_kind` `||`
5812    /// compositions on the same axis). Sweep `ConditionKind::ALL ×
5813    /// ConditionKind::ALL × ConditionKind::ALL` so a regression that
5814    /// (a) inlined a divergent count at either half-slice arm, (b)
5815    /// subtracted rather than summed, or (c) collapsed the sum to
5816    /// [`std::cmp::max`] (silently narrowing the union to a max-per-
5817    /// side probe) surfaces HERE at the substrate boundary.
5818    #[test]
5819    fn boundary_count_condition_kind_triad_delegates_and_sums_slice_count_kind() {
5820        for pre_kind in ConditionKind::ALL {
5821            for post_kind in ConditionKind::ALL {
5822                let mut b = Boundary::default();
5823                b.preconditions.push(condition_with(pre_kind));
5824                b.postconditions.push(condition_with(post_kind));
5825                for query in ConditionKind::ALL {
5826                    let via_pre = b.preconditions.count_kind(query);
5827                    let via_post = b.postconditions.count_kind(query);
5828                    assert_eq!(
5829                        b.count_precondition_kind(query),
5830                        via_pre,
5831                        "boundary precondition count arm must delegate: \
5832                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5833                    );
5834                    assert_eq!(
5835                        b.count_postcondition_kind(query),
5836                        via_post,
5837                        "boundary postcondition count arm must delegate: \
5838                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5839                    );
5840                    assert_eq!(
5841                        b.count_condition_kind(query),
5842                        via_pre + via_post,
5843                        "boundary union count arm must SUM pre + post: \
5844                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5845                    );
5846                }
5847            }
5848        }
5849    }
5850
5851    /// STRUCT-LEVEL DELEGATION pin (count ↔ iter on Boundary) — the
5852    /// three [`Boundary`] `count_*_kind` arms equal their widened
5853    /// peers' `.count()` projection at EVERY (pre-populated, post-
5854    /// populated, query) triple on `ConditionKind::ALL`. Re-anchors
5855    /// the composition-law pin
5856    /// `count_condition_kind == iter_condition_kind.count()` through
5857    /// the cardinality axis on the parent surface — a future consumer
5858    /// that reads `count_condition_kind(k)` as sugar for
5859    /// `iter_condition_kind(k).count()` stays typed against the SAME
5860    /// truth table on both the slice-level and struct-level layers.
5861    /// Also pins the sum-composition round-trip through the widened
5862    /// stream: the union arm's SUM equals the chained stream's count.
5863    #[test]
5864    fn boundary_count_triad_equals_iter_triad_count_projection() {
5865        for pre_kind in ConditionKind::ALL {
5866            for post_kind in ConditionKind::ALL {
5867                let mut b = Boundary::default();
5868                b.preconditions.push(condition_with(pre_kind));
5869                b.preconditions.push(condition_with(pre_kind));
5870                b.postconditions.push(condition_with(post_kind));
5871                for query in ConditionKind::ALL {
5872                    assert_eq!(
5873                        b.count_precondition_kind(query),
5874                        b.iter_precondition_kind(query).count(),
5875                        "precondition count/iter bridge drifted: \
5876                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5877                    );
5878                    assert_eq!(
5879                        b.count_postcondition_kind(query),
5880                        b.iter_postcondition_kind(query).count(),
5881                        "postcondition count/iter bridge drifted: \
5882                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5883                    );
5884                    assert_eq!(
5885                        b.count_condition_kind(query),
5886                        b.iter_condition_kind(query).count(),
5887                        "union count/iter bridge drifted: \
5888                         pre={pre_kind:?} post={post_kind:?} query={query:?}",
5889                    );
5890                }
5891            }
5892        }
5893    }
5894
5895    // ── ConditionSliceExt::distinct_kinds — closed-set-inversion axis ──
5896    //
5897    // The fifth refinement on the slice-level presence-probe algebra
5898    // inverts the axis: the four point-probe refinements (has, find,
5899    // iter, count) fix a [`ConditionKind`] and vary the return type;
5900    // `distinct_kinds` fixes the slice and varies over
5901    // [`ConditionKind::ALL`], returning the SET of present kinds
5902    // projected in [`ConditionKind::ALL`] order with no duplicates.
5903    // The composition-law arms in `assert_slice_refinement_composition_laws`
5904    // pin the fifth refinement against `has_kind` per variant AND
5905    // against the canonical ALL-order equality; the four dedicated
5906    // behavior tests below pin the returned VALUE per authored
5907    // arrangement (empty, single-element populated, dual-populated,
5908    // duplicate-populated).
5909
5910    /// EMPTY-SLICE pin — an empty slice returns an empty `Vec` on
5911    /// `distinct_kinds`, distinct from every populated arrangement.
5912    /// Locks the zero-element identity so a regression that (a)
5913    /// returned `ConditionKind::ALL.to_vec()` (the wrong direction of
5914    /// the closed-set walk), (b) returned a placeholder `[ProcessPhase]`
5915    /// vec (a copy-paste of the first-variant default in a `impl
5916    /// Default` for a hypothetical `KindSet` wrapper) surfaces HERE.
5917    #[test]
5918    fn condition_slice_distinct_kinds_returns_empty_vec_on_empty_slice() {
5919        let empty: &[Condition] = &[];
5920        assert_eq!(
5921            empty.distinct_kinds(),
5922            Vec::<ConditionKind>::new(),
5923            "empty slice must return empty distinct-kinds vec",
5924        );
5925    }
5926
5927    /// PER-VARIANT pin — a slice with EXACTLY ONE `Condition` carrying
5928    /// the addressed kind returns `[kind]` — a single-element vec
5929    /// containing exactly that kind. Sweep `ConditionKind::ALL` so a
5930    /// new variant added without a matching arm in the closed-set walk
5931    /// surfaces at rustc's exhaustiveness gate on the ALL literal
5932    /// (arity forced by `[Self; 8]`) rather than as a silent false-
5933    /// negative at every downstream `distinct_condition_kinds`
5934    /// callsite. Locks the closed-set-inversion probe body against a
5935    /// regression that (a) always returned `[ProcessPhase]` regardless
5936    /// of the actual kind, (b) collapsed `distinct_kinds` to
5937    /// `iter_kind(<first ALL variant>).map(|c| c.kind).collect()`
5938    /// (silently filtering to only ProcessPhase matches).
5939    #[test]
5940    fn condition_slice_distinct_kinds_returns_single_element_vec_per_variant() {
5941        for populated in ConditionKind::ALL {
5942            let slice = [condition_with(populated)];
5943            assert_eq!(
5944                slice.distinct_kinds(),
5945                vec![populated],
5946                "single-populated slice must return exactly [{populated:?}] on distinct_kinds",
5947            );
5948        }
5949    }
5950
5951    /// DEDUP pin — a slice with the SAME kind at multiple positions
5952    /// (three interleaved with distinct kinds) returns a distinct-set
5953    /// containing that kind exactly ONCE. The closed-set-inversion
5954    /// projection collapses multiplicity — a caller that needs the
5955    /// per-kind cardinality reaches for `count_kind`; this refinement
5956    /// returns the PRESENCE set. A regression that (a) omitted the
5957    /// dedup and returned `[ClosedLoopAuth, PromQL, ClosedLoopAuth,
5958    /// PromQL, ClosedLoopAuth]` (byte-identical to
5959    /// `slice.iter().map(|c| c.kind).collect()` — the wrong closed-
5960    /// set walk direction), (b) counted every duplicate as a distinct
5961    /// entry via a `.collect::<HashSet<_>>()` without canonicalizing
5962    /// order surfaces HERE.
5963    #[test]
5964    fn condition_slice_distinct_kinds_deduplicates_and_yields_canonical_all_order() {
5965        let interleaved = [
5966            Condition {
5967                kind: ConditionKind::ClosedLoopAuth,
5968                params: json!({ "probeImage": "first" }),
5969            },
5970            Condition {
5971                kind: ConditionKind::PromQL,
5972                params: json!({ "query": "up" }),
5973            },
5974            Condition {
5975                kind: ConditionKind::ClosedLoopAuth,
5976                params: json!({ "probeImage": "second" }),
5977            },
5978            Condition {
5979                kind: ConditionKind::PromQL,
5980                params: json!({ "query": "healthy" }),
5981            },
5982            Condition {
5983                kind: ConditionKind::ClosedLoopAuth,
5984                params: json!({ "probeImage": "third" }),
5985            },
5986        ];
5987        // Canonical ConditionKind::ALL order: PromQL is at position 3,
5988        // ClosedLoopAuth at position 7 in the ALL array. So PromQL comes
5989        // FIRST in the distinct-set even though ClosedLoopAuth appears
5990        // FIRST in the slice — the closed-set-inversion walk is
5991        // ordered by ConditionKind::ALL, not by slice-encounter order.
5992        assert_eq!(
5993            interleaved.distinct_kinds(),
5994            vec![ConditionKind::PromQL, ConditionKind::ClosedLoopAuth],
5995            "interleaved-duplicate slice must dedup AND order by ConditionKind::ALL, not by slice-encounter order",
5996        );
5997    }
5998
5999    /// FULL-COVERAGE pin — a slice that carries every [`ConditionKind`]
6000    /// variant returns `ConditionKind::ALL.to_vec()` on `distinct_kinds`.
6001    /// The closed-set-inversion probe covers the full closed set at ONE
6002    /// call site — a regression that missed one variant in the walk
6003    /// (skipping the FIRST or LAST `ALL` entry via a `[1..]` or
6004    /// `[..ALL.len() - 1]` slice bug in the closed-set walk) surfaces
6005    /// HERE.
6006    #[test]
6007    fn condition_slice_distinct_kinds_covers_full_closed_set_on_saturated_slice() {
6008        let saturated: Vec<Condition> =
6009            ConditionKind::ALL.into_iter().map(condition_with).collect();
6010        assert_eq!(
6011            saturated.as_slice().distinct_kinds(),
6012            ConditionKind::ALL.to_vec(),
6013            "slice containing every ConditionKind must return ConditionKind::ALL as its distinct-set",
6014        );
6015    }
6016
6017    // ── distinct_kind_count — slice-level scalar-cardinality pins ──────
6018    //
6019    // The trait-level scalar-cardinality projection of the closed-set-
6020    // inversion widened primitive: `distinct_kind_count()` collapses
6021    // `distinct_kinds()` to its cardinality without materializing the
6022    // intermediate `Vec<ConditionKind>`. Composition law
6023    // `distinct_kind_count() == distinct_kinds().len()` pinned as the
6024    // sixth arm of the substrate testkit primitive
6025    // [`assert_slice_refinement_composition_laws`].
6026
6027    /// ZERO-ELEMENT pin — an empty slice returns `0` on
6028    /// `distinct_kind_count`, byte-for-byte with `distinct_kinds().len()`
6029    /// on the same slice. Locks the zero-element identity so a
6030    /// regression that (a) returned `ConditionKind::ALL.len()` (the
6031    /// wrong direction of the closed-set walk — every kind counted
6032    /// regardless of presence), (b) returned a placeholder `1` (a
6033    /// copy-paste of a single-slot factory's cardinality), or (c) drifted
6034    /// off `distinct_kinds().len()` surfaces HERE.
6035    #[test]
6036    fn condition_slice_distinct_kind_count_returns_zero_on_empty_slice() {
6037        let empty: &[Condition] = &[];
6038        assert_eq!(
6039            empty.distinct_kind_count(),
6040            0,
6041            "empty slice must return 0 on distinct_kind_count",
6042        );
6043        assert_eq!(
6044            empty.distinct_kind_count(),
6045            empty.distinct_kinds().len(),
6046            "empty slice distinct_kind_count must equal distinct_kinds().len()",
6047        );
6048    }
6049
6050    /// PER-VARIANT pin — a slice with EXACTLY ONE `Condition` carrying
6051    /// the addressed kind returns `1` on `distinct_kind_count` — the
6052    /// single-slot diagonal cardinality. Sweep [`ConditionKind::ALL`]
6053    /// so a regression that (a) always returned `0` regardless of the
6054    /// actual kind, (b) always returned `ConditionKind::ALL.len()`
6055    /// (missed the `filter` step), or (c) collapsed the walk to a
6056    /// single fixed variant surfaces HERE.
6057    #[test]
6058    fn condition_slice_distinct_kind_count_returns_one_per_variant() {
6059        for populated in ConditionKind::ALL {
6060            let slice = [condition_with(populated)];
6061            assert_eq!(
6062                slice.distinct_kind_count(),
6063                1,
6064                "single-populated slice must return 1 on distinct_kind_count for {populated:?}",
6065            );
6066            assert_eq!(
6067                slice.distinct_kind_count(),
6068                slice.distinct_kinds().len(),
6069                "single-populated distinct_kind_count must equal distinct_kinds().len() for {populated:?}",
6070            );
6071        }
6072    }
6073
6074    /// DEDUP pin — a slice with the SAME kind at multiple positions
6075    /// (three interleaved with distinct kinds — two `PromQL`, three
6076    /// `ClosedLoopAuth`) returns `2` on `distinct_kind_count` (the
6077    /// scalar cardinality of the DISTINCT presence set, byte-for-byte
6078    /// with `distinct_kinds().len()` on the same slice). Locks the
6079    /// closed-set projection against a regression that (a) counted
6080    /// every occurrence (returning `5` — byte-identical to
6081    /// `slice.len()`), (b) omitted the dedup and returned `5` via
6082    /// `.iter().map(|c| c.kind).count()`.
6083    #[test]
6084    fn condition_slice_distinct_kind_count_dedups_across_duplicates() {
6085        let interleaved = [
6086            Condition {
6087                kind: ConditionKind::ClosedLoopAuth,
6088                params: json!({ "probeImage": "first" }),
6089            },
6090            Condition {
6091                kind: ConditionKind::PromQL,
6092                params: json!({ "query": "up" }),
6093            },
6094            Condition {
6095                kind: ConditionKind::ClosedLoopAuth,
6096                params: json!({ "probeImage": "second" }),
6097            },
6098            Condition {
6099                kind: ConditionKind::PromQL,
6100                params: json!({ "query": "healthy" }),
6101            },
6102            Condition {
6103                kind: ConditionKind::ClosedLoopAuth,
6104                params: json!({ "probeImage": "third" }),
6105            },
6106        ];
6107        assert_eq!(
6108            interleaved.distinct_kind_count(),
6109            2,
6110            "interleaved-duplicate slice must return 2 on distinct_kind_count (PromQL + ClosedLoopAuth)",
6111        );
6112        assert_eq!(
6113            interleaved.distinct_kind_count(),
6114            interleaved.distinct_kinds().len(),
6115            "interleaved-duplicate distinct_kind_count must equal distinct_kinds().len()",
6116        );
6117    }
6118
6119    /// FULL-COVERAGE pin — a slice that carries every [`ConditionKind`]
6120    /// variant returns `ConditionKind::ALL.len()` on `distinct_kind_count`.
6121    /// The scalar cardinality projection covers the full closed set at
6122    /// ONE call site — a regression that missed one variant in the walk
6123    /// (skipping the FIRST or LAST `ALL` entry via a `[1..]` or
6124    /// `[..ALL.len() - 1]` slice bug in the closed-set walk) surfaces
6125    /// HERE.
6126    #[test]
6127    fn condition_slice_distinct_kind_count_covers_full_closed_set_on_saturated_slice() {
6128        let saturated: Vec<Condition> =
6129            ConditionKind::ALL.into_iter().map(condition_with).collect();
6130        assert_eq!(
6131            saturated.as_slice().distinct_kind_count(),
6132            ConditionKind::ALL.len(),
6133            "slice containing every ConditionKind must return ConditionKind::ALL.len() on distinct_kind_count",
6134        );
6135        assert_eq!(
6136            saturated.as_slice().distinct_kind_count(),
6137            saturated.as_slice().distinct_kinds().len(),
6138            "saturated distinct_kind_count must equal distinct_kinds().len()",
6139        );
6140    }
6141
6142    // ── ConditionSliceExt::missing_kinds — closed-set-complement axis ──
6143    //
6144    // The complement peer of `distinct_kinds` on the closed-set-
6145    // inversion axis: `missing_kinds` returns the SET of kinds that
6146    // do NOT appear in the slice, in canonical [`ConditionKind::ALL`]
6147    // order. The four tests below pin each authored arrangement's
6148    // returned VALUE (empty, single-populated, saturated, interleaved-
6149    // duplicate); the composition-law arms in
6150    // `assert_slice_refinement_composition_laws` pin the closed-set-
6151    // partition invariants against `distinct_kinds` and `has_kind`.
6152
6153    /// EMPTY-SLICE pin — an empty slice returns
6154    /// `ConditionKind::ALL.to_vec()` on `missing_kinds` (every kind is
6155    /// missing). Locks the maximum-cardinality identity on the
6156    /// complement side, byte-for-byte dual to the empty-slice arm of
6157    /// `distinct_kinds` (which returns an empty vec). A regression that
6158    /// returned an empty vec (forgot the negation) or a placeholder
6159    /// `[ProcessPhase]` (a copy-paste of the first-variant default)
6160    /// surfaces HERE.
6161    #[test]
6162    fn condition_slice_missing_kinds_returns_full_closed_set_on_empty_slice() {
6163        let empty: &[Condition] = &[];
6164        assert_eq!(
6165            empty.missing_kinds(),
6166            ConditionKind::ALL.to_vec(),
6167            "empty slice must return ConditionKind::ALL on missing_kinds (every kind is missing)",
6168        );
6169    }
6170
6171    /// PER-VARIANT pin — a slice with EXACTLY ONE `Condition` carrying
6172    /// the addressed kind returns `ConditionKind::ALL` MINUS that kind
6173    /// on `missing_kinds`. Sweep [`ConditionKind::ALL`] so a regression
6174    /// that (a) returned an empty vec regardless of the kind, (b)
6175    /// returned the full ALL vec (forgot to filter), or (c) inverted
6176    /// the negation and returned only the addressed kind surfaces HERE.
6177    #[test]
6178    fn condition_slice_missing_kinds_returns_all_minus_populated_kind() {
6179        for populated in ConditionKind::ALL {
6180            let slice = [condition_with(populated)];
6181            let expected: Vec<_> = ConditionKind::ALL
6182                .into_iter()
6183                .filter(|k| *k != populated)
6184                .collect();
6185            assert_eq!(
6186                slice.missing_kinds(),
6187                expected,
6188                "single-populated slice must return ConditionKind::ALL minus {populated:?} on missing_kinds",
6189            );
6190        }
6191    }
6192
6193    /// FULL-COVERAGE pin — a slice that carries every [`ConditionKind`]
6194    /// variant returns an empty vec on `missing_kinds` (no kind is
6195    /// missing). Dual of the empty-slice arm above; a regression that
6196    /// returned the full ALL vec regardless of population or inverted
6197    /// the presence direction surfaces HERE.
6198    #[test]
6199    fn condition_slice_missing_kinds_returns_empty_vec_on_saturated_slice() {
6200        let saturated: Vec<Condition> =
6201            ConditionKind::ALL.into_iter().map(condition_with).collect();
6202        assert_eq!(
6203            saturated.as_slice().missing_kinds(),
6204            Vec::<ConditionKind>::new(),
6205            "slice containing every ConditionKind must return empty vec on missing_kinds",
6206        );
6207    }
6208
6209    /// DEDUP pin — a slice with the SAME kind at multiple positions
6210    /// (three ClosedLoopAuth, two PromQL, none of the other six)
6211    /// returns those SIX absent kinds on `missing_kinds`, in canonical
6212    /// [`ConditionKind::ALL`] order — multiplicity on the present side
6213    /// is irrelevant to the complement. A regression that (a) counted
6214    /// duplicates as decreasing the missing set (a `saturating_sub`
6215    /// bug in a cardinality-tracking override), (b) yielded the
6216    /// missing set in slice-encounter order (which is undefined when
6217    /// no positions carry the missing kind — a subtle failure mode
6218    /// that must yield the ALL-ordered subsequence regardless)
6219    /// surfaces HERE.
6220    #[test]
6221    fn condition_slice_missing_kinds_yields_canonical_all_order_on_duplicates() {
6222        let interleaved = [
6223            Condition {
6224                kind: ConditionKind::ClosedLoopAuth,
6225                params: json!({ "probeImage": "first" }),
6226            },
6227            Condition {
6228                kind: ConditionKind::PromQL,
6229                params: json!({ "query": "up" }),
6230            },
6231            Condition {
6232                kind: ConditionKind::ClosedLoopAuth,
6233                params: json!({ "probeImage": "second" }),
6234            },
6235            Condition {
6236                kind: ConditionKind::PromQL,
6237                params: json!({ "query": "healthy" }),
6238            },
6239            Condition {
6240                kind: ConditionKind::ClosedLoopAuth,
6241                params: json!({ "probeImage": "third" }),
6242            },
6243        ];
6244        let expected: Vec<_> = ConditionKind::ALL
6245            .into_iter()
6246            .filter(|k| *k != ConditionKind::PromQL && *k != ConditionKind::ClosedLoopAuth)
6247            .collect();
6248        assert_eq!(
6249            interleaved.missing_kinds(),
6250            expected,
6251            "interleaved-duplicate slice must return canonical ALL-ordered complement of {{PromQL, ClosedLoopAuth}}",
6252        );
6253    }
6254
6255    // ── ConditionSliceExt::missing_kind_count — scalar cardinality pins ─
6256    //
6257    // Scalar-cardinality peer of the closed-set-complement widened
6258    // primitive `missing_kinds`: `missing_kind_count()` collapses the
6259    // set to its cardinality without allocating. The composition law
6260    // `missing_kind_count() == missing_kinds().len()` is pinned as the
6261    // scalar-cardinality-complement arm of
6262    // `assert_slice_refinement_composition_laws`. The three tests below
6263    // pin each authored arrangement's returned VALUE (empty, single-
6264    // populated, saturated) directly against `missing_kinds().len()`.
6265
6266    /// EMPTY-SLICE pin — an empty slice returns
6267    /// `ConditionKind::ALL.len()` on `missing_kind_count`, byte-for-byte
6268    /// with `missing_kinds().len()`. Locks the maximum-cardinality
6269    /// identity on the complement side; dual of the empty-slice arm on
6270    /// `distinct_kind_count` which returns `0`. A regression that
6271    /// forgot the negation, returned `0` (the distinct-kind-count
6272    /// identity on empty), or returned the wrong constant surfaces
6273    /// HERE.
6274    #[test]
6275    fn condition_slice_missing_kind_count_returns_full_closed_set_on_empty_slice() {
6276        let empty: &[Condition] = &[];
6277        assert_eq!(
6278            empty.missing_kind_count(),
6279            ConditionKind::ALL.len(),
6280            "empty slice must return ConditionKind::ALL.len() on missing_kind_count",
6281        );
6282        assert_eq!(
6283            empty.missing_kind_count(),
6284            empty.missing_kinds().len(),
6285            "empty slice missing_kind_count must equal missing_kinds().len()",
6286        );
6287    }
6288
6289    /// PER-VARIANT pin — a slice with EXACTLY ONE `Condition` carrying
6290    /// the addressed kind returns `ConditionKind::ALL.len() - 1` on
6291    /// `missing_kind_count` (every OTHER kind is missing). Sweep
6292    /// [`ConditionKind::ALL`] so a regression that returned `0` (forgot
6293    /// to negate), `ConditionKind::ALL.len()` (forgot the populated
6294    /// kind), or a per-kind constant surfaces HERE.
6295    #[test]
6296    fn condition_slice_missing_kind_count_returns_all_minus_one_per_variant() {
6297        for populated in ConditionKind::ALL {
6298            let slice = [condition_with(populated)];
6299            assert_eq!(
6300                slice.missing_kind_count(),
6301                ConditionKind::ALL.len() - 1,
6302                "single-populated slice must return ConditionKind::ALL.len() - 1 on missing_kind_count for {populated:?}",
6303            );
6304            assert_eq!(
6305                slice.missing_kind_count(),
6306                slice.missing_kinds().len(),
6307                "single-populated missing_kind_count must equal missing_kinds().len() for {populated:?}",
6308            );
6309        }
6310    }
6311
6312    /// FULL-COVERAGE pin — a slice that carries every [`ConditionKind`]
6313    /// variant returns `0` on `missing_kind_count` (no kind is missing).
6314    /// Dual of the empty-slice arm above; a regression that returned
6315    /// `ConditionKind::ALL.len()` regardless of population or inverted
6316    /// the presence direction surfaces HERE.
6317    #[test]
6318    fn condition_slice_missing_kind_count_returns_zero_on_saturated_slice() {
6319        let saturated: Vec<Condition> =
6320            ConditionKind::ALL.into_iter().map(condition_with).collect();
6321        assert_eq!(
6322            saturated.as_slice().missing_kind_count(),
6323            0,
6324            "slice containing every ConditionKind must return 0 on missing_kind_count",
6325        );
6326        assert_eq!(
6327            saturated.as_slice().missing_kind_count(),
6328            saturated.as_slice().missing_kinds().len(),
6329            "saturated missing_kind_count must equal missing_kinds().len()",
6330        );
6331    }
6332
6333    // ── ConditionSliceExt::is_kind_saturated — Boolean saturation pins ─
6334    //
6335    // Short-circuiting Boolean saturation-endpoint peer of the closed-set-
6336    // complement widened + scalar primitives: `is_kind_saturated()`
6337    // returns `true` iff every ConditionKind::ALL variant appears at
6338    // least once in the slice, WITHOUT allocating `missing_kinds` or
6339    // walking every entry to build `missing_kind_count`. The composition
6340    // laws `is_kind_saturated() == (missing_kind_count() == 0)` and
6341    // `is_kind_saturated() == missing_kinds().is_empty()` are pinned as
6342    // the saturation-endpoint arm of
6343    // `assert_slice_refinement_composition_laws`. Byte-for-byte peer of
6344    // `crate::tagged_union::TaggedUnion::is_saturated` one struct-layer
6345    // up under the SAME `<CLOSED_SET>::ALL.iter().all(has)` short-
6346    // circuit walk shape.
6347
6348    /// EMPTY-SLICE pin — an empty slice returns `false` on
6349    /// `is_kind_saturated` (every kind is missing).
6350    #[test]
6351    fn condition_slice_is_kind_saturated_returns_false_on_empty_slice() {
6352        let empty: &[Condition] = &[];
6353        assert!(
6354            !empty.is_kind_saturated(),
6355            "empty slice must return false on is_kind_saturated",
6356        );
6357        assert_eq!(
6358            empty.is_kind_saturated(),
6359            empty.missing_kind_count() == 0,
6360            "empty is_kind_saturated must equal (missing_kind_count() == 0)",
6361        );
6362    }
6363
6364    /// SINGLE-KIND pin — a slice populating exactly one variant returns
6365    /// `false` on any [`ConditionKind::ALL`] closed set with `N ≥ 2`
6366    /// (the other `N - 1` variants are missing).
6367    #[test]
6368    fn condition_slice_is_kind_saturated_returns_false_on_single_kind_slice() {
6369        assert!(
6370            ConditionKind::ALL.len() >= 2,
6371            "test assumes ConditionKind::ALL has ≥ 2 variants",
6372        );
6373        for populated in ConditionKind::ALL {
6374            let slice = [condition_with(populated)];
6375            assert!(
6376                !slice.is_kind_saturated(),
6377                "single-populated slice with {populated:?} must return false on is_kind_saturated",
6378            );
6379            assert_eq!(
6380                slice.is_kind_saturated(),
6381                slice.missing_kind_count() == 0,
6382                "single-populated is_kind_saturated must equal (missing_kind_count() == 0) for {populated:?}",
6383            );
6384        }
6385    }
6386
6387    /// FULL-COVERAGE pin — a slice that carries every [`ConditionKind`]
6388    /// variant returns `true` on `is_kind_saturated` — the SOLE arm
6389    /// where the primitive returns `true`.
6390    #[test]
6391    fn condition_slice_is_kind_saturated_returns_true_on_saturated_slice() {
6392        let saturated: Vec<Condition> =
6393            ConditionKind::ALL.into_iter().map(condition_with).collect();
6394        assert!(
6395            saturated.as_slice().is_kind_saturated(),
6396            "slice containing every ConditionKind must return true on is_kind_saturated",
6397        );
6398        assert_eq!(
6399            saturated.as_slice().is_kind_saturated(),
6400            saturated.as_slice().missing_kind_count() == 0,
6401            "saturated is_kind_saturated must equal (missing_kind_count() == 0)",
6402        );
6403        assert_eq!(
6404            saturated.as_slice().is_kind_saturated(),
6405            saturated.as_slice().missing_kinds().is_empty(),
6406            "saturated is_kind_saturated must equal missing_kinds().is_empty()",
6407        );
6408    }
6409
6410    /// DUPLICATE-COVERAGE pin — a slice that carries every
6411    /// [`ConditionKind`] variant multiple times still returns `true`
6412    /// (multiplicity is irrelevant to the saturation predicate on the
6413    /// closed-set-inversion axis).
6414    #[test]
6415    fn condition_slice_is_kind_saturated_ignores_multiplicity() {
6416        let mut doubled: Vec<Condition> = Vec::new();
6417        for k in ConditionKind::ALL {
6418            doubled.push(condition_with(k));
6419            doubled.push(condition_with(k));
6420        }
6421        assert!(
6422            doubled.as_slice().is_kind_saturated(),
6423            "slice carrying every ConditionKind twice must return true on is_kind_saturated",
6424        );
6425    }
6426
6427    // ── ConditionSliceExt::has_any_missing_kind — at-least-one halfspace pins ──
6428    //
6429    // Boolean at-least-one halfspace peer of `is_kind_saturated`:
6430    // `has_any_missing_kind()` returns `true` iff AT LEAST ONE
6431    // `ConditionKind::ALL` variant appears zero times in the slice,
6432    // byte-for-byte with `!is_kind_saturated()` via the definitional
6433    // negation in the trait's default body. The composition laws
6434    // `has_any_missing_kind() == !is_kind_saturated()`,
6435    // `has_any_missing_kind() == (missing_kind_count() > 0)`, and
6436    // `has_any_missing_kind() == !missing_kinds().is_empty()` are
6437    // pinned as the at-least-one halfspace arm of
6438    // `assert_slice_refinement_composition_laws`. Byte-for-byte peer
6439    // of `crate::tagged_union::TaggedUnion::has_any_missing_kind` one
6440    // struct-layer up under the SAME `!is_saturated` definitional
6441    // negation shape.
6442
6443    /// EMPTY-SLICE pin — an empty slice returns `true` on
6444    /// `has_any_missing_kind` (every kind is missing, so at least one
6445    /// is). Dual of the empty-slice arm on `is_kind_saturated` (which
6446    /// returns `false`).
6447    #[test]
6448    fn condition_slice_has_any_missing_kind_returns_true_on_empty_slice() {
6449        let empty: &[Condition] = &[];
6450        assert!(
6451            empty.has_any_missing_kind(),
6452            "empty slice must return true on has_any_missing_kind",
6453        );
6454        assert_eq!(
6455            empty.has_any_missing_kind(),
6456            !empty.is_kind_saturated(),
6457            "empty has_any_missing_kind must equal !is_kind_saturated()",
6458        );
6459        assert_eq!(
6460            empty.has_any_missing_kind(),
6461            empty.missing_kind_count() > 0,
6462            "empty has_any_missing_kind must equal (missing_kind_count() > 0)",
6463        );
6464    }
6465
6466    /// SINGLE-KIND pin — a slice populating exactly one variant
6467    /// returns `true` on any `ConditionKind::ALL` closed set with
6468    /// `N ≥ 2` (the other `N - 1` variants are missing).
6469    #[test]
6470    fn condition_slice_has_any_missing_kind_returns_true_on_single_kind_slice() {
6471        assert!(
6472            ConditionKind::ALL.len() >= 2,
6473            "test assumes ConditionKind::ALL has ≥ 2 variants",
6474        );
6475        for populated in ConditionKind::ALL {
6476            let slice = [condition_with(populated)];
6477            assert!(
6478                slice.has_any_missing_kind(),
6479                "single-populated slice with {populated:?} must return true on has_any_missing_kind",
6480            );
6481            assert_eq!(
6482                slice.has_any_missing_kind(),
6483                !slice.is_kind_saturated(),
6484                "single-populated has_any_missing_kind must equal !is_kind_saturated() for {populated:?}",
6485            );
6486        }
6487    }
6488
6489    /// FULL-COVERAGE pin — a slice that carries every
6490    /// [`ConditionKind`] variant returns `false` on
6491    /// `has_any_missing_kind` — the SOLE arm where the primitive
6492    /// returns `false`, byte-for-byte peer of the SOLE arm on which
6493    /// `is_kind_saturated` returns `true`.
6494    #[test]
6495    fn condition_slice_has_any_missing_kind_returns_false_on_saturated_slice() {
6496        let saturated: Vec<Condition> =
6497            ConditionKind::ALL.into_iter().map(condition_with).collect();
6498        assert!(
6499            !saturated.as_slice().has_any_missing_kind(),
6500            "slice containing every ConditionKind must return false on has_any_missing_kind",
6501        );
6502        assert_eq!(
6503            saturated.as_slice().has_any_missing_kind(),
6504            !saturated.as_slice().is_kind_saturated(),
6505            "saturated has_any_missing_kind must equal !is_kind_saturated()",
6506        );
6507        assert_eq!(
6508            saturated.as_slice().has_any_missing_kind(),
6509            !saturated.as_slice().missing_kinds().is_empty(),
6510            "saturated has_any_missing_kind must equal !missing_kinds().is_empty()",
6511        );
6512    }
6513
6514    /// DUPLICATE-COVERAGE pin — a slice that carries every
6515    /// [`ConditionKind`] variant multiple times still returns `false`
6516    /// (multiplicity is irrelevant to the at-least-one halfspace
6517    /// predicate on the closed-set-complement axis, byte-for-byte peer
6518    /// of the saturation-predicate arm).
6519    #[test]
6520    fn condition_slice_has_any_missing_kind_ignores_multiplicity() {
6521        let mut doubled: Vec<Condition> = Vec::new();
6522        for k in ConditionKind::ALL {
6523            doubled.push(condition_with(k));
6524            doubled.push(condition_with(k));
6525        }
6526        assert!(
6527            !doubled.as_slice().has_any_missing_kind(),
6528            "slice carrying every ConditionKind twice must return false on has_any_missing_kind",
6529        );
6530    }
6531
6532    // ── ConditionSliceExt::has_unique_missing_kind — near-saturation-endpoint pins ─
6533    //
6534    // Boolean cardinality-mid-endpoint peer of `has_any_missing_kind`
6535    // on the closed-set-complement axis: `has_unique_missing_kind()`
6536    // returns `true` iff EXACTLY ONE ConditionKind::ALL variant
6537    // appears zero times in the slice. Default body is a two-step-
6538    // short-circuit walk over ConditionKind::ALL under a negated
6539    // `has_kind` predicate — pulls up to two hits off the filtered
6540    // iterator, returns `true` iff the first is Some and the second
6541    // is None. Short-circuits at the SECOND missing kind — strictly
6542    // cheaper than `missing_kind_count() == 1` (which walks every
6543    // slot) and `missing_kinds().len() == 1` (which allocates the
6544    // Vec) on every arm with ≥ 2 missing kinds. The composition laws
6545    // `has_unique_missing_kind() == (missing_kind_count() == 1)` and
6546    // `has_unique_missing_kind() == (missing_kinds().len() == 1)`
6547    // are pinned as the cardinality-mid-endpoint arm of
6548    // `assert_slice_refinement_composition_laws`. Byte-for-byte peer
6549    // of `crate::tagged_union::TaggedUnion::has_unique_missing_kind`
6550    // one struct-layer up under the SAME two-step short-circuit walk
6551    // shape.
6552
6553    /// EMPTY-SLICE pin — an empty slice returns `false` on
6554    /// `has_unique_missing_kind` on any `N ≥ 2` closed set (every
6555    /// kind is missing — the fully-missing endpoint, `N` missing not
6556    /// `1`).
6557    #[test]
6558    fn condition_slice_has_unique_missing_kind_returns_false_on_empty_slice() {
6559        assert!(
6560            ConditionKind::ALL.len() >= 2,
6561            "test assumes ConditionKind::ALL has ≥ 2 variants",
6562        );
6563        let empty: &[Condition] = &[];
6564        assert!(
6565            !empty.has_unique_missing_kind(),
6566            "empty slice must return false on has_unique_missing_kind (all N kinds missing, not exactly 1)",
6567        );
6568        assert_eq!(
6569            empty.has_unique_missing_kind(),
6570            empty.missing_kind_count() == 1,
6571            "empty has_unique_missing_kind must equal (missing_kind_count() == 1)",
6572        );
6573    }
6574
6575    /// SINGLE-KIND pin — a slice populating exactly one variant
6576    /// returns `false` on any `N ≥ 3` closed set (`N - 1 ≥ 2` kinds
6577    /// missing). On the degenerate `N == 2` closed set (which no
6578    /// production `ConditionKind` reaches; this workspace has
6579    /// `N == 8`) it would return `true`, so the pin gates on
6580    /// `N ≥ 3`.
6581    #[test]
6582    fn condition_slice_has_unique_missing_kind_returns_false_on_single_kind_slice() {
6583        if ConditionKind::ALL.len() < 3 {
6584            return;
6585        }
6586        for populated in ConditionKind::ALL {
6587            let slice = [condition_with(populated)];
6588            assert!(
6589                !slice.has_unique_missing_kind(),
6590                "single-populated slice with {populated:?} must return false on has_unique_missing_kind on N ≥ 3 closed sets ({} kinds missing, not exactly 1)",
6591                ConditionKind::ALL.len() - 1,
6592            );
6593            assert_eq!(
6594                slice.has_unique_missing_kind(),
6595                slice.missing_kind_count() == 1,
6596                "single-populated has_unique_missing_kind must equal (missing_kind_count() == 1) for {populated:?}",
6597            );
6598        }
6599    }
6600
6601    /// NEAR-SATURATION-ENDPOINT pin — a slice carrying every
6602    /// [`ConditionKind`] EXCEPT exactly one returns `true` on
6603    /// `has_unique_missing_kind`. Sweeps ConditionKind::ALL; each
6604    /// arrangement omits one variant and populates the other `N - 1`.
6605    /// This is the SOLE arrangement where the primitive returns
6606    /// `true`. Also pins the widened composition law
6607    /// `has_unique_missing_kind() == (missing_kinds().len() == 1)`.
6608    #[test]
6609    fn condition_slice_has_unique_missing_kind_returns_true_on_near_saturation_endpoint() {
6610        for omitted in ConditionKind::ALL {
6611            let near_saturated: Vec<Condition> = ConditionKind::ALL
6612                .into_iter()
6613                .filter(|k| *k != omitted)
6614                .map(condition_with)
6615                .collect();
6616            let slice = near_saturated.as_slice();
6617            assert!(
6618                slice.has_unique_missing_kind(),
6619                "near-saturation-endpoint slice (omitting {omitted:?}) must return true on has_unique_missing_kind",
6620            );
6621            assert_eq!(
6622                slice.has_unique_missing_kind(),
6623                slice.missing_kind_count() == 1,
6624                "near-saturation-endpoint has_unique_missing_kind must equal (missing_kind_count() == 1) for omitted={omitted:?}",
6625            );
6626            assert_eq!(
6627                slice.has_unique_missing_kind(),
6628                slice.missing_kinds().len() == 1,
6629                "near-saturation-endpoint has_unique_missing_kind must equal (missing_kinds().len() == 1) for omitted={omitted:?}",
6630            );
6631            assert_eq!(
6632                slice.first_missing_kind(),
6633                Some(omitted),
6634                "near-saturation-endpoint first_missing_kind must name the SOLE remaining hole for omitted={omitted:?}",
6635            );
6636        }
6637    }
6638
6639    /// SATURATED pin — a slice carrying every [`ConditionKind`]
6640    /// variant returns `false` on `has_unique_missing_kind` (zero
6641    /// missing, not exactly one). Dual of the SATURATED arm on
6642    /// `is_kind_saturated` which returns `true`. Also pins the
6643    /// composition law `has_unique_missing_kind() ==
6644    /// (missing_kind_count() == 1)` at zero-missing.
6645    #[test]
6646    fn condition_slice_has_unique_missing_kind_returns_false_on_saturated_slice() {
6647        let saturated: Vec<Condition> =
6648            ConditionKind::ALL.into_iter().map(condition_with).collect();
6649        assert!(
6650            !saturated.as_slice().has_unique_missing_kind(),
6651            "slice containing every ConditionKind must return false on has_unique_missing_kind (0 missing, not exactly 1)",
6652        );
6653        assert_eq!(
6654            saturated.as_slice().has_unique_missing_kind(),
6655            saturated.as_slice().missing_kind_count() == 1,
6656            "saturated has_unique_missing_kind must equal (missing_kind_count() == 1)",
6657        );
6658    }
6659
6660    /// TWO-MISSING pin — a slice populating exactly `N - 2` variants
6661    /// returns `false` on `has_unique_missing_kind` (2 missing, not
6662    /// exactly 1). Pins the SECOND-slot short-circuit boundary — a
6663    /// regression that dropped the second-slot check (returning `true`
6664    /// on any partial-populated arm) surfaces HERE. Only meaningful
6665    /// on `N ≥ 2` closed sets.
6666    #[test]
6667    fn condition_slice_has_unique_missing_kind_returns_false_on_two_missing_slice() {
6668        assert!(
6669            ConditionKind::ALL.len() >= 2,
6670            "test assumes ConditionKind::ALL has ≥ 2 variants",
6671        );
6672        for i in 0..ConditionKind::ALL.len() {
6673            for j in (i + 1)..ConditionKind::ALL.len() {
6674                let two_missing: Vec<Condition> = ConditionKind::ALL
6675                    .into_iter()
6676                    .enumerate()
6677                    .filter(|(k, _)| *k != i && *k != j)
6678                    .map(|(_, k)| condition_with(k))
6679                    .collect();
6680                let slice = two_missing.as_slice();
6681                assert!(
6682                    !slice.has_unique_missing_kind(),
6683                    "two-missing slice (omitting index {i} and {j}) must return false on has_unique_missing_kind (2 missing, not exactly 1)",
6684                );
6685                assert_eq!(
6686                    slice.has_unique_missing_kind(),
6687                    slice.missing_kind_count() == 1,
6688                    "two-missing has_unique_missing_kind must equal (missing_kind_count() == 1) for omitted=({i}, {j})",
6689                );
6690            }
6691        }
6692    }
6693
6694    /// MULTIPLICITY pin — a slice at the near-saturation-endpoint
6695    /// with each populated kind duplicated still returns `true`
6696    /// (multiplicity is irrelevant to the cardinality-mid-endpoint
6697    /// projection on the closed-set-complement axis, byte-for-byte
6698    /// peer of the saturation-predicate arm).
6699    #[test]
6700    fn condition_slice_has_unique_missing_kind_ignores_multiplicity() {
6701        for omitted in ConditionKind::ALL {
6702            let mut doubled: Vec<Condition> = Vec::new();
6703            for k in ConditionKind::ALL {
6704                if k != omitted {
6705                    doubled.push(condition_with(k));
6706                    doubled.push(condition_with(k));
6707                }
6708            }
6709            assert!(
6710                doubled.as_slice().has_unique_missing_kind(),
6711                "near-saturation-endpoint slice with each populated kind duplicated (omitting {omitted:?}) must return true on has_unique_missing_kind",
6712            );
6713        }
6714    }
6715
6716    // ── ConditionSliceExt::has_multiple_missing_kinds — many-arm pins ──
6717    //
6718    // Boolean cardinality "≥ 2" many-arm peer of
6719    // `has_unique_missing_kind` on the closed-set-complement axis:
6720    // `has_multiple_missing_kinds()` returns `true` iff AT LEAST TWO
6721    // `ConditionKind::ALL` variants appear zero times in the slice.
6722    // Third and final arm of the {0, 1, ≥2} trichotomy on the missing
6723    // axis at the slice level (0-arm: `is_kind_saturated`; 1-arm:
6724    // `has_unique_missing_kind`; ≥ 2-arm: this primitive). Body
6725    // short-circuits at the second missing kind — strictly cheaper
6726    // than `missing_kind_count() >= 2` (which walks every slot) and
6727    // `missing_kinds().len() >= 2` (which allocates the Vec) on every
6728    // arm with ≥ 2 missing kinds. The composition laws
6729    // `has_multiple_missing_kinds() == (missing_kind_count() >= 2)`
6730    // and `has_multiple_missing_kinds() == (missing_kinds().len() >= 2)`
6731    // are pinned as the cardinality-many-arm arm of
6732    // `assert_slice_refinement_composition_laws`. Byte-for-byte peer
6733    // of `crate::tagged_union::TaggedUnion::has_multiple_missing_kinds`
6734    // one struct-layer up under the SAME two-step short-circuit walk
6735    // shape.
6736
6737    /// EMPTY-SLICE pin — an empty slice returns `true` on
6738    /// `has_multiple_missing_kinds` on any `N ≥ 2` closed set (every
6739    /// kind is missing — the fully-missing endpoint, `N ≥ 2`
6740    /// missing).
6741    #[test]
6742    fn condition_slice_has_multiple_missing_kinds_returns_true_on_empty_slice() {
6743        assert!(
6744            ConditionKind::ALL.len() >= 2,
6745            "test assumes ConditionKind::ALL has ≥ 2 variants",
6746        );
6747        let empty: &[Condition] = &[];
6748        assert!(
6749            empty.has_multiple_missing_kinds(),
6750            "empty slice must return true on has_multiple_missing_kinds (all N ≥ 2 kinds missing)",
6751        );
6752        assert_eq!(
6753            empty.has_multiple_missing_kinds(),
6754            empty.missing_kind_count() >= 2,
6755            "empty has_multiple_missing_kinds must equal (missing_kind_count() >= 2)",
6756        );
6757    }
6758
6759    /// SINGLE-KIND pin — a slice populating exactly one variant
6760    /// returns `true` on any `N ≥ 3` closed set (`N - 1 ≥ 2` kinds
6761    /// missing). On the degenerate `N == 2` closed set (which no
6762    /// production `ConditionKind` reaches; this workspace has
6763    /// `N == 8`) it would return `false`, so the pin gates on
6764    /// `N ≥ 3`.
6765    #[test]
6766    fn condition_slice_has_multiple_missing_kinds_returns_true_on_single_kind_slice() {
6767        if ConditionKind::ALL.len() < 3 {
6768            return;
6769        }
6770        for populated in ConditionKind::ALL {
6771            let slice = [condition_with(populated)];
6772            assert!(
6773                slice.has_multiple_missing_kinds(),
6774                "single-populated slice with {populated:?} must return true on has_multiple_missing_kinds on N ≥ 3 closed sets ({} kinds missing, ≥ 2)",
6775                ConditionKind::ALL.len() - 1,
6776            );
6777            assert_eq!(
6778                slice.has_multiple_missing_kinds(),
6779                slice.missing_kind_count() >= 2,
6780                "single-populated has_multiple_missing_kinds must equal (missing_kind_count() >= 2) for {populated:?}",
6781            );
6782        }
6783    }
6784
6785    /// NEAR-SATURATION-ENDPOINT pin — a slice carrying every
6786    /// [`ConditionKind`] EXCEPT exactly one returns `false` on
6787    /// `has_multiple_missing_kinds` (exactly one missing, not ≥ 2).
6788    /// The SOLE-missing arrangement where the many-arm primitive
6789    /// returns `false` — the definitional boundary between the
6790    /// = 1 mid-endpoint and the ≥ 2 many-arm on the missing axis.
6791    /// Also pins the widened composition law
6792    /// `has_multiple_missing_kinds() == (missing_kinds().len() >= 2)`.
6793    #[test]
6794    fn condition_slice_has_multiple_missing_kinds_returns_false_on_near_saturation_endpoint() {
6795        for omitted in ConditionKind::ALL {
6796            let near_saturated: Vec<Condition> = ConditionKind::ALL
6797                .into_iter()
6798                .filter(|k| *k != omitted)
6799                .map(condition_with)
6800                .collect();
6801            let slice = near_saturated.as_slice();
6802            assert!(
6803                !slice.has_multiple_missing_kinds(),
6804                "near-saturation-endpoint slice (omitting {omitted:?}) must return false on has_multiple_missing_kinds (1 missing, not ≥ 2)",
6805            );
6806            assert_eq!(
6807                slice.has_multiple_missing_kinds(),
6808                slice.missing_kind_count() >= 2,
6809                "near-saturation-endpoint has_multiple_missing_kinds must equal (missing_kind_count() >= 2) for omitted={omitted:?}",
6810            );
6811            assert_eq!(
6812                slice.has_multiple_missing_kinds(),
6813                slice.missing_kinds().len() >= 2,
6814                "near-saturation-endpoint has_multiple_missing_kinds must equal (missing_kinds().len() >= 2) for omitted={omitted:?}",
6815            );
6816        }
6817    }
6818
6819    /// SATURATED pin — a slice carrying every [`ConditionKind`]
6820    /// variant returns `false` on `has_multiple_missing_kinds` (zero
6821    /// missing, not ≥ 2). Dual of the SATURATED arm on
6822    /// `is_kind_saturated` which returns `true`. Also pins the
6823    /// composition law `has_multiple_missing_kinds() ==
6824    /// (missing_kind_count() >= 2)` at zero-missing.
6825    #[test]
6826    fn condition_slice_has_multiple_missing_kinds_returns_false_on_saturated_slice() {
6827        let saturated: Vec<Condition> =
6828            ConditionKind::ALL.into_iter().map(condition_with).collect();
6829        assert!(
6830            !saturated.as_slice().has_multiple_missing_kinds(),
6831            "slice containing every ConditionKind must return false on has_multiple_missing_kinds (0 missing, not ≥ 2)",
6832        );
6833        assert_eq!(
6834            saturated.as_slice().has_multiple_missing_kinds(),
6835            saturated.as_slice().missing_kind_count() >= 2,
6836            "saturated has_multiple_missing_kinds must equal (missing_kind_count() >= 2)",
6837        );
6838    }
6839
6840    /// TWO-MISSING pin — a slice populating exactly `N - 2` variants
6841    /// returns `true` on `has_multiple_missing_kinds` (exactly 2
6842    /// missing, the SECOND-slot boundary of the ≥ 2 arm). Pins the
6843    /// second-slot short-circuit — a regression that dropped the
6844    /// second-slot check (returning `true` on any ≥ 1-missing arm,
6845    /// conflating with `has_any_missing_kind`) would still pass here,
6846    /// so this pin is complemented by the NEAR-SATURATION-ENDPOINT
6847    /// pin which distinguishes the =1 arm from the ≥ 2 arm.
6848    /// Only meaningful on `N ≥ 2` closed sets.
6849    #[test]
6850    fn condition_slice_has_multiple_missing_kinds_returns_true_on_two_missing_slice() {
6851        assert!(
6852            ConditionKind::ALL.len() >= 2,
6853            "test assumes ConditionKind::ALL has ≥ 2 variants",
6854        );
6855        for i in 0..ConditionKind::ALL.len() {
6856            for j in (i + 1)..ConditionKind::ALL.len() {
6857                let two_missing: Vec<Condition> = ConditionKind::ALL
6858                    .into_iter()
6859                    .enumerate()
6860                    .filter(|(k, _)| *k != i && *k != j)
6861                    .map(|(_, k)| condition_with(k))
6862                    .collect();
6863                let slice = two_missing.as_slice();
6864                assert!(
6865                    slice.has_multiple_missing_kinds(),
6866                    "two-missing slice (omitting index {i} and {j}) must return true on has_multiple_missing_kinds (2 missing, ≥ 2)",
6867                );
6868                assert_eq!(
6869                    slice.has_multiple_missing_kinds(),
6870                    slice.missing_kind_count() >= 2,
6871                    "two-missing has_multiple_missing_kinds must equal (missing_kind_count() >= 2) for omitted=({i}, {j})",
6872                );
6873            }
6874        }
6875    }
6876
6877    /// MULTIPLICITY pin — a slice at the empty-endpoint duplicated
6878    /// remains empty (nothing to duplicate), while a slice at a
6879    /// K-populated arm with each populated kind duplicated still
6880    /// returns `true` on any `N ≥ K + 2` — multiplicity is
6881    /// irrelevant to the cardinality many-arm projection on the
6882    /// closed-set-complement axis, byte-for-byte peer of the
6883    /// saturation-predicate arm. Sweeps the near-two-missing
6884    /// arrangement (each pair-omitted arm, doubled populated) on
6885    /// `N ≥ 2` closed sets.
6886    #[test]
6887    fn condition_slice_has_multiple_missing_kinds_ignores_multiplicity() {
6888        assert!(
6889            ConditionKind::ALL.len() >= 2,
6890            "test assumes ConditionKind::ALL has ≥ 2 variants",
6891        );
6892        for i in 0..ConditionKind::ALL.len() {
6893            for j in (i + 1)..ConditionKind::ALL.len() {
6894                let mut doubled: Vec<Condition> = Vec::new();
6895                for (idx, kind) in ConditionKind::ALL.into_iter().enumerate() {
6896                    if idx != i && idx != j {
6897                        doubled.push(condition_with(kind));
6898                        doubled.push(condition_with(kind));
6899                    }
6900                }
6901                assert!(
6902                    doubled.as_slice().has_multiple_missing_kinds(),
6903                    "two-missing slice (omitting index {i} and {j}) with each populated kind duplicated must return true on has_multiple_missing_kinds",
6904                );
6905            }
6906        }
6907    }
6908
6909    // ── ConditionSliceExt::has_at_most_one_missing_kind — "≤ 1" pins ─
6910    //
6911    // Boolean cardinality "≤ 1" negation peer of
6912    // `has_multiple_missing_kinds` on the closed-set-complement axis:
6913    // `has_at_most_one_missing_kind()` returns `true` iff AT MOST ONE
6914    // `ConditionKind::ALL` variant appears zero times in the slice.
6915    // Definitional negation of the many-arm primitive
6916    // (`!has_multiple_missing_kinds`), and trichotomy-union of the
6917    // zero-arm + one-arm primitives (`is_kind_saturated ||
6918    // has_unique_missing_kind`). Body short-circuits transitively
6919    // through the many-arm walk — strictly cheaper than
6920    // `missing_kind_count() <= 1` (which walks every slot) and
6921    // `missing_kinds().len() <= 1` (which allocates the Vec) on every
6922    // arm. The composition laws
6923    // `has_at_most_one_missing_kind() == !has_multiple_missing_kinds()`,
6924    // `has_at_most_one_missing_kind() == (missing_kind_count() <= 1)`,
6925    // `has_at_most_one_missing_kind() == (missing_kinds().len() <= 1)`,
6926    // and `has_at_most_one_missing_kind() == is_kind_saturated() ||
6927    // has_unique_missing_kind()` are pinned as the "≤ 1" arm of
6928    // `assert_slice_refinement_composition_laws`. Byte-for-byte peer
6929    // of `crate::tagged_union::TaggedUnion::has_at_most_one_missing_kind`
6930    // one struct-layer up under the SAME `!has_multiple_missing_kinds`
6931    // definitional negation shape.
6932
6933    /// EMPTY-SLICE pin — an empty slice returns `false` on
6934    /// `has_at_most_one_missing_kind` on any `N ≥ 2` closed set
6935    /// (every kind is missing — `N ≥ 2` missing, not `≤ 1`). Dual of
6936    /// the empty-slice arm on `has_multiple_missing_kinds` which
6937    /// returns `true`.
6938    #[test]
6939    fn condition_slice_has_at_most_one_missing_kind_returns_false_on_empty_slice() {
6940        assert!(
6941            ConditionKind::ALL.len() >= 2,
6942            "test assumes ConditionKind::ALL has ≥ 2 variants",
6943        );
6944        let empty: &[Condition] = &[];
6945        assert!(
6946            !empty.has_at_most_one_missing_kind(),
6947            "empty slice must return false on has_at_most_one_missing_kind (all N ≥ 2 kinds missing, not ≤ 1)",
6948        );
6949        assert_eq!(
6950            empty.has_at_most_one_missing_kind(),
6951            empty.missing_kind_count() <= 1,
6952            "empty has_at_most_one_missing_kind must equal (missing_kind_count() <= 1)",
6953        );
6954    }
6955
6956    /// SINGLE-KIND pin — a slice populating exactly one variant
6957    /// returns `false` on any `N ≥ 3` closed set (`N - 1 ≥ 2` kinds
6958    /// missing, not `≤ 1`). On the degenerate `N == 2` closed set it
6959    /// would return `true` (exactly 1 missing), so the pin gates on
6960    /// `N ≥ 3` — this workspace has `N == 8`.
6961    #[test]
6962    fn condition_slice_has_at_most_one_missing_kind_returns_false_on_single_kind_slice() {
6963        if ConditionKind::ALL.len() < 3 {
6964            return;
6965        }
6966        for populated in ConditionKind::ALL {
6967            let slice = [condition_with(populated)];
6968            assert!(
6969                !slice.has_at_most_one_missing_kind(),
6970                "single-populated slice with {populated:?} must return false on has_at_most_one_missing_kind on N ≥ 3 closed sets ({} kinds missing, not ≤ 1)",
6971                ConditionKind::ALL.len() - 1,
6972            );
6973            assert_eq!(
6974                slice.has_at_most_one_missing_kind(),
6975                slice.missing_kind_count() <= 1,
6976                "single-populated has_at_most_one_missing_kind must equal (missing_kind_count() <= 1) for {populated:?}",
6977            );
6978        }
6979    }
6980
6981    /// NEAR-SATURATION-ENDPOINT pin — a slice carrying every
6982    /// [`ConditionKind`] EXCEPT exactly one returns `true` on
6983    /// `has_at_most_one_missing_kind` (exactly 1 missing, `≤ 1`).
6984    /// The `= 1` mid-endpoint arm of the trichotomy union — one of
6985    /// the two arrangement classes where the "≤ 1" primitive
6986    /// returns `true`. Also pins the widened composition laws
6987    /// `has_at_most_one_missing_kind() == (missing_kinds().len() <= 1)`
6988    /// and `has_at_most_one_missing_kind() == !has_multiple_missing_kinds()`
6989    /// and the trichotomy-union composition law
6990    /// `has_at_most_one_missing_kind() == is_kind_saturated() ||
6991    /// has_unique_missing_kind()`.
6992    #[test]
6993    fn condition_slice_has_at_most_one_missing_kind_returns_true_on_near_saturation_endpoint() {
6994        for omitted in ConditionKind::ALL {
6995            let near_saturated: Vec<Condition> = ConditionKind::ALL
6996                .into_iter()
6997                .filter(|k| *k != omitted)
6998                .map(condition_with)
6999                .collect();
7000            let slice = near_saturated.as_slice();
7001            assert!(
7002                slice.has_at_most_one_missing_kind(),
7003                "near-saturation-endpoint slice (omitting {omitted:?}) must return true on has_at_most_one_missing_kind (1 missing, ≤ 1)",
7004            );
7005            assert_eq!(
7006                slice.has_at_most_one_missing_kind(),
7007                !slice.has_multiple_missing_kinds(),
7008                "near-saturation-endpoint has_at_most_one_missing_kind must equal !has_multiple_missing_kinds() for omitted={omitted:?}",
7009            );
7010            assert_eq!(
7011                slice.has_at_most_one_missing_kind(),
7012                slice.missing_kind_count() <= 1,
7013                "near-saturation-endpoint has_at_most_one_missing_kind must equal (missing_kind_count() <= 1) for omitted={omitted:?}",
7014            );
7015            assert_eq!(
7016                slice.has_at_most_one_missing_kind(),
7017                slice.missing_kinds().len() <= 1,
7018                "near-saturation-endpoint has_at_most_one_missing_kind must equal (missing_kinds().len() <= 1) for omitted={omitted:?}",
7019            );
7020            assert_eq!(
7021                slice.has_at_most_one_missing_kind(),
7022                slice.is_kind_saturated() || slice.has_unique_missing_kind(),
7023                "near-saturation-endpoint has_at_most_one_missing_kind must equal (is_kind_saturated() || has_unique_missing_kind()) for omitted={omitted:?}",
7024            );
7025        }
7026    }
7027
7028    /// SATURATED pin — a slice carrying every [`ConditionKind`]
7029    /// variant returns `true` on `has_at_most_one_missing_kind` (0
7030    /// missing, `≤ 1`). The `= 0` zero-arm of the trichotomy union
7031    /// — the OTHER arrangement class where the "≤ 1" primitive
7032    /// returns `true`. Dual of the SATURATED arm on
7033    /// `has_multiple_missing_kinds` which returns `false`.
7034    #[test]
7035    fn condition_slice_has_at_most_one_missing_kind_returns_true_on_saturated_slice() {
7036        let saturated: Vec<Condition> =
7037            ConditionKind::ALL.into_iter().map(condition_with).collect();
7038        assert!(
7039            saturated.as_slice().has_at_most_one_missing_kind(),
7040            "slice containing every ConditionKind must return true on has_at_most_one_missing_kind (0 missing, ≤ 1)",
7041        );
7042        assert_eq!(
7043            saturated.as_slice().has_at_most_one_missing_kind(),
7044            saturated.as_slice().missing_kind_count() <= 1,
7045            "saturated has_at_most_one_missing_kind must equal (missing_kind_count() <= 1)",
7046        );
7047        assert_eq!(
7048            saturated.as_slice().has_at_most_one_missing_kind(),
7049            saturated.as_slice().is_kind_saturated()
7050                || saturated.as_slice().has_unique_missing_kind(),
7051            "saturated has_at_most_one_missing_kind must equal (is_kind_saturated() || has_unique_missing_kind())",
7052        );
7053    }
7054
7055    /// TWO-MISSING pin — a slice populating exactly `N - 2` variants
7056    /// returns `false` on `has_at_most_one_missing_kind` (exactly 2
7057    /// missing, not `≤ 1`). The SECOND-slot boundary between the
7058    /// "≤ 1" arm and the "≥ 2" arm — a regression that dropped the
7059    /// negation (returning `has_multiple_missing_kinds` itself),
7060    /// swapped the wrong side, or drifted the trichotomy union
7061    /// operator from `||` to `&&` surfaces HERE.
7062    #[test]
7063    fn condition_slice_has_at_most_one_missing_kind_returns_false_on_two_missing_slice() {
7064        assert!(
7065            ConditionKind::ALL.len() >= 2,
7066            "test assumes ConditionKind::ALL has ≥ 2 variants",
7067        );
7068        for i in 0..ConditionKind::ALL.len() {
7069            for j in (i + 1)..ConditionKind::ALL.len() {
7070                let two_missing: Vec<Condition> = ConditionKind::ALL
7071                    .into_iter()
7072                    .enumerate()
7073                    .filter(|(k, _)| *k != i && *k != j)
7074                    .map(|(_, k)| condition_with(k))
7075                    .collect();
7076                let slice = two_missing.as_slice();
7077                assert!(
7078                    !slice.has_at_most_one_missing_kind(),
7079                    "two-missing slice (omitting index {i} and {j}) must return false on has_at_most_one_missing_kind (2 missing, not ≤ 1)",
7080                );
7081                assert_eq!(
7082                    slice.has_at_most_one_missing_kind(),
7083                    slice.missing_kind_count() <= 1,
7084                    "two-missing has_at_most_one_missing_kind must equal (missing_kind_count() <= 1) for omitted=({i}, {j})",
7085                );
7086            }
7087        }
7088    }
7089
7090    /// MULTIPLICITY pin — a slice at a K-populated arm with each
7091    /// populated kind duplicated still returns the same "≤ 1"
7092    /// Boolean as its single-copy peer — multiplicity is irrelevant
7093    /// to the cardinality "≤ 1" projection on the closed-set-
7094    /// complement axis, byte-for-byte peer of
7095    /// `has_multiple_missing_kinds`'s multiplicity behavior.
7096    #[test]
7097    fn condition_slice_has_at_most_one_missing_kind_ignores_multiplicity() {
7098        // Near-saturation arm doubled — every populated kind
7099        // doubled, exactly one variant omitted; still returns true.
7100        for omitted in ConditionKind::ALL {
7101            let mut doubled: Vec<Condition> = Vec::new();
7102            for k in ConditionKind::ALL {
7103                if k != omitted {
7104                    doubled.push(condition_with(k));
7105                    doubled.push(condition_with(k));
7106                }
7107            }
7108            assert!(
7109                doubled.as_slice().has_at_most_one_missing_kind(),
7110                "near-saturation slice (omitting {omitted:?}) with each populated kind duplicated must return true on has_at_most_one_missing_kind",
7111            );
7112        }
7113    }
7114
7115    // ── ConditionSliceExt::lacks_kind — per-kind complement pins ──────
7116    //
7117    // Boolean per-kind closed-set-complement peer of `has_kind`:
7118    // `lacks_kind(k)` returns `true` iff NO Condition in the slice
7119    // carries the addressed kind, byte-for-byte with `!has_kind(k)`
7120    // via the definitional negation in the trait's default body.
7121    // The composition laws `lacks_kind(k) == !has_kind(k)` and
7122    // `lacks_kind(k) == missing_kinds().contains(&k)` are pinned as
7123    // the per-kind-complement arm of
7124    // `assert_slice_refinement_composition_laws`. Byte-for-byte peer
7125    // of `crate::tagged_union::TaggedUnion::lacks` one struct-layer up
7126    // under the SAME `!has(kind)` definitional negation shape.
7127
7128    /// EMPTY-SLICE pin — an empty slice returns `true` for every
7129    /// [`ConditionKind`] on `lacks_kind` (no kind appears, so every
7130    /// kind is lacked). Dual of the empty-slice arm on `has_kind`
7131    /// (which returns `false` for every kind). Sweeps
7132    /// [`ConditionKind::ALL`] so a regression that dropped the
7133    /// negation, returned `false` (the has-kind identity on empty),
7134    /// or drifted to a per-kind constant surfaces HERE.
7135    #[test]
7136    fn condition_slice_lacks_kind_returns_true_on_empty_slice_for_every_kind() {
7137        let empty: &[Condition] = &[];
7138        for kind in ConditionKind::ALL {
7139            assert!(
7140                empty.lacks_kind(kind),
7141                "empty slice must return true on lacks_kind for {kind:?}",
7142            );
7143            assert_eq!(
7144                empty.lacks_kind(kind),
7145                !empty.has_kind(kind),
7146                "empty lacks_kind must equal !has_kind for {kind:?}",
7147            );
7148        }
7149    }
7150
7151    /// SINGLE-KIND pin — a slice with EXACTLY ONE `Condition` carrying
7152    /// the addressed kind returns `false` on `lacks_kind` for the
7153    /// populated kind and `true` for every OTHER kind. Sweeps
7154    /// [`ConditionKind::ALL`] × [`ConditionKind::ALL`] so a regression
7155    /// that swapped the wrong side, drifted the negation, or drifted
7156    /// the walk from `has_kind` surfaces HERE. Also pins the
7157    /// composition law `lacks_kind(k) == !has_kind(k)` per-kind.
7158    #[test]
7159    fn condition_slice_lacks_kind_returns_true_on_every_missing_kind() {
7160        for populated in ConditionKind::ALL {
7161            let slice = [condition_with(populated)];
7162            for probe in ConditionKind::ALL {
7163                let expected_lacks = probe != populated;
7164                assert_eq!(
7165                    slice.as_slice().lacks_kind(probe),
7166                    expected_lacks,
7167                    "single-populated slice with {populated:?} must return {expected_lacks} on lacks_kind({probe:?})",
7168                );
7169                assert_eq!(
7170                    slice.as_slice().lacks_kind(probe),
7171                    !slice.as_slice().has_kind(probe),
7172                    "single-populated lacks_kind({probe:?}) must equal !has_kind({probe:?}) for populated={populated:?}",
7173                );
7174            }
7175        }
7176    }
7177
7178    /// SATURATED pin — a slice carrying every [`ConditionKind`] variant
7179    /// returns `false` on `lacks_kind` for every arm (the SOLE
7180    /// arrangement where the primitive returns `false` for every kind).
7181    /// Dual of the SATURATED arm on `is_kind_saturated` which returns
7182    /// `true`. Pins the composition law `lacks_kind(k) ==
7183    /// missing_kinds().contains(&k)` per-kind against the empty missing
7184    /// set.
7185    #[test]
7186    fn condition_slice_lacks_kind_returns_false_on_saturated_slice_for_every_kind() {
7187        let saturated: Vec<Condition> =
7188            ConditionKind::ALL.into_iter().map(condition_with).collect();
7189        let missing = saturated.as_slice().missing_kinds();
7190        for kind in ConditionKind::ALL {
7191            assert!(
7192                !saturated.as_slice().lacks_kind(kind),
7193                "saturated slice must return false on lacks_kind for {kind:?}",
7194            );
7195            assert_eq!(
7196                saturated.as_slice().lacks_kind(kind),
7197                missing.contains(&kind),
7198                "saturated lacks_kind({kind:?}) must equal missing_kinds().contains(&{kind:?})",
7199            );
7200        }
7201    }
7202
7203    /// MULTIPLICITY pin — a slice carrying the addressed kind multiple
7204    /// times still returns `false` on `lacks_kind` for that kind
7205    /// (multiplicity is irrelevant to the per-kind Boolean-complement
7206    /// projection on the closed-set-complement axis, byte-for-byte
7207    /// with `has_kind`'s multiplicity behavior).
7208    #[test]
7209    fn condition_slice_lacks_kind_ignores_multiplicity_on_the_populated_side() {
7210        for populated in ConditionKind::ALL {
7211            let slice = [
7212                condition_with(populated),
7213                condition_with(populated),
7214                condition_with(populated),
7215            ];
7216            assert!(
7217                !slice.as_slice().lacks_kind(populated),
7218                "duplicate-populated slice with {populated:?} must return false on lacks_kind for {populated:?}",
7219            );
7220        }
7221    }
7222
7223    // ── ConditionSliceExt::first_distinct_kind — earliest-element pins ─
7224    //
7225    // Short-circuiting Option<ConditionKind> peer of the closed-set-
7226    // inversion widened primitive `distinct_kinds`: `first_distinct_kind()`
7227    // returns the earliest present kind in canonical ConditionKind::ALL
7228    // order without materializing the intermediate Vec<ConditionKind>.
7229    // The composition law `first_distinct_kind() == distinct_kinds()
7230    // .first().copied()` is pinned as the earliest-element-inversion arm
7231    // of `assert_slice_refinement_composition_laws`.
7232
7233    /// EMPTY-SLICE pin — an empty slice returns `None` on
7234    /// `first_distinct_kind`, byte-for-byte with
7235    /// `distinct_kinds().first().copied()`.
7236    #[test]
7237    fn condition_slice_first_distinct_kind_returns_none_on_empty_slice() {
7238        let empty: &[Condition] = &[];
7239        assert_eq!(
7240            empty.first_distinct_kind(),
7241            None,
7242            "empty slice must return None on first_distinct_kind",
7243        );
7244        assert_eq!(
7245            empty.first_distinct_kind(),
7246            empty.distinct_kinds().first().copied(),
7247            "empty first_distinct_kind must equal distinct_kinds().first().copied()",
7248        );
7249    }
7250
7251    /// PER-VARIANT pin — a slice with EXACTLY ONE `Condition` carrying
7252    /// the addressed kind returns `Some(that_kind)` on
7253    /// `first_distinct_kind`.
7254    #[test]
7255    fn condition_slice_first_distinct_kind_returns_populated_variant() {
7256        for populated in ConditionKind::ALL {
7257            let slice = [condition_with(populated)];
7258            assert_eq!(
7259                slice.first_distinct_kind(),
7260                Some(populated),
7261                "single-populated slice must return Some({populated:?}) on first_distinct_kind",
7262            );
7263            assert_eq!(
7264                slice.first_distinct_kind(),
7265                slice.distinct_kinds().first().copied(),
7266                "single-populated first_distinct_kind must equal distinct_kinds().first().copied() for {populated:?}",
7267            );
7268        }
7269    }
7270
7271    /// FULL-COVERAGE pin — a slice that carries every [`ConditionKind`]
7272    /// variant returns `Some(ConditionKind::ALL[0])` on
7273    /// `first_distinct_kind` (the first ALL entry hits at the earliest
7274    /// walk step).
7275    #[test]
7276    fn condition_slice_first_distinct_kind_returns_first_all_on_saturated_slice() {
7277        let saturated: Vec<Condition> =
7278            ConditionKind::ALL.into_iter().map(condition_with).collect();
7279        assert_eq!(
7280            saturated.as_slice().first_distinct_kind(),
7281            Some(ConditionKind::ALL[0]),
7282            "saturated slice must return Some(ConditionKind::ALL[0]) on first_distinct_kind",
7283        );
7284        assert_eq!(
7285            saturated.as_slice().first_distinct_kind(),
7286            saturated.as_slice().distinct_kinds().first().copied(),
7287            "saturated first_distinct_kind must equal distinct_kinds().first().copied()",
7288        );
7289    }
7290
7291    // ── ConditionSliceExt::first_missing_kind — earliest-element pins ──
7292
7293    /// EMPTY-SLICE pin — an empty slice returns
7294    /// `Some(ConditionKind::ALL[0])` on `first_missing_kind` (every
7295    /// kind missing, first hit is index 0). Dual of the empty-slice arm
7296    /// on `first_distinct_kind` which returns `None`.
7297    #[test]
7298    fn condition_slice_first_missing_kind_returns_first_all_on_empty_slice() {
7299        let empty: &[Condition] = &[];
7300        assert_eq!(
7301            empty.first_missing_kind(),
7302            Some(ConditionKind::ALL[0]),
7303            "empty slice must return Some(ConditionKind::ALL[0]) on first_missing_kind",
7304        );
7305        assert_eq!(
7306            empty.first_missing_kind(),
7307            empty.missing_kinds().first().copied(),
7308            "empty first_missing_kind must equal missing_kinds().first().copied()",
7309        );
7310    }
7311
7312    /// PER-VARIANT pin — a slice populating exactly `k` returns
7313    /// `Some(ALL[0])` if `k != ALL[0]`, else `Some(ALL[1])` (the earliest
7314    /// non-`k` entry).
7315    #[test]
7316    fn condition_slice_first_missing_kind_returns_earliest_absent_variant() {
7317        for populated in ConditionKind::ALL {
7318            let slice = [condition_with(populated)];
7319            let expected = ConditionKind::ALL.into_iter().find(|k| *k != populated);
7320            assert_eq!(
7321                slice.first_missing_kind(),
7322                expected,
7323                "single-populated slice must return earliest ALL entry != {populated:?} on first_missing_kind",
7324            );
7325            assert_eq!(
7326                slice.first_missing_kind(),
7327                slice.missing_kinds().first().copied(),
7328                "single-populated first_missing_kind must equal missing_kinds().first().copied() for {populated:?}",
7329            );
7330        }
7331    }
7332
7333    /// FULL-COVERAGE pin — a slice that carries every [`ConditionKind`]
7334    /// variant returns `None` on `first_missing_kind` (no kind missing).
7335    #[test]
7336    fn condition_slice_first_missing_kind_returns_none_on_saturated_slice() {
7337        let saturated: Vec<Condition> =
7338            ConditionKind::ALL.into_iter().map(condition_with).collect();
7339        assert_eq!(
7340            saturated.as_slice().first_missing_kind(),
7341            None,
7342            "saturated slice must return None on first_missing_kind",
7343        );
7344        assert_eq!(
7345            saturated.as_slice().first_missing_kind(),
7346            saturated.as_slice().missing_kinds().first().copied(),
7347            "saturated first_missing_kind must equal missing_kinds().first().copied()",
7348        );
7349    }
7350
7351    // ── ConditionSliceExt::last_distinct_kind — latest-element pins ────
7352    //
7353    // Short-circuiting Option<ConditionKind> peer of the closed-set-
7354    // inversion widened primitive `distinct_kinds` on the LATEST-hit
7355    // side: `last_distinct_kind()` returns the latest present kind in
7356    // canonical ConditionKind::ALL order via a REVERSED walk with no
7357    // intermediate Vec<ConditionKind> allocation. The composition law
7358    // `last_distinct_kind() == distinct_kinds().last().copied()` is
7359    // pinned as the latest-element-inversion arm of
7360    // `assert_slice_refinement_composition_laws`.
7361
7362    /// EMPTY-SLICE pin — an empty slice returns `None` on
7363    /// `last_distinct_kind`, byte-for-byte with
7364    /// `distinct_kinds().last().copied()` (both scalar endpoints agree
7365    /// on emptiness).
7366    #[test]
7367    fn condition_slice_last_distinct_kind_returns_none_on_empty_slice() {
7368        let empty: &[Condition] = &[];
7369        assert_eq!(
7370            empty.last_distinct_kind(),
7371            None,
7372            "empty slice must return None on last_distinct_kind",
7373        );
7374        assert_eq!(
7375            empty.last_distinct_kind(),
7376            empty.distinct_kinds().last().copied(),
7377            "empty last_distinct_kind must equal distinct_kinds().last().copied()",
7378        );
7379    }
7380
7381    /// PER-VARIANT pin — a slice with EXACTLY ONE `Condition` carrying
7382    /// the addressed kind returns `Some(that_kind)` on
7383    /// `last_distinct_kind` (single hit; earliest = latest endpoint).
7384    #[test]
7385    fn condition_slice_last_distinct_kind_returns_populated_variant() {
7386        for populated in ConditionKind::ALL {
7387            let slice = [condition_with(populated)];
7388            assert_eq!(
7389                slice.last_distinct_kind(),
7390                Some(populated),
7391                "single-populated slice must return Some({populated:?}) on last_distinct_kind",
7392            );
7393            assert_eq!(
7394                slice.last_distinct_kind(),
7395                slice.distinct_kinds().last().copied(),
7396                "single-populated last_distinct_kind must equal distinct_kinds().last().copied() for {populated:?}",
7397            );
7398            // On single-populated slice both endpoint projections agree.
7399            assert_eq!(
7400                slice.last_distinct_kind(),
7401                slice.first_distinct_kind(),
7402                "single-populated last_distinct_kind must equal first_distinct_kind for {populated:?} (single hit ⇒ earliest = latest)",
7403            );
7404        }
7405    }
7406
7407    /// FULL-COVERAGE pin — a slice that carries every [`ConditionKind`]
7408    /// variant returns `Some(*ConditionKind::ALL.last().unwrap())` on
7409    /// `last_distinct_kind` (the last ALL entry hits at the earliest
7410    /// walk step of the REVERSED walk).
7411    #[test]
7412    fn condition_slice_last_distinct_kind_returns_last_all_on_saturated_slice() {
7413        let saturated: Vec<Condition> =
7414            ConditionKind::ALL.into_iter().map(condition_with).collect();
7415        let last_all = ConditionKind::ALL.last().copied();
7416        assert_eq!(
7417            saturated.as_slice().last_distinct_kind(),
7418            last_all,
7419            "saturated slice must return Some(*ConditionKind::ALL.last().unwrap()) on last_distinct_kind",
7420        );
7421        assert_eq!(
7422            saturated.as_slice().last_distinct_kind(),
7423            saturated.as_slice().distinct_kinds().last().copied(),
7424            "saturated last_distinct_kind must equal distinct_kinds().last().copied()",
7425        );
7426    }
7427
7428    // ── ConditionSliceExt::last_missing_kind — latest-element pins ─────
7429
7430    /// EMPTY-SLICE pin — an empty slice returns
7431    /// `Some(*ConditionKind::ALL.last().unwrap())` on `last_missing_kind`
7432    /// (every kind missing, latest hit is the last ALL entry). Dual of
7433    /// the empty-slice arm on `last_distinct_kind` which returns `None`.
7434    #[test]
7435    fn condition_slice_last_missing_kind_returns_last_all_on_empty_slice() {
7436        let empty: &[Condition] = &[];
7437        let last_all = ConditionKind::ALL.last().copied();
7438        assert_eq!(
7439            empty.last_missing_kind(),
7440            last_all,
7441            "empty slice must return Some(*ConditionKind::ALL.last().unwrap()) on last_missing_kind",
7442        );
7443        assert_eq!(
7444            empty.last_missing_kind(),
7445            empty.missing_kinds().last().copied(),
7446            "empty last_missing_kind must equal missing_kinds().last().copied()",
7447        );
7448    }
7449
7450    /// PER-VARIANT pin — a slice populating exactly `k` returns
7451    /// `Some(*ALL.last().unwrap())` if `k != ALL.last().unwrap()`, else
7452    /// `Some(ALL[ALL.len() - 2])` (the latest ALL entry != `k`).
7453    #[test]
7454    fn condition_slice_last_missing_kind_returns_latest_absent_variant() {
7455        for populated in ConditionKind::ALL {
7456            let slice = [condition_with(populated)];
7457            let expected = ConditionKind::ALL
7458                .into_iter()
7459                .rev()
7460                .find(|k| *k != populated);
7461            assert_eq!(
7462                slice.last_missing_kind(),
7463                expected,
7464                "single-populated slice must return latest ALL entry != {populated:?} on last_missing_kind",
7465            );
7466            assert_eq!(
7467                slice.last_missing_kind(),
7468                slice.missing_kinds().last().copied(),
7469                "single-populated last_missing_kind must equal missing_kinds().last().copied() for {populated:?}",
7470            );
7471        }
7472    }
7473
7474    /// FULL-COVERAGE pin — a slice that carries every [`ConditionKind`]
7475    /// variant returns `None` on `last_missing_kind` (no kind missing).
7476    #[test]
7477    fn condition_slice_last_missing_kind_returns_none_on_saturated_slice() {
7478        let saturated: Vec<Condition> =
7479            ConditionKind::ALL.into_iter().map(condition_with).collect();
7480        assert_eq!(
7481            saturated.as_slice().last_missing_kind(),
7482            None,
7483            "saturated slice must return None on last_missing_kind",
7484        );
7485        assert_eq!(
7486            saturated.as_slice().last_missing_kind(),
7487            saturated.as_slice().missing_kinds().last().copied(),
7488            "saturated last_missing_kind must equal missing_kinds().last().copied()",
7489        );
7490    }
7491
7492    // ── Boundary distinct-set triad — substrate-delegation pins ────────
7493    //
7494    // The (precondition, postcondition, condition-union) distinct-set
7495    // triad on [`Boundary`] delegates to the slice-level substrate
7496    // primitive [`ConditionSliceExt::distinct_kinds`] on each half-slice
7497    // and composes the union via [`Self::has_condition_kind`] over
7498    // [`ConditionKind::ALL`]. The dedicated tests below pin each arm's
7499    // delegation shape; the substrate testkit macro
7500    // `assert_surface_union_composition_laws` (extended in this commit
7501    // with the closed-set-inversion arm) pins the union composition law
7502    // against the two half-slice arms in canonical ALL-order.
7503
7504    /// SUBSTRATE-DELEGATION pin (Boundary distinct-kind-count triad)
7505    /// — the three `distinct_*_kind_count` methods on [`Boundary`]
7506    /// delegate to the slice-level substrate primitive
7507    /// [`ConditionSliceExt::distinct_kind_count`] over the two
7508    /// `Vec<Condition>` slots (precondition + postcondition) and
7509    /// compose the union scalar via
7510    /// `ConditionKind::ALL.filter(|k| has_condition_kind(*k)).count()`.
7511    /// Sweep `ConditionKind::ALL × ConditionKind::ALL` so a regression
7512    /// that (a) inlined a divergent closed-set walk at either half-slice
7513    /// arm, (b) reversed the union walk order, or (c) narrowed the
7514    /// union to an intersection surfaces HERE. Also pins the
7515    /// composition law
7516    /// `distinct_*_kind_count() == distinct_*_kinds().len()` at each
7517    /// arm — a regression that overrode the scalar projection to skip a
7518    /// kind or double-count a slot fails HERE.
7519    #[test]
7520    fn distinct_condition_kind_count_triad_delegates_and_matches_distinct_kinds_len() {
7521        // Empty boundary — every arm returns 0.
7522        let b = Boundary::default();
7523        for kind in ConditionKind::ALL {
7524            assert_eq!(
7525                b.distinct_precondition_kind_count(),
7526                0,
7527                "empty boundary must return 0 on distinct_precondition_kind_count, kind={kind:?}",
7528            );
7529            assert_eq!(
7530                b.distinct_postcondition_kind_count(),
7531                0,
7532                "empty boundary must return 0 on distinct_postcondition_kind_count, kind={kind:?}",
7533            );
7534            assert_eq!(
7535                b.distinct_condition_kind_count(),
7536                0,
7537                "empty boundary must return 0 on distinct_condition_kind_count, kind={kind:?}",
7538            );
7539        }
7540
7541        for pre_kind in ConditionKind::ALL {
7542            for post_kind in ConditionKind::ALL {
7543                let mut b = Boundary::default();
7544                b.preconditions.push(condition_with(pre_kind));
7545                b.postconditions.push(condition_with(post_kind));
7546
7547                assert_eq!(
7548                    b.distinct_precondition_kind_count(),
7549                    b.preconditions.distinct_kind_count(),
7550                    "Boundary::distinct_precondition_kind_count must delegate verbatim to \
7551                     preconditions.distinct_kind_count() for pre={pre_kind:?} post={post_kind:?}",
7552                );
7553                assert_eq!(
7554                    b.distinct_precondition_kind_count(),
7555                    b.distinct_precondition_kinds().len(),
7556                    "Boundary::distinct_precondition_kind_count must equal \
7557                     distinct_precondition_kinds().len() for pre={pre_kind:?} post={post_kind:?}",
7558                );
7559                assert_eq!(
7560                    b.distinct_postcondition_kind_count(),
7561                    b.postconditions.distinct_kind_count(),
7562                    "Boundary::distinct_postcondition_kind_count must delegate verbatim to \
7563                     postconditions.distinct_kind_count() for pre={pre_kind:?} post={post_kind:?}",
7564                );
7565                assert_eq!(
7566                    b.distinct_postcondition_kind_count(),
7567                    b.distinct_postcondition_kinds().len(),
7568                    "Boundary::distinct_postcondition_kind_count must equal \
7569                     distinct_postcondition_kinds().len() for pre={pre_kind:?} post={post_kind:?}",
7570                );
7571                let expected_union_count = if pre_kind == post_kind { 1 } else { 2 };
7572                assert_eq!(
7573                    b.distinct_condition_kind_count(),
7574                    expected_union_count,
7575                    "Boundary::distinct_condition_kind_count must count distinct union kinds \
7576                     for pre={pre_kind:?} post={post_kind:?}",
7577                );
7578                assert_eq!(
7579                    b.distinct_condition_kind_count(),
7580                    b.distinct_condition_kinds().len(),
7581                    "Boundary::distinct_condition_kind_count must equal \
7582                     distinct_condition_kinds().len() for pre={pre_kind:?} post={post_kind:?}",
7583                );
7584            }
7585        }
7586    }
7587
7588    /// SUBSTRATE-DELEGATION pin (Boundary distinct-set triad) — the
7589    /// three `distinct_*_kinds` methods on [`Boundary`] delegate to the
7590    /// slice-level substrate primitive over the two `Vec<Condition>`
7591    /// slots (precondition + postcondition) and compose the union via
7592    /// `ConditionKind::ALL.filter(|k| has_condition_kind(*k))`. Sweep
7593    /// `ConditionKind::ALL × ConditionKind::ALL` so a regression that
7594    /// (a) inlined a divergent closed-set walk at either half-slice
7595    /// arm, (b) reversed the union walk order, or (c) narrowed the
7596    /// union to an intersection surfaces HERE.
7597    #[test]
7598    fn distinct_condition_kinds_triad_delegates_to_slice_distinct_kinds() {
7599        for pre_kind in ConditionKind::ALL {
7600            for post_kind in ConditionKind::ALL {
7601                let mut b = Boundary::default();
7602                b.preconditions.push(condition_with(pre_kind));
7603                b.postconditions.push(condition_with(post_kind));
7604
7605                assert_eq!(
7606                    b.distinct_precondition_kinds(),
7607                    b.preconditions.distinct_kinds(),
7608                    "Boundary::distinct_precondition_kinds must delegate verbatim to \
7609                     preconditions.distinct_kinds() for pre={pre_kind:?} post={post_kind:?}",
7610                );
7611                assert_eq!(
7612                    b.distinct_postcondition_kinds(),
7613                    b.postconditions.distinct_kinds(),
7614                    "Boundary::distinct_postcondition_kinds must delegate verbatim to \
7615                     postconditions.distinct_kinds() for pre={pre_kind:?} post={post_kind:?}",
7616                );
7617                let expected_union: Vec<_> = ConditionKind::ALL
7618                    .into_iter()
7619                    .filter(|k| pre_kind == *k || post_kind == *k)
7620                    .collect();
7621                assert_eq!(
7622                    b.distinct_condition_kinds(),
7623                    expected_union,
7624                    "Boundary::distinct_condition_kinds must equal ConditionKind::ALL-ordered \
7625                     set-union of the two half-slice distinct-sets for pre={pre_kind:?} post={post_kind:?}",
7626                );
7627            }
7628        }
7629    }
7630
7631    /// SUBSTRATE-DELEGATION pin (Boundary missing-set triad) — the
7632    /// three `missing_*_kinds` methods on [`Boundary`] delegate to the
7633    /// slice-level substrate primitive
7634    /// [`ConditionSliceExt::missing_kinds`] over the two
7635    /// `Vec<Condition>` slots (precondition + postcondition) and
7636    /// compose the union via
7637    /// `ConditionKind::ALL.filter(|k| !has_condition_kind(*k))`. Sweep
7638    /// `ConditionKind::ALL × ConditionKind::ALL` so a regression that
7639    /// (a) inlined a divergent closed-set walk at either half-slice
7640    /// arm, (b) reversed the union walk order, (c) widened the union
7641    /// intersection to a union (a `||` inlined where `&&` is required
7642    /// on the missing side), or (d) forgot the negation surfaces HERE.
7643    /// Also pins the empty-boundary edge case: every arm returns
7644    /// `ConditionKind::ALL.to_vec()` on an empty boundary.
7645    #[test]
7646    fn missing_condition_kinds_triad_delegates_to_slice_missing_kinds() {
7647        // Empty boundary — every arm returns ConditionKind::ALL (nothing
7648        // is populated, so every kind is missing on all three slots).
7649        let b = Boundary::default();
7650        let all_kinds = ConditionKind::ALL.to_vec();
7651        assert_eq!(
7652            b.missing_precondition_kinds(),
7653            all_kinds,
7654            "empty boundary must return ConditionKind::ALL on missing_precondition_kinds",
7655        );
7656        assert_eq!(
7657            b.missing_postcondition_kinds(),
7658            all_kinds,
7659            "empty boundary must return ConditionKind::ALL on missing_postcondition_kinds",
7660        );
7661        assert_eq!(
7662            b.missing_condition_kinds(),
7663            all_kinds,
7664            "empty boundary must return ConditionKind::ALL on missing_condition_kinds",
7665        );
7666
7667        for pre_kind in ConditionKind::ALL {
7668            for post_kind in ConditionKind::ALL {
7669                let mut b = Boundary::default();
7670                b.preconditions.push(condition_with(pre_kind));
7671                b.postconditions.push(condition_with(post_kind));
7672
7673                assert_eq!(
7674                    b.missing_precondition_kinds(),
7675                    b.preconditions.missing_kinds(),
7676                    "Boundary::missing_precondition_kinds must delegate verbatim to \
7677                     preconditions.missing_kinds() for pre={pre_kind:?} post={post_kind:?}",
7678                );
7679                assert_eq!(
7680                    b.missing_postcondition_kinds(),
7681                    b.postconditions.missing_kinds(),
7682                    "Boundary::missing_postcondition_kinds must delegate verbatim to \
7683                     postconditions.missing_kinds() for pre={pre_kind:?} post={post_kind:?}",
7684                );
7685                // Union: a kind is missing from the union iff it is
7686                // missing from BOTH half-slices (SET-INTERSECTION).
7687                let expected_union: Vec<_> = ConditionKind::ALL
7688                    .into_iter()
7689                    .filter(|k| pre_kind != *k && post_kind != *k)
7690                    .collect();
7691                assert_eq!(
7692                    b.missing_condition_kinds(),
7693                    expected_union,
7694                    "Boundary::missing_condition_kinds must equal ConditionKind::ALL-ordered \
7695                     set-INTERSECTION of the two half-slice missing-sets for pre={pre_kind:?} post={post_kind:?}",
7696                );
7697                // Partition invariant: distinct ∪ missing == ALL, disjoint.
7698                let distinct = b.distinct_condition_kinds();
7699                let missing = b.missing_condition_kinds();
7700                for kind in ConditionKind::ALL {
7701                    assert!(
7702                        distinct.contains(&kind) ^ missing.contains(&kind),
7703                        "(distinct, missing) partition violated on {kind:?} for pre={pre_kind:?} post={post_kind:?}",
7704                    );
7705                }
7706                assert_eq!(
7707                    distinct.len() + missing.len(),
7708                    ConditionKind::ALL.len(),
7709                    "Boundary (distinct, missing) cardinality partition drift for pre={pre_kind:?} post={post_kind:?}",
7710                );
7711            }
7712        }
7713    }
7714
7715    /// SUBSTRATE-DELEGATION pin (Boundary missing-kind-count triad) —
7716    /// the three `missing_*_kind_count` methods on [`Boundary`] delegate
7717    /// to the slice-level substrate primitive
7718    /// [`ConditionSliceExt::missing_kind_count`] over the two
7719    /// `Vec<Condition>` slots (precondition + postcondition) and
7720    /// compose the union via
7721    /// `ConditionKind::ALL.iter().filter(|k|
7722    /// !self.has_condition_kind(**k)).count()`. Sweep
7723    /// `ConditionKind::ALL × ConditionKind::ALL` so a regression that
7724    /// (a) inlined a divergent negated closed-set walk at either half-
7725    /// slice arm, (b) dropped the negation on the union arm, or (c)
7726    /// drifted from the widened-primitive length surfaces HERE. Also
7727    /// pins the scalar-partition invariant
7728    /// `distinct_kind_count + missing_kind_count == ConditionKind::ALL.len()`
7729    /// per arrangement.
7730    #[test]
7731    fn missing_condition_kind_count_triad_delegates_to_slice_missing_kind_count() {
7732        // Empty boundary — every arm returns ConditionKind::ALL.len()
7733        // (nothing is populated, so every kind is missing on all three
7734        // slots).
7735        let b = Boundary::default();
7736        let total = ConditionKind::ALL.len();
7737        assert_eq!(
7738            b.missing_precondition_kind_count(),
7739            total,
7740            "empty boundary must return ConditionKind::ALL.len() on missing_precondition_kind_count",
7741        );
7742        assert_eq!(
7743            b.missing_postcondition_kind_count(),
7744            total,
7745            "empty boundary must return ConditionKind::ALL.len() on missing_postcondition_kind_count",
7746        );
7747        assert_eq!(
7748            b.missing_condition_kind_count(),
7749            total,
7750            "empty boundary must return ConditionKind::ALL.len() on missing_condition_kind_count",
7751        );
7752
7753        for pre_kind in ConditionKind::ALL {
7754            for post_kind in ConditionKind::ALL {
7755                let mut b = Boundary::default();
7756                b.preconditions.push(condition_with(pre_kind));
7757                b.postconditions.push(condition_with(post_kind));
7758
7759                // Half-slice arms delegate byte-for-byte to the slice
7760                // substrate primitive.
7761                assert_eq!(
7762                    b.missing_precondition_kind_count(),
7763                    b.preconditions.missing_kind_count(),
7764                    "Boundary::missing_precondition_kind_count must delegate verbatim to \
7765                     preconditions.missing_kind_count() for pre={pre_kind:?} post={post_kind:?}",
7766                );
7767                assert_eq!(
7768                    b.missing_postcondition_kind_count(),
7769                    b.postconditions.missing_kind_count(),
7770                    "Boundary::missing_postcondition_kind_count must delegate verbatim to \
7771                     postconditions.missing_kind_count() for pre={pre_kind:?} post={post_kind:?}",
7772                );
7773                // Union arm equals missing_condition_kinds().len() — the
7774                // scalar cardinality of the two-slice intersection.
7775                assert_eq!(
7776                    b.missing_condition_kind_count(),
7777                    b.missing_condition_kinds().len(),
7778                    "Boundary::missing_condition_kind_count must equal missing_condition_kinds().len() \
7779                     for pre={pre_kind:?} post={post_kind:?}",
7780                );
7781                // Scalar-partition invariant: distinct + missing == ALL.
7782                assert_eq!(
7783                    b.distinct_condition_kind_count() + b.missing_condition_kind_count(),
7784                    ConditionKind::ALL.len(),
7785                    "Boundary (distinct, missing) scalar partition drift for pre={pre_kind:?} post={post_kind:?}",
7786                );
7787            }
7788        }
7789    }
7790
7791    /// SUBSTRATE-DELEGATION pin (Boundary first-distinct-kind triad) —
7792    /// the three `first_distinct_*_kind` methods on [`Boundary`]
7793    /// delegate to the slice-level substrate primitive
7794    /// [`ConditionSliceExt::first_distinct_kind`] over the two
7795    /// `Vec<Condition>` slots (precondition + postcondition) and
7796    /// compose the union via `ConditionKind::ALL.iter().copied()
7797    /// .find(|k| has_condition_kind(*k))`. Sweep
7798    /// `ConditionKind::ALL × ConditionKind::ALL` so a regression that
7799    /// inlined a divergent short-circuit walk at either half-slice arm,
7800    /// reversed the walk order, or dropped the short-circuit surfaces
7801    /// HERE. Also pins the composition law `first_distinct_*_kind() ==
7802    /// distinct_*_kinds().first().copied()` at each arm.
7803    #[test]
7804    fn first_distinct_condition_kind_triad_delegates_to_slice_first_distinct_kind() {
7805        // Empty boundary — every arm returns None.
7806        let b = Boundary::default();
7807        assert_eq!(
7808            b.first_distinct_precondition_kind(),
7809            None,
7810            "empty boundary must return None on first_distinct_precondition_kind",
7811        );
7812        assert_eq!(
7813            b.first_distinct_postcondition_kind(),
7814            None,
7815            "empty boundary must return None on first_distinct_postcondition_kind",
7816        );
7817        assert_eq!(
7818            b.first_distinct_condition_kind(),
7819            None,
7820            "empty boundary must return None on first_distinct_condition_kind",
7821        );
7822
7823        for pre_kind in ConditionKind::ALL {
7824            for post_kind in ConditionKind::ALL {
7825                let mut b = Boundary::default();
7826                b.preconditions.push(condition_with(pre_kind));
7827                b.postconditions.push(condition_with(post_kind));
7828
7829                assert_eq!(
7830                    b.first_distinct_precondition_kind(),
7831                    b.preconditions.first_distinct_kind(),
7832                    "Boundary::first_distinct_precondition_kind must delegate verbatim to \
7833                     preconditions.first_distinct_kind() for pre={pre_kind:?} post={post_kind:?}",
7834                );
7835                assert_eq!(
7836                    b.first_distinct_precondition_kind(),
7837                    b.distinct_precondition_kinds().first().copied(),
7838                    "Boundary::first_distinct_precondition_kind must equal \
7839                     distinct_precondition_kinds().first().copied() for pre={pre_kind:?} post={post_kind:?}",
7840                );
7841                assert_eq!(
7842                    b.first_distinct_postcondition_kind(),
7843                    b.postconditions.first_distinct_kind(),
7844                    "Boundary::first_distinct_postcondition_kind must delegate verbatim to \
7845                     postconditions.first_distinct_kind() for pre={pre_kind:?} post={post_kind:?}",
7846                );
7847                assert_eq!(
7848                    b.first_distinct_postcondition_kind(),
7849                    b.distinct_postcondition_kinds().first().copied(),
7850                    "Boundary::first_distinct_postcondition_kind must equal \
7851                     distinct_postcondition_kinds().first().copied() for pre={pre_kind:?} post={post_kind:?}",
7852                );
7853                let expected_union = ConditionKind::ALL
7854                    .into_iter()
7855                    .find(|k| pre_kind == *k || post_kind == *k);
7856                assert_eq!(
7857                    b.first_distinct_condition_kind(),
7858                    expected_union,
7859                    "Boundary::first_distinct_condition_kind must equal earliest ALL entry \
7860                     populated by either half-slice for pre={pre_kind:?} post={post_kind:?}",
7861                );
7862                assert_eq!(
7863                    b.first_distinct_condition_kind(),
7864                    b.distinct_condition_kinds().first().copied(),
7865                    "Boundary::first_distinct_condition_kind must equal \
7866                     distinct_condition_kinds().first().copied() for pre={pre_kind:?} post={post_kind:?}",
7867                );
7868            }
7869        }
7870    }
7871
7872    /// SUBSTRATE-DELEGATION pin (Boundary first-missing-kind triad) —
7873    /// the three `first_missing_*_kind` methods on [`Boundary`]
7874    /// delegate to the slice-level substrate primitive
7875    /// [`ConditionSliceExt::first_missing_kind`] over the two
7876    /// `Vec<Condition>` slots (precondition + postcondition) and
7877    /// compose the union via `ConditionKind::ALL.iter().copied()
7878    /// .find(|k| !has_condition_kind(*k))`. Sweep
7879    /// `ConditionKind::ALL × ConditionKind::ALL` so a regression that
7880    /// dropped the negation or drifted the short-circuit walk surfaces
7881    /// HERE. Also pins the composition law `first_missing_*_kind() ==
7882    /// missing_*_kinds().first().copied()` at each arm.
7883    #[test]
7884    fn first_missing_condition_kind_triad_delegates_to_slice_first_missing_kind() {
7885        // Empty boundary — every arm returns Some(ConditionKind::ALL[0]).
7886        let b = Boundary::default();
7887        let first = Some(ConditionKind::ALL[0]);
7888        assert_eq!(
7889            b.first_missing_precondition_kind(),
7890            first,
7891            "empty boundary must return Some(ConditionKind::ALL[0]) on first_missing_precondition_kind",
7892        );
7893        assert_eq!(
7894            b.first_missing_postcondition_kind(),
7895            first,
7896            "empty boundary must return Some(ConditionKind::ALL[0]) on first_missing_postcondition_kind",
7897        );
7898        assert_eq!(
7899            b.first_missing_condition_kind(),
7900            first,
7901            "empty boundary must return Some(ConditionKind::ALL[0]) on first_missing_condition_kind",
7902        );
7903
7904        for pre_kind in ConditionKind::ALL {
7905            for post_kind in ConditionKind::ALL {
7906                let mut b = Boundary::default();
7907                b.preconditions.push(condition_with(pre_kind));
7908                b.postconditions.push(condition_with(post_kind));
7909
7910                assert_eq!(
7911                    b.first_missing_precondition_kind(),
7912                    b.preconditions.first_missing_kind(),
7913                    "Boundary::first_missing_precondition_kind must delegate verbatim to \
7914                     preconditions.first_missing_kind() for pre={pre_kind:?} post={post_kind:?}",
7915                );
7916                assert_eq!(
7917                    b.first_missing_precondition_kind(),
7918                    b.missing_precondition_kinds().first().copied(),
7919                    "Boundary::first_missing_precondition_kind must equal \
7920                     missing_precondition_kinds().first().copied() for pre={pre_kind:?} post={post_kind:?}",
7921                );
7922                assert_eq!(
7923                    b.first_missing_postcondition_kind(),
7924                    b.postconditions.first_missing_kind(),
7925                    "Boundary::first_missing_postcondition_kind must delegate verbatim to \
7926                     postconditions.first_missing_kind() for pre={pre_kind:?} post={post_kind:?}",
7927                );
7928                assert_eq!(
7929                    b.first_missing_postcondition_kind(),
7930                    b.missing_postcondition_kinds().first().copied(),
7931                    "Boundary::first_missing_postcondition_kind must equal \
7932                     missing_postcondition_kinds().first().copied() for pre={pre_kind:?} post={post_kind:?}",
7933                );
7934                let expected_union = ConditionKind::ALL
7935                    .into_iter()
7936                    .find(|k| pre_kind != *k && post_kind != *k);
7937                assert_eq!(
7938                    b.first_missing_condition_kind(),
7939                    expected_union,
7940                    "Boundary::first_missing_condition_kind must equal earliest ALL entry \
7941                     NOT populated by either half-slice for pre={pre_kind:?} post={post_kind:?}",
7942                );
7943                assert_eq!(
7944                    b.first_missing_condition_kind(),
7945                    b.missing_condition_kinds().first().copied(),
7946                    "Boundary::first_missing_condition_kind must equal \
7947                     missing_condition_kinds().first().copied() for pre={pre_kind:?} post={post_kind:?}",
7948                );
7949            }
7950        }
7951    }
7952
7953    /// SUBSTRATE-DELEGATION pin (Boundary last-distinct-kind triad)
7954    /// — the three `last_distinct_*_kind` methods on [`Boundary`]
7955    /// delegate to the slice-level substrate primitive
7956    /// [`ConditionSliceExt::last_distinct_kind`] over the two
7957    /// `Vec<Condition>` slots (precondition + postcondition) and
7958    /// compose the union via `ConditionKind::ALL.iter().rev().copied()
7959    /// .find(|k| has_condition_kind(*k))`. Sweep
7960    /// `ConditionKind::ALL × ConditionKind::ALL` so a regression that
7961    /// (a) forgot to reverse the walk (returning `first_distinct_*_kind`),
7962    /// (b) inlined a divergent closed-set walk at either half-slice
7963    /// arm, or (c) narrowed the union to an intersection surfaces
7964    /// HERE. Also pins the composition law `last_distinct_*_kind() ==
7965    /// distinct_*_kinds().last().copied()` at each arm.
7966    #[test]
7967    fn last_distinct_condition_kind_triad_delegates_to_slice_last_distinct_kind() {
7968        // Empty boundary — every arm returns None.
7969        let b = Boundary::default();
7970        assert_eq!(
7971            b.last_distinct_precondition_kind(),
7972            None,
7973            "empty boundary must return None on last_distinct_precondition_kind",
7974        );
7975        assert_eq!(
7976            b.last_distinct_postcondition_kind(),
7977            None,
7978            "empty boundary must return None on last_distinct_postcondition_kind",
7979        );
7980        assert_eq!(
7981            b.last_distinct_condition_kind(),
7982            None,
7983            "empty boundary must return None on last_distinct_condition_kind",
7984        );
7985
7986        for pre_kind in ConditionKind::ALL {
7987            for post_kind in ConditionKind::ALL {
7988                let mut b = Boundary::default();
7989                b.preconditions.push(condition_with(pre_kind));
7990                b.postconditions.push(condition_with(post_kind));
7991
7992                assert_eq!(
7993                    b.last_distinct_precondition_kind(),
7994                    b.preconditions.last_distinct_kind(),
7995                    "Boundary::last_distinct_precondition_kind must delegate verbatim to \
7996                     preconditions.last_distinct_kind() for pre={pre_kind:?} post={post_kind:?}",
7997                );
7998                assert_eq!(
7999                    b.last_distinct_precondition_kind(),
8000                    b.distinct_precondition_kinds().last().copied(),
8001                    "Boundary::last_distinct_precondition_kind must equal \
8002                     distinct_precondition_kinds().last().copied() for pre={pre_kind:?} post={post_kind:?}",
8003                );
8004                assert_eq!(
8005                    b.last_distinct_postcondition_kind(),
8006                    b.postconditions.last_distinct_kind(),
8007                    "Boundary::last_distinct_postcondition_kind must delegate verbatim to \
8008                     postconditions.last_distinct_kind() for pre={pre_kind:?} post={post_kind:?}",
8009                );
8010                assert_eq!(
8011                    b.last_distinct_postcondition_kind(),
8012                    b.distinct_postcondition_kinds().last().copied(),
8013                    "Boundary::last_distinct_postcondition_kind must equal \
8014                     distinct_postcondition_kinds().last().copied() for pre={pre_kind:?} post={post_kind:?}",
8015                );
8016                let expected_union = ConditionKind::ALL
8017                    .into_iter()
8018                    .rev()
8019                    .find(|k| pre_kind == *k || post_kind == *k);
8020                assert_eq!(
8021                    b.last_distinct_condition_kind(),
8022                    expected_union,
8023                    "Boundary::last_distinct_condition_kind must equal latest ALL entry \
8024                     populated by either half-slice for pre={pre_kind:?} post={post_kind:?}",
8025                );
8026                assert_eq!(
8027                    b.last_distinct_condition_kind(),
8028                    b.distinct_condition_kinds().last().copied(),
8029                    "Boundary::last_distinct_condition_kind must equal \
8030                     distinct_condition_kinds().last().copied() for pre={pre_kind:?} post={post_kind:?}",
8031                );
8032            }
8033        }
8034    }
8035
8036    /// SUBSTRATE-DELEGATION pin (Boundary last-missing-kind triad) —
8037    /// the three `last_missing_*_kind` methods on [`Boundary`]
8038    /// delegate to the slice-level substrate primitive
8039    /// [`ConditionSliceExt::last_missing_kind`] over the two
8040    /// `Vec<Condition>` slots (precondition + postcondition) and
8041    /// compose the union via `ConditionKind::ALL.iter().rev().copied()
8042    /// .find(|k| !has_condition_kind(*k))`. Sweep
8043    /// `ConditionKind::ALL × ConditionKind::ALL` so a regression that
8044    /// dropped the negation or forgot the reversed short-circuit walk
8045    /// surfaces HERE. Also pins the composition law `last_missing_*_kind()
8046    /// == missing_*_kinds().last().copied()` at each arm.
8047    #[test]
8048    fn last_missing_condition_kind_triad_delegates_to_slice_last_missing_kind() {
8049        // Empty boundary — every arm returns Some(*ConditionKind::ALL.last().unwrap()).
8050        let b = Boundary::default();
8051        let last = ConditionKind::ALL.last().copied();
8052        assert_eq!(
8053            b.last_missing_precondition_kind(),
8054            last,
8055            "empty boundary must return Some(*ConditionKind::ALL.last().unwrap()) on last_missing_precondition_kind",
8056        );
8057        assert_eq!(
8058            b.last_missing_postcondition_kind(),
8059            last,
8060            "empty boundary must return Some(*ConditionKind::ALL.last().unwrap()) on last_missing_postcondition_kind",
8061        );
8062        assert_eq!(
8063            b.last_missing_condition_kind(),
8064            last,
8065            "empty boundary must return Some(*ConditionKind::ALL.last().unwrap()) on last_missing_condition_kind",
8066        );
8067
8068        for pre_kind in ConditionKind::ALL {
8069            for post_kind in ConditionKind::ALL {
8070                let mut b = Boundary::default();
8071                b.preconditions.push(condition_with(pre_kind));
8072                b.postconditions.push(condition_with(post_kind));
8073
8074                assert_eq!(
8075                    b.last_missing_precondition_kind(),
8076                    b.preconditions.last_missing_kind(),
8077                    "Boundary::last_missing_precondition_kind must delegate verbatim to \
8078                     preconditions.last_missing_kind() for pre={pre_kind:?} post={post_kind:?}",
8079                );
8080                assert_eq!(
8081                    b.last_missing_precondition_kind(),
8082                    b.missing_precondition_kinds().last().copied(),
8083                    "Boundary::last_missing_precondition_kind must equal \
8084                     missing_precondition_kinds().last().copied() for pre={pre_kind:?} post={post_kind:?}",
8085                );
8086                assert_eq!(
8087                    b.last_missing_postcondition_kind(),
8088                    b.postconditions.last_missing_kind(),
8089                    "Boundary::last_missing_postcondition_kind must delegate verbatim to \
8090                     postconditions.last_missing_kind() for pre={pre_kind:?} post={post_kind:?}",
8091                );
8092                assert_eq!(
8093                    b.last_missing_postcondition_kind(),
8094                    b.missing_postcondition_kinds().last().copied(),
8095                    "Boundary::last_missing_postcondition_kind must equal \
8096                     missing_postcondition_kinds().last().copied() for pre={pre_kind:?} post={post_kind:?}",
8097                );
8098                let expected_union = ConditionKind::ALL
8099                    .into_iter()
8100                    .rev()
8101                    .find(|k| pre_kind != *k && post_kind != *k);
8102                assert_eq!(
8103                    b.last_missing_condition_kind(),
8104                    expected_union,
8105                    "Boundary::last_missing_condition_kind must equal latest ALL entry \
8106                     NOT populated by either half-slice for pre={pre_kind:?} post={post_kind:?}",
8107                );
8108                assert_eq!(
8109                    b.last_missing_condition_kind(),
8110                    b.missing_condition_kinds().last().copied(),
8111                    "Boundary::last_missing_condition_kind must equal \
8112                     missing_condition_kinds().last().copied() for pre={pre_kind:?} post={post_kind:?}",
8113                );
8114            }
8115        }
8116    }
8117
8118    /// SUBSTRATE-DELEGATION pin (Boundary saturation-predicate triad)
8119    /// — the three `is_*_kind_saturated` methods on [`Boundary`]
8120    /// delegate to the slice-level substrate primitive
8121    /// [`ConditionSliceExt::is_kind_saturated`] over the two
8122    /// `Vec<Condition>` slots (precondition + postcondition) and
8123    /// compose the union via `ConditionKind::ALL.iter().all(|k|
8124    /// has_condition_kind(*k))`. Sweeps the empty boundary (every arm
8125    /// returns `false`), a single-populated-per-side arrangement (both
8126    /// per-slice arms return `false` on any `N ≥ 2` closed set; the
8127    /// union returns `false` unless the two kinds are distinct AND
8128    /// `N == 2`), and the saturated boundary (both slices carry every
8129    /// [`ConditionKind`], every arm returns `true`). Also pins the
8130    /// composition law `is_*_kind_saturated() ==
8131    /// missing_*_kinds().is_empty()` at each arm — a regression that
8132    /// dropped the `all` short-circuit, drifted the walk from
8133    /// `ConditionKind::ALL`, or negated the wrong side surfaces HERE.
8134    #[test]
8135    fn is_condition_kind_saturated_triad_delegates_to_slice_is_kind_saturated() {
8136        // Empty boundary — every arm returns false; missing_*_kinds
8137        // covers the full closed set on every arm.
8138        let b = Boundary::default();
8139        assert!(
8140            !b.is_precondition_kind_saturated(),
8141            "empty boundary must return false on is_precondition_kind_saturated",
8142        );
8143        assert!(
8144            !b.is_postcondition_kind_saturated(),
8145            "empty boundary must return false on is_postcondition_kind_saturated",
8146        );
8147        assert!(
8148            !b.is_condition_kind_saturated(),
8149            "empty boundary must return false on is_condition_kind_saturated",
8150        );
8151        assert_eq!(
8152            b.is_precondition_kind_saturated(),
8153            b.missing_precondition_kinds().is_empty(),
8154            "empty is_precondition_kind_saturated must equal missing_precondition_kinds().is_empty()",
8155        );
8156
8157        // Single-populated per side — every per-slice arm returns
8158        // false on any N ≥ 2 closed set; the union returns false too
8159        // (needs every ALL kind covered).
8160        for pre_kind in ConditionKind::ALL {
8161            for post_kind in ConditionKind::ALL {
8162                let mut b = Boundary::default();
8163                b.preconditions.push(condition_with(pre_kind));
8164                b.postconditions.push(condition_with(post_kind));
8165                assert_eq!(
8166                    b.is_precondition_kind_saturated(),
8167                    b.preconditions.is_kind_saturated(),
8168                    "Boundary::is_precondition_kind_saturated must delegate verbatim to \
8169                     preconditions.is_kind_saturated() for pre={pre_kind:?} post={post_kind:?}",
8170                );
8171                assert_eq!(
8172                    b.is_postcondition_kind_saturated(),
8173                    b.postconditions.is_kind_saturated(),
8174                    "Boundary::is_postcondition_kind_saturated must delegate verbatim to \
8175                     postconditions.is_kind_saturated() for pre={pre_kind:?} post={post_kind:?}",
8176                );
8177                let expected_union = ConditionKind::ALL
8178                    .iter()
8179                    .all(|k| pre_kind == *k || post_kind == *k);
8180                assert_eq!(
8181                    b.is_condition_kind_saturated(),
8182                    expected_union,
8183                    "Boundary::is_condition_kind_saturated must equal all-ALL-covered-by-either-slice \
8184                     for pre={pre_kind:?} post={post_kind:?}",
8185                );
8186                assert_eq!(
8187                    b.is_condition_kind_saturated(),
8188                    b.missing_condition_kinds().is_empty(),
8189                    "Boundary::is_condition_kind_saturated must equal missing_condition_kinds().is_empty() \
8190                     for pre={pre_kind:?} post={post_kind:?}",
8191                );
8192            }
8193        }
8194
8195        // Saturated boundary — both slices carry every ConditionKind
8196        // at least once, every arm returns true.
8197        let mut b = Boundary::default();
8198        for k in ConditionKind::ALL {
8199            b.preconditions.push(condition_with(k));
8200            b.postconditions.push(condition_with(k));
8201        }
8202        assert!(
8203            b.is_precondition_kind_saturated(),
8204            "saturated boundary must return true on is_precondition_kind_saturated",
8205        );
8206        assert!(
8207            b.is_postcondition_kind_saturated(),
8208            "saturated boundary must return true on is_postcondition_kind_saturated",
8209        );
8210        assert!(
8211            b.is_condition_kind_saturated(),
8212            "saturated boundary must return true on is_condition_kind_saturated",
8213        );
8214    }
8215
8216    /// SUBSTRATE-DELEGATION pin (Boundary at-least-one halfspace
8217    /// triad) — the three `has_any_missing_*_condition_kind` methods
8218    /// on [`Boundary`] delegate to the slice-level substrate primitive
8219    /// [`ConditionSliceExt::has_any_missing_kind`] over the two
8220    /// `Vec<Condition>` slots (precondition + postcondition) and
8221    /// compose the union via `!self.is_condition_kind_saturated()`.
8222    /// Sweeps the empty boundary (every arm returns `true`), a single-
8223    /// populated-per-side arrangement (both per-slice arms return
8224    /// `true` on any `N ≥ 2` closed set; the union returns `true`
8225    /// unless the two kinds together cover every ALL variant), and
8226    /// the saturated boundary (both slices carry every
8227    /// [`ConditionKind`], every arm returns `false`). Also pins the
8228    /// composition law `has_any_missing_*_condition_kind() ==
8229    /// !is_*_condition_kind_saturated()` at each arm — a regression
8230    /// that dropped the negation, drifted the underlying saturation
8231    /// primitive, or negated the wrong side surfaces HERE.
8232    #[test]
8233    fn has_any_missing_condition_kind_triad_delegates_to_slice_has_any_missing_kind() {
8234        // Empty boundary — every arm returns true (every kind is
8235        // missing from every slice + from the union).
8236        let b = Boundary::default();
8237        assert!(
8238            b.has_any_missing_precondition_kind(),
8239            "empty boundary must return true on has_any_missing_precondition_kind",
8240        );
8241        assert!(
8242            b.has_any_missing_postcondition_kind(),
8243            "empty boundary must return true on has_any_missing_postcondition_kind",
8244        );
8245        assert!(
8246            b.has_any_missing_condition_kind(),
8247            "empty boundary must return true on has_any_missing_condition_kind",
8248        );
8249        assert_eq!(
8250            b.has_any_missing_condition_kind(),
8251            !b.is_condition_kind_saturated(),
8252            "empty has_any_missing_condition_kind must equal !is_condition_kind_saturated()",
8253        );
8254
8255        // Single-populated per side — sweep ALL × ALL. Every per-slice
8256        // arm returns true on any N ≥ 2 closed set; the union returns
8257        // true unless the two kinds together cover every ALL variant.
8258        for pre_kind in ConditionKind::ALL {
8259            for post_kind in ConditionKind::ALL {
8260                let mut b = Boundary::default();
8261                b.preconditions.push(condition_with(pre_kind));
8262                b.postconditions.push(condition_with(post_kind));
8263                assert_eq!(
8264                    b.has_any_missing_precondition_kind(),
8265                    b.preconditions.has_any_missing_kind(),
8266                    "Boundary::has_any_missing_precondition_kind must delegate verbatim to \
8267                     preconditions.has_any_missing_kind() for pre={pre_kind:?} post={post_kind:?}",
8268                );
8269                assert_eq!(
8270                    b.has_any_missing_postcondition_kind(),
8271                    b.postconditions.has_any_missing_kind(),
8272                    "Boundary::has_any_missing_postcondition_kind must delegate verbatim to \
8273                     postconditions.has_any_missing_kind() for pre={pre_kind:?} post={post_kind:?}",
8274                );
8275                let expected_union = !ConditionKind::ALL
8276                    .iter()
8277                    .all(|k| pre_kind == *k || post_kind == *k);
8278                assert_eq!(
8279                    b.has_any_missing_condition_kind(),
8280                    expected_union,
8281                    "Boundary::has_any_missing_condition_kind must equal \
8282                     !all-ALL-covered-by-either-slice \
8283                     for pre={pre_kind:?} post={post_kind:?}",
8284                );
8285                assert_eq!(
8286                    b.has_any_missing_condition_kind(),
8287                    !b.is_condition_kind_saturated(),
8288                    "Boundary::has_any_missing_condition_kind must equal \
8289                     !is_condition_kind_saturated() for pre={pre_kind:?} post={post_kind:?}",
8290                );
8291            }
8292        }
8293
8294        // Saturated boundary — both slices carry every ConditionKind
8295        // at least once, every arm returns false.
8296        let mut b = Boundary::default();
8297        for k in ConditionKind::ALL {
8298            b.preconditions.push(condition_with(k));
8299            b.postconditions.push(condition_with(k));
8300        }
8301        assert!(
8302            !b.has_any_missing_precondition_kind(),
8303            "saturated boundary must return false on has_any_missing_precondition_kind",
8304        );
8305        assert!(
8306            !b.has_any_missing_postcondition_kind(),
8307            "saturated boundary must return false on has_any_missing_postcondition_kind",
8308        );
8309        assert!(
8310            !b.has_any_missing_condition_kind(),
8311            "saturated boundary must return false on has_any_missing_condition_kind",
8312        );
8313    }
8314
8315    /// SUBSTRATE-DELEGATION pin (Boundary cardinality-mid-endpoint
8316    /// triad) — the three `has_unique_missing_*_condition_kind`
8317    /// methods on [`Boundary`] delegate to the slice-level substrate
8318    /// primitive [`ConditionSliceExt::has_unique_missing_kind`] over
8319    /// the two `Vec<Condition>` slots (precondition + postcondition)
8320    /// and compose the union via a two-step-short-circuit walk over
8321    /// [`ConditionKind::ALL`] under negated
8322    /// [`Boundary::has_condition_kind`]. Sweeps the empty boundary
8323    /// (every arm returns `false` — all N missing, not exactly 1),
8324    /// the near-saturation-endpoint (each slice carries every
8325    /// [`ConditionKind`] except one — every per-slice arm returns
8326    /// `true`; the union returns `true` iff BOTH slices omit the SAME
8327    /// kind), the saturated boundary (every arm returns `false` — 0
8328    /// missing), and a single-populated-per-side arrangement (every
8329    /// per-slice arm returns `false` on any `N ≥ 3` closed set; the
8330    /// union returns `true` only when the two kinds together leave
8331    /// exactly one kind uncovered). Also pins the composition law
8332    /// `has_unique_missing_*_condition_kind() ==
8333    /// (missing_*_condition_kind_count() == 1)` at each arm — a
8334    /// regression that dropped the second-slot short-circuit, drifted
8335    /// the underlying `has_kind` predicate, or conflated with
8336    /// `is_kind_saturated` surfaces HERE.
8337    #[test]
8338    fn has_unique_missing_condition_kind_triad_delegates_to_slice_has_unique_missing_kind() {
8339        // Empty boundary — every arm returns false (all N missing,
8340        // not exactly 1) on any N ≥ 2 closed set.
8341        assert!(
8342            ConditionKind::ALL.len() >= 2,
8343            "test assumes ConditionKind::ALL has ≥ 2 variants",
8344        );
8345        let b = Boundary::default();
8346        assert!(
8347            !b.has_unique_missing_precondition_kind(),
8348            "empty boundary must return false on has_unique_missing_precondition_kind",
8349        );
8350        assert!(
8351            !b.has_unique_missing_postcondition_kind(),
8352            "empty boundary must return false on has_unique_missing_postcondition_kind",
8353        );
8354        assert!(
8355            !b.has_unique_missing_condition_kind(),
8356            "empty boundary must return false on has_unique_missing_condition_kind",
8357        );
8358        assert_eq!(
8359            b.has_unique_missing_condition_kind(),
8360            b.missing_condition_kind_count() == 1,
8361            "empty has_unique_missing_condition_kind must equal (missing_condition_kind_count() == 1)",
8362        );
8363
8364        // Single-populated per side — sweep ALL × ALL on N ≥ 3 closed
8365        // sets. Every per-slice arm returns false (N - 1 ≥ 2 kinds
8366        // missing per slice); the union returns true iff the two kinds
8367        // together leave exactly one ALL variant uncovered.
8368        if ConditionKind::ALL.len() >= 3 {
8369            for pre_kind in ConditionKind::ALL {
8370                for post_kind in ConditionKind::ALL {
8371                    let mut b = Boundary::default();
8372                    b.preconditions.push(condition_with(pre_kind));
8373                    b.postconditions.push(condition_with(post_kind));
8374                    assert_eq!(
8375                        b.has_unique_missing_precondition_kind(),
8376                        b.preconditions.has_unique_missing_kind(),
8377                        "Boundary::has_unique_missing_precondition_kind must delegate verbatim to \
8378                         preconditions.has_unique_missing_kind() for pre={pre_kind:?} post={post_kind:?}",
8379                    );
8380                    assert_eq!(
8381                        b.has_unique_missing_postcondition_kind(),
8382                        b.postconditions.has_unique_missing_kind(),
8383                        "Boundary::has_unique_missing_postcondition_kind must delegate verbatim to \
8384                         postconditions.has_unique_missing_kind() for pre={pre_kind:?} post={post_kind:?}",
8385                    );
8386                    let uncovered = ConditionKind::ALL
8387                        .into_iter()
8388                        .filter(|k| *k != pre_kind && *k != post_kind)
8389                        .count();
8390                    let expected_union = uncovered == 1;
8391                    assert_eq!(
8392                        b.has_unique_missing_condition_kind(),
8393                        expected_union,
8394                        "Boundary::has_unique_missing_condition_kind must equal \
8395                         (uncovered-ALL-count == 1) for pre={pre_kind:?} post={post_kind:?}",
8396                    );
8397                    assert_eq!(
8398                        b.has_unique_missing_condition_kind(),
8399                        b.missing_condition_kind_count() == 1,
8400                        "Boundary::has_unique_missing_condition_kind must equal \
8401                         (missing_condition_kind_count() == 1) for pre={pre_kind:?} post={post_kind:?}",
8402                    );
8403                }
8404            }
8405        }
8406
8407        // Near-saturation-endpoint per side — each slice carries
8408        // every ConditionKind except one; every per-slice arm returns
8409        // true. The union returns true iff BOTH slices omit the SAME
8410        // kind (otherwise the two omissions are covered by each
8411        // other and the union is saturated).
8412        for pre_omit in ConditionKind::ALL {
8413            for post_omit in ConditionKind::ALL {
8414                let mut b = Boundary::default();
8415                for k in ConditionKind::ALL {
8416                    if k != pre_omit {
8417                        b.preconditions.push(condition_with(k));
8418                    }
8419                    if k != post_omit {
8420                        b.postconditions.push(condition_with(k));
8421                    }
8422                }
8423                assert!(
8424                    b.has_unique_missing_precondition_kind(),
8425                    "near-saturation-endpoint precondition slice (omitting {pre_omit:?}) must return true on has_unique_missing_precondition_kind",
8426                );
8427                assert!(
8428                    b.has_unique_missing_postcondition_kind(),
8429                    "near-saturation-endpoint postcondition slice (omitting {post_omit:?}) must return true on has_unique_missing_postcondition_kind",
8430                );
8431                let expected_union = pre_omit == post_omit;
8432                assert_eq!(
8433                    b.has_unique_missing_condition_kind(),
8434                    expected_union,
8435                    "Boundary::has_unique_missing_condition_kind on both-slices-near-saturated must equal (pre_omit == post_omit) for pre_omit={pre_omit:?} post_omit={post_omit:?}",
8436                );
8437                assert_eq!(
8438                    b.has_unique_missing_condition_kind(),
8439                    b.missing_condition_kind_count() == 1,
8440                    "Boundary::has_unique_missing_condition_kind must equal (missing_condition_kind_count() == 1) for pre_omit={pre_omit:?} post_omit={post_omit:?}",
8441                );
8442            }
8443        }
8444
8445        // Saturated boundary — every arm returns false (0 missing,
8446        // not exactly 1).
8447        let mut b = Boundary::default();
8448        for k in ConditionKind::ALL {
8449            b.preconditions.push(condition_with(k));
8450            b.postconditions.push(condition_with(k));
8451        }
8452        assert!(
8453            !b.has_unique_missing_precondition_kind(),
8454            "saturated boundary must return false on has_unique_missing_precondition_kind",
8455        );
8456        assert!(
8457            !b.has_unique_missing_postcondition_kind(),
8458            "saturated boundary must return false on has_unique_missing_postcondition_kind",
8459        );
8460        assert!(
8461            !b.has_unique_missing_condition_kind(),
8462            "saturated boundary must return false on has_unique_missing_condition_kind",
8463        );
8464    }
8465
8466    /// SUBSTRATE-DELEGATION pin (Boundary cardinality-many-arm triad)
8467    /// — the three `has_multiple_missing_*_condition_kind` methods on
8468    /// [`Boundary`] delegate to the slice-level substrate primitive
8469    /// [`ConditionSliceExt::has_multiple_missing_kinds`] over the two
8470    /// `Vec<Condition>` slots (precondition + postcondition) and
8471    /// compose the union via a two-step-short-circuit walk over
8472    /// [`ConditionKind::ALL`] under negated
8473    /// [`Boundary::has_condition_kind`]. Sweeps the empty boundary
8474    /// (every arm returns `true` — all N missing, ≥ 2), the near-
8475    /// saturation-endpoint (each slice carries every
8476    /// [`ConditionKind`] except one — every per-slice arm returns
8477    /// `false`; the union returns `true` iff the two slices omit
8478    /// DIFFERENT kinds), the saturated boundary (every arm returns
8479    /// `false` — 0 missing), and a single-populated-per-side
8480    /// arrangement (every per-slice arm returns `true` on any `N ≥ 3`
8481    /// closed set; the union returns `true` when the two kinds
8482    /// together leave ≥ 2 kinds uncovered). Also pins the composition
8483    /// law `has_multiple_missing_*_condition_kind() ==
8484    /// (missing_*_condition_kind_count() >= 2)` at each arm — a
8485    /// regression that dropped the second-slot short-circuit, drifted
8486    /// the underlying `has_kind` predicate, or conflated with
8487    /// `has_any_missing_kind` surfaces HERE.
8488    #[test]
8489    fn has_multiple_missing_condition_kind_triad_delegates_to_slice_has_multiple_missing_kinds() {
8490        // Empty boundary — every arm returns true (all N missing,
8491        // ≥ 2) on any N ≥ 2 closed set.
8492        assert!(
8493            ConditionKind::ALL.len() >= 2,
8494            "test assumes ConditionKind::ALL has ≥ 2 variants",
8495        );
8496        let b = Boundary::default();
8497        assert!(
8498            b.has_multiple_missing_precondition_kind(),
8499            "empty boundary must return true on has_multiple_missing_precondition_kind",
8500        );
8501        assert!(
8502            b.has_multiple_missing_postcondition_kind(),
8503            "empty boundary must return true on has_multiple_missing_postcondition_kind",
8504        );
8505        assert!(
8506            b.has_multiple_missing_condition_kind(),
8507            "empty boundary must return true on has_multiple_missing_condition_kind",
8508        );
8509        assert_eq!(
8510            b.has_multiple_missing_condition_kind(),
8511            b.missing_condition_kind_count() >= 2,
8512            "empty has_multiple_missing_condition_kind must equal (missing_condition_kind_count() >= 2)",
8513        );
8514
8515        // Single-populated per side — sweep ALL × ALL on N ≥ 3 closed
8516        // sets. Every per-slice arm returns true (N - 1 ≥ 2 kinds
8517        // missing per slice); the union returns true iff the two
8518        // kinds together leave ≥ 2 ALL variants uncovered.
8519        if ConditionKind::ALL.len() >= 3 {
8520            for pre_kind in ConditionKind::ALL {
8521                for post_kind in ConditionKind::ALL {
8522                    let mut b = Boundary::default();
8523                    b.preconditions.push(condition_with(pre_kind));
8524                    b.postconditions.push(condition_with(post_kind));
8525                    assert_eq!(
8526                        b.has_multiple_missing_precondition_kind(),
8527                        b.preconditions.has_multiple_missing_kinds(),
8528                        "Boundary::has_multiple_missing_precondition_kind must delegate verbatim to \
8529                         preconditions.has_multiple_missing_kinds() for pre={pre_kind:?} post={post_kind:?}",
8530                    );
8531                    assert_eq!(
8532                        b.has_multiple_missing_postcondition_kind(),
8533                        b.postconditions.has_multiple_missing_kinds(),
8534                        "Boundary::has_multiple_missing_postcondition_kind must delegate verbatim to \
8535                         postconditions.has_multiple_missing_kinds() for pre={pre_kind:?} post={post_kind:?}",
8536                    );
8537                    let uncovered = ConditionKind::ALL
8538                        .into_iter()
8539                        .filter(|k| *k != pre_kind && *k != post_kind)
8540                        .count();
8541                    let expected_union = uncovered >= 2;
8542                    assert_eq!(
8543                        b.has_multiple_missing_condition_kind(),
8544                        expected_union,
8545                        "Boundary::has_multiple_missing_condition_kind must equal \
8546                         (uncovered-ALL-count >= 2) for pre={pre_kind:?} post={post_kind:?}",
8547                    );
8548                    assert_eq!(
8549                        b.has_multiple_missing_condition_kind(),
8550                        b.missing_condition_kind_count() >= 2,
8551                        "Boundary::has_multiple_missing_condition_kind must equal \
8552                         (missing_condition_kind_count() >= 2) for pre={pre_kind:?} post={post_kind:?}",
8553                    );
8554                }
8555            }
8556        }
8557
8558        // Near-saturation-endpoint per side — each slice carries
8559        // every ConditionKind except one; every per-slice arm returns
8560        // false (exactly 1 missing per slice, not ≥ 2). The union
8561        // returns true iff the two slices omit DIFFERENT kinds
8562        // (otherwise both omissions coincide and the union has
8563        // exactly 1 missing, not ≥ 2).
8564        for pre_omit in ConditionKind::ALL {
8565            for post_omit in ConditionKind::ALL {
8566                let mut b = Boundary::default();
8567                for k in ConditionKind::ALL {
8568                    if k != pre_omit {
8569                        b.preconditions.push(condition_with(k));
8570                    }
8571                    if k != post_omit {
8572                        b.postconditions.push(condition_with(k));
8573                    }
8574                }
8575                assert!(
8576                    !b.has_multiple_missing_precondition_kind(),
8577                    "near-saturation-endpoint precondition slice (omitting {pre_omit:?}) must return false on has_multiple_missing_precondition_kind",
8578                );
8579                assert!(
8580                    !b.has_multiple_missing_postcondition_kind(),
8581                    "near-saturation-endpoint postcondition slice (omitting {post_omit:?}) must return false on has_multiple_missing_postcondition_kind",
8582                );
8583                // Union: pre-only-missing = {pre_omit}, post-only-
8584                // missing = {post_omit}. Union missing = both
8585                // omissions ∩ each other only when they coincide.
8586                let expected_union = false;
8587                assert_eq!(
8588                    b.has_multiple_missing_condition_kind(),
8589                    expected_union,
8590                    "Boundary::has_multiple_missing_condition_kind on both-slices-near-saturated must always be false (union missing ≤ 1) for pre_omit={pre_omit:?} post_omit={post_omit:?}",
8591                );
8592                assert_eq!(
8593                    b.has_multiple_missing_condition_kind(),
8594                    b.missing_condition_kind_count() >= 2,
8595                    "Boundary::has_multiple_missing_condition_kind must equal (missing_condition_kind_count() >= 2) for pre_omit={pre_omit:?} post_omit={post_omit:?}",
8596                );
8597            }
8598        }
8599
8600        // Saturated boundary — every arm returns false (0 missing,
8601        // not ≥ 2).
8602        let mut b = Boundary::default();
8603        for k in ConditionKind::ALL {
8604            b.preconditions.push(condition_with(k));
8605            b.postconditions.push(condition_with(k));
8606        }
8607        assert!(
8608            !b.has_multiple_missing_precondition_kind(),
8609            "saturated boundary must return false on has_multiple_missing_precondition_kind",
8610        );
8611        assert!(
8612            !b.has_multiple_missing_postcondition_kind(),
8613            "saturated boundary must return false on has_multiple_missing_postcondition_kind",
8614        );
8615        assert!(
8616            !b.has_multiple_missing_condition_kind(),
8617            "saturated boundary must return false on has_multiple_missing_condition_kind",
8618        );
8619    }
8620
8621    /// SUBSTRATE-DELEGATION pin (Boundary cardinality "≤ 1" triad) —
8622    /// the three `has_at_most_one_missing_*_condition_kind` methods on
8623    /// [`Boundary`] delegate to the slice-level substrate primitive
8624    /// [`ConditionSliceExt::has_at_most_one_missing_kind`] over the
8625    /// two `Vec<Condition>` slots (precondition + postcondition) and
8626    /// compose the union via
8627    /// `!self.has_multiple_missing_condition_kind()` — a definitional
8628    /// negation of the many-arm union primitive. Sweeps the empty
8629    /// boundary (every arm returns `false` — `N ≥ 2` missing, not
8630    /// `≤ 1`), the near-saturation-endpoint (each slice carries
8631    /// every [`ConditionKind`] except one — every per-slice arm
8632    /// returns `true`; the union returns `true` — since the union of
8633    /// two near-saturated slices always has `≤ 1` missing), the
8634    /// saturated boundary (every arm returns `true` — 0 missing,
8635    /// `≤ 1`), and a single-populated-per-side arrangement (every
8636    /// per-slice arm returns `false` on any `N ≥ 3` closed set; the
8637    /// union returns `true` iff the two kinds together leave `≤ 1`
8638    /// kind uncovered — the near-saturation-endpoint of the union
8639    /// axis). Also pins the composition law
8640    /// `has_at_most_one_missing_*_condition_kind() ==
8641    /// (missing_*_condition_kind_count() <= 1)` at each arm — a
8642    /// regression that dropped the definitional negation (returning
8643    /// `has_multiple_missing_condition_kind` itself), swapped the
8644    /// wrong side, or drifted the trichotomy union operator from
8645    /// `||` to `&&` surfaces HERE.
8646    #[test]
8647    fn has_at_most_one_missing_condition_kind_triad_delegates_to_slice_has_at_most_one_missing_kind(
8648    ) {
8649        // Empty boundary — every arm returns false (all N missing,
8650        // not ≤ 1) on any N ≥ 2 closed set.
8651        assert!(
8652            ConditionKind::ALL.len() >= 2,
8653            "test assumes ConditionKind::ALL has ≥ 2 variants",
8654        );
8655        let b = Boundary::default();
8656        assert!(
8657            !b.has_at_most_one_missing_precondition_kind(),
8658            "empty boundary must return false on has_at_most_one_missing_precondition_kind",
8659        );
8660        assert!(
8661            !b.has_at_most_one_missing_postcondition_kind(),
8662            "empty boundary must return false on has_at_most_one_missing_postcondition_kind",
8663        );
8664        assert!(
8665            !b.has_at_most_one_missing_condition_kind(),
8666            "empty boundary must return false on has_at_most_one_missing_condition_kind",
8667        );
8668        assert_eq!(
8669            b.has_at_most_one_missing_condition_kind(),
8670            b.missing_condition_kind_count() <= 1,
8671            "empty has_at_most_one_missing_condition_kind must equal (missing_condition_kind_count() <= 1)",
8672        );
8673
8674        // Single-populated per side — sweep ALL × ALL on N ≥ 3
8675        // closed sets. Every per-slice arm returns false (N - 1 ≥ 2
8676        // kinds missing per slice, not ≤ 1); the union returns true
8677        // iff the two kinds together leave ≤ 1 ALL variant
8678        // uncovered — the near-saturation-endpoint of the union
8679        // axis.
8680        if ConditionKind::ALL.len() >= 3 {
8681            for pre_kind in ConditionKind::ALL {
8682                for post_kind in ConditionKind::ALL {
8683                    let mut b = Boundary::default();
8684                    b.preconditions.push(condition_with(pre_kind));
8685                    b.postconditions.push(condition_with(post_kind));
8686                    assert_eq!(
8687                        b.has_at_most_one_missing_precondition_kind(),
8688                        b.preconditions.has_at_most_one_missing_kind(),
8689                        "Boundary::has_at_most_one_missing_precondition_kind must delegate verbatim to \
8690                         preconditions.has_at_most_one_missing_kind() for pre={pre_kind:?} post={post_kind:?}",
8691                    );
8692                    assert_eq!(
8693                        b.has_at_most_one_missing_postcondition_kind(),
8694                        b.postconditions.has_at_most_one_missing_kind(),
8695                        "Boundary::has_at_most_one_missing_postcondition_kind must delegate verbatim to \
8696                         postconditions.has_at_most_one_missing_kind() for pre={pre_kind:?} post={post_kind:?}",
8697                    );
8698                    let uncovered = ConditionKind::ALL
8699                        .into_iter()
8700                        .filter(|k| *k != pre_kind && *k != post_kind)
8701                        .count();
8702                    let expected_union = uncovered <= 1;
8703                    assert_eq!(
8704                        b.has_at_most_one_missing_condition_kind(),
8705                        expected_union,
8706                        "Boundary::has_at_most_one_missing_condition_kind must equal \
8707                         (uncovered-ALL-count <= 1) for pre={pre_kind:?} post={post_kind:?}",
8708                    );
8709                    assert_eq!(
8710                        b.has_at_most_one_missing_condition_kind(),
8711                        !b.has_multiple_missing_condition_kind(),
8712                        "Boundary::has_at_most_one_missing_condition_kind must equal \
8713                         !has_multiple_missing_condition_kind() for pre={pre_kind:?} post={post_kind:?}",
8714                    );
8715                    assert_eq!(
8716                        b.has_at_most_one_missing_condition_kind(),
8717                        b.missing_condition_kind_count() <= 1,
8718                        "Boundary::has_at_most_one_missing_condition_kind must equal \
8719                         (missing_condition_kind_count() <= 1) for pre={pre_kind:?} post={post_kind:?}",
8720                    );
8721                }
8722            }
8723        }
8724
8725        // Near-saturation-endpoint per side — each slice carries
8726        // every ConditionKind except one; every per-slice arm returns
8727        // true (exactly 1 missing per slice, ≤ 1). The union has ≤ 1
8728        // missing whether or not the two omissions coincide, so the
8729        // union is always true on this arm.
8730        for pre_omit in ConditionKind::ALL {
8731            for post_omit in ConditionKind::ALL {
8732                let mut b = Boundary::default();
8733                for k in ConditionKind::ALL {
8734                    if k != pre_omit {
8735                        b.preconditions.push(condition_with(k));
8736                    }
8737                    if k != post_omit {
8738                        b.postconditions.push(condition_with(k));
8739                    }
8740                }
8741                assert!(
8742                    b.has_at_most_one_missing_precondition_kind(),
8743                    "near-saturation-endpoint precondition slice (omitting {pre_omit:?}) must return true on has_at_most_one_missing_precondition_kind",
8744                );
8745                assert!(
8746                    b.has_at_most_one_missing_postcondition_kind(),
8747                    "near-saturation-endpoint postcondition slice (omitting {post_omit:?}) must return true on has_at_most_one_missing_postcondition_kind",
8748                );
8749                assert!(
8750                    b.has_at_most_one_missing_condition_kind(),
8751                    "Boundary::has_at_most_one_missing_condition_kind on both-slices-near-saturated must always be true (union missing ≤ 1) for pre_omit={pre_omit:?} post_omit={post_omit:?}",
8752                );
8753                assert_eq!(
8754                    b.has_at_most_one_missing_condition_kind(),
8755                    b.missing_condition_kind_count() <= 1,
8756                    "Boundary::has_at_most_one_missing_condition_kind must equal (missing_condition_kind_count() <= 1) for pre_omit={pre_omit:?} post_omit={post_omit:?}",
8757                );
8758            }
8759        }
8760
8761        // Saturated boundary — every arm returns true (0 missing,
8762        // ≤ 1).
8763        let mut b = Boundary::default();
8764        for k in ConditionKind::ALL {
8765            b.preconditions.push(condition_with(k));
8766            b.postconditions.push(condition_with(k));
8767        }
8768        assert!(
8769            b.has_at_most_one_missing_precondition_kind(),
8770            "saturated boundary must return true on has_at_most_one_missing_precondition_kind",
8771        );
8772        assert!(
8773            b.has_at_most_one_missing_postcondition_kind(),
8774            "saturated boundary must return true on has_at_most_one_missing_postcondition_kind",
8775        );
8776        assert!(
8777            b.has_at_most_one_missing_condition_kind(),
8778            "saturated boundary must return true on has_at_most_one_missing_condition_kind",
8779        );
8780    }
8781
8782    /// SUBSTRATE-DELEGATION pin (Boundary per-kind-complement triad) —
8783    /// the three `lacks_*_condition_kind` methods on [`Boundary`]
8784    /// delegate to the slice-level substrate primitive
8785    /// [`ConditionSliceExt::lacks_kind`] over the two `Vec<Condition>`
8786    /// slots (precondition + postcondition) and compose the union via
8787    /// `!self.has_condition_kind(kind)`. Sweeps the empty boundary
8788    /// (every arm returns `true` for every kind), a single-populated-
8789    /// per-side arrangement (per-slice arms return `false` on the
8790    /// populated kind + `true` on every other kind; the union returns
8791    /// `false` iff EITHER slice populates the addressed kind), and the
8792    /// saturated boundary (both slices carry every [`ConditionKind`],
8793    /// every arm returns `false` for every kind). Also pins the
8794    /// composition laws `lacks_*_condition_kind(k) ==
8795    /// !has_*_condition_kind(k)` at each arm AND `lacks_condition_kind(k)
8796    /// == lacks_precondition_kind(k) && lacks_postcondition_kind(k)`
8797    /// (the union AND-composition dual of `has`'s OR-composition) — a
8798    /// regression that dropped the negation, drifted the union operator
8799    /// to `||`, or negated the wrong side surfaces HERE.
8800    #[test]
8801    fn lacks_condition_kind_triad_delegates_to_slice_lacks_kind() {
8802        // Empty boundary — every arm returns true on every kind.
8803        let b = Boundary::default();
8804        for kind in ConditionKind::ALL {
8805            assert!(
8806                b.lacks_precondition_kind(kind),
8807                "empty boundary must return true on lacks_precondition_kind for {kind:?}",
8808            );
8809            assert!(
8810                b.lacks_postcondition_kind(kind),
8811                "empty boundary must return true on lacks_postcondition_kind for {kind:?}",
8812            );
8813            assert!(
8814                b.lacks_condition_kind(kind),
8815                "empty boundary must return true on lacks_condition_kind for {kind:?}",
8816            );
8817            assert_eq!(
8818                b.lacks_condition_kind(kind),
8819                !b.has_condition_kind(kind),
8820                "empty lacks_condition_kind must equal !has_condition_kind for {kind:?}",
8821            );
8822        }
8823
8824        // Single-populated per side — sweep ALL × ALL, then probe every
8825        // ConditionKind on the (pre, post, union) triad.
8826        for pre_kind in ConditionKind::ALL {
8827            for post_kind in ConditionKind::ALL {
8828                let mut b = Boundary::default();
8829                b.preconditions.push(condition_with(pre_kind));
8830                b.postconditions.push(condition_with(post_kind));
8831                for probe in ConditionKind::ALL {
8832                    assert_eq!(
8833                        b.lacks_precondition_kind(probe),
8834                        b.preconditions.lacks_kind(probe),
8835                        "Boundary::lacks_precondition_kind must delegate verbatim to preconditions.lacks_kind for pre={pre_kind:?} post={post_kind:?} probe={probe:?}",
8836                    );
8837                    assert_eq!(
8838                        b.lacks_postcondition_kind(probe),
8839                        b.postconditions.lacks_kind(probe),
8840                        "Boundary::lacks_postcondition_kind must delegate verbatim to postconditions.lacks_kind for pre={pre_kind:?} post={post_kind:?} probe={probe:?}",
8841                    );
8842                    let expected_union = pre_kind != probe && post_kind != probe;
8843                    assert_eq!(
8844                        b.lacks_condition_kind(probe),
8845                        expected_union,
8846                        "Boundary::lacks_condition_kind must equal all-ALL-absent-in-both-slices for pre={pre_kind:?} post={post_kind:?} probe={probe:?}",
8847                    );
8848                    assert_eq!(
8849                        b.lacks_condition_kind(probe),
8850                        !b.has_condition_kind(probe),
8851                        "Boundary::lacks_condition_kind must equal !has_condition_kind for pre={pre_kind:?} post={post_kind:?} probe={probe:?}",
8852                    );
8853                    assert_eq!(
8854                        b.lacks_condition_kind(probe),
8855                        b.lacks_precondition_kind(probe)
8856                            && b.lacks_postcondition_kind(probe),
8857                        "Boundary::lacks_condition_kind must equal AND-of-half-slice-arms for pre={pre_kind:?} post={post_kind:?} probe={probe:?}",
8858                    );
8859                }
8860            }
8861        }
8862
8863        // Saturated boundary — both slices carry every ConditionKind,
8864        // every arm returns false on every kind.
8865        let mut b = Boundary::default();
8866        for k in ConditionKind::ALL {
8867            b.preconditions.push(condition_with(k));
8868            b.postconditions.push(condition_with(k));
8869        }
8870        for kind in ConditionKind::ALL {
8871            assert!(
8872                !b.lacks_precondition_kind(kind),
8873                "saturated boundary must return false on lacks_precondition_kind for {kind:?}",
8874            );
8875            assert!(
8876                !b.lacks_postcondition_kind(kind),
8877                "saturated boundary must return false on lacks_postcondition_kind for {kind:?}",
8878            );
8879            assert!(
8880                !b.lacks_condition_kind(kind),
8881                "saturated boundary must return false on lacks_condition_kind for {kind:?}",
8882            );
8883        }
8884    }
8885
8886    // ── assert_slice_refinement_composition_laws — substrate testkit ──
8887    //
8888    // The substrate testkit primitive
8889    // [`assert_slice_refinement_composition_laws`] pins the FOUR
8890    // composition laws that bind the [`ConditionSliceExt`] refinement
8891    // algebra (find ↔ iter, count ↔ iter, has ↔ find, has ↔ count) at
8892    // ONE call site per authored arrangement, sweeping
8893    // [`ConditionKind::ALL`]. The four hand-authored slice-level
8894    // composition-law tests above
8895    // (`condition_slice_find_kind_equals_iter_kind_next`,
8896    // `condition_slice_count_kind_equals_iter_kind_count`,
8897    // `condition_slice_has_kind_equals_find_kind_is_some`,
8898    // `condition_slice_has_and_find_equal_count_greater_than_zero`)
8899    // stay as first-class per-law drift-arm pins; this substrate
8900    // testkit is the compound-lift primitive that binds all four
8901    // laws through ONE typed sweep so a future FIFTH refinement's
8902    // composition law picks up its pin as ONE new arm inside the
8903    // primitive's body rather than as ONE new sibling test at every
8904    // downstream author-time enumeration.
8905
8906    /// SUBSTRATE PANEL pin — the substrate testkit primitive
8907    /// [`assert_slice_refinement_composition_laws`] passes on the
8908    /// FOUR canonical authored arrangements the trait's downstream
8909    /// consumers reach for: the empty slice (every refinement returns
8910    /// its zero-element identity), a single-element populated slice
8911    /// (every refinement returns the addressed match's projection),
8912    /// a dual-populated slice with distinct kinds (every refinement
8913    /// probes the kind field per element), and a duplicate-populated
8914    /// slice with the same kind at multiple positions (the widened
8915    /// primitive `iter_kind` yields every match; `find_kind` collapses
8916    /// to the first; `count_kind` returns the exact cardinality;
8917    /// `has_kind` returns true). Sweeping the four arrangements at
8918    /// ONE call site pins that every composition law holds regardless
8919    /// of the widened primitive's yield structure.
8920    #[test]
8921    fn slice_refinement_composition_laws_hold_across_authored_arrangements() {
8922        let empty: &[Condition] = &[];
8923        assert_slice_refinement_composition_laws(empty);
8924
8925        for populated in ConditionKind::ALL {
8926            let single = [condition_with(populated)];
8927            assert_slice_refinement_composition_laws(single.as_slice());
8928        }
8929
8930        for pre_kind in ConditionKind::ALL {
8931            for post_kind in ConditionKind::ALL {
8932                let dual = [condition_with(pre_kind), condition_with(post_kind)];
8933                assert_slice_refinement_composition_laws(dual.as_slice());
8934            }
8935        }
8936
8937        for populated in ConditionKind::ALL {
8938            let duplicates = [
8939                condition_with(populated),
8940                condition_with(populated),
8941                condition_with(populated),
8942            ];
8943            assert_slice_refinement_composition_laws(duplicates.as_slice());
8944        }
8945    }
8946
8947    /// SUBSTRATE PANEL pin (params-distinguishable duplicates) — the
8948    /// substrate primitive holds on a slice that carries duplicate
8949    /// kinds interleaved with a distinct kind, byte-for-byte peer of
8950    /// the standalone `condition_slice_iter_kind_yields_every_match_in_slice_order_on_duplicates`
8951    /// / `condition_slice_count_kind_counts_every_match_on_duplicates`
8952    /// arrangement. Confirms the four composition laws hold when
8953    /// the widened primitive's yield stream is genuinely multi-element
8954    /// AND the addressed kind is interleaved with a non-matching kind
8955    /// (the union structural case that the diagonal-and-corners sweep
8956    /// above doesn't reach).
8957    #[test]
8958    fn slice_refinement_composition_laws_hold_on_interleaved_duplicates() {
8959        let interleaved = [
8960            Condition {
8961                kind: ConditionKind::ClosedLoopAuth,
8962                params: json!({ "probeImage": "first" }),
8963            },
8964            Condition {
8965                kind: ConditionKind::PromQL,
8966                params: json!({ "query": "up" }),
8967            },
8968            Condition {
8969                kind: ConditionKind::ClosedLoopAuth,
8970                params: json!({ "probeImage": "second" }),
8971            },
8972            Condition {
8973                kind: ConditionKind::PromQL,
8974                params: json!({ "query": "healthy" }),
8975            },
8976            Condition {
8977                kind: ConditionKind::ClosedLoopAuth,
8978                params: json!({ "probeImage": "third" }),
8979            },
8980        ];
8981        assert_slice_refinement_composition_laws(interleaved.as_slice());
8982    }
8983
8984    // ── assert_surface_union_composition_laws — substrate testkit ────
8985    //
8986    // The substrate testkit macro
8987    // [`crate::assert_surface_union_composition_laws`] pins the FOUR
8988    // union composition laws (has: OR, find: or_else, iter: chain,
8989    // count: SUM) that bind the (pre, post, union) refinement triads
8990    // on the [`Boundary`] surface at ONE call site per authored
8991    // arrangement, sweeping [`ConditionKind::ALL`]. The four hand-
8992    // authored point-surface composition-law tests above
8993    // (`boundary_has_condition_kind_composes_precondition_and_postcondition_arms`,
8994    // `find_condition_kind_triad_delegates_to_slice_find_kind`,
8995    // `iter_condition_kind_triad_delegates_to_slice_iter_kind`,
8996    // `boundary_count_condition_kind_triad_delegates_and_sums_slice_count_kind`)
8997    // stay as first-class per-law drift-arm pins; this substrate
8998    // testkit macro is the compound-lift primitive that binds all
8999    // four union composition laws through ONE typed sweep so a
9000    // future FIFTH union refinement picks up its composition-law
9001    // pin as ONE new arm inside the macro body rather than as ONE
9002    // new sibling test at every downstream author-time
9003    // enumeration on each of the two surfaces.
9004
9005    /// SUBSTRATE PANEL pin — the substrate testkit macro
9006    /// [`crate::assert_surface_union_composition_laws`] passes on
9007    /// [`Boundary`] for the four canonical authored arrangements the
9008    /// surface's downstream consumers reach for: the empty boundary
9009    /// (every union arm returns its zero-element identity), a
9010    /// precondition-only populated boundary (every union arm equals
9011    /// its precondition arm, postcondition arm is empty), a
9012    /// postcondition-only populated boundary (mirror), and a dual-
9013    /// populated boundary sweeping `ALL × ALL` (both half-slice arms
9014    /// contribute; the union monoid operator applies). Sweeping the
9015    /// four arrangements at ONE call site pins every union
9016    /// composition law holds regardless of the arrangement's per-
9017    /// half fill pattern.
9018    #[test]
9019    fn boundary_surface_union_composition_laws_hold_across_authored_arrangements() {
9020        let empty = Boundary::default();
9021        crate::assert_surface_union_composition_laws!(empty);
9022
9023        for populated in ConditionKind::ALL {
9024            let mut pre_only = Boundary::default();
9025            pre_only.preconditions.push(condition_with(populated));
9026            crate::assert_surface_union_composition_laws!(pre_only);
9027
9028            let mut post_only = Boundary::default();
9029            post_only.postconditions.push(condition_with(populated));
9030            crate::assert_surface_union_composition_laws!(post_only);
9031        }
9032
9033        for pre_kind in ConditionKind::ALL {
9034            for post_kind in ConditionKind::ALL {
9035                let mut dual = Boundary::default();
9036                dual.preconditions.push(condition_with(pre_kind));
9037                dual.postconditions.push(condition_with(post_kind));
9038                crate::assert_surface_union_composition_laws!(dual);
9039            }
9040        }
9041    }
9042
9043    /// SUBSTRATE PANEL pin (params-distinguishable duplicates) — the
9044    /// substrate macro holds on a [`Boundary`] whose two half-slices
9045    /// each carry duplicates of the same kind at multiple positions,
9046    /// interleaved with a distinct kind. The scenario reaches every
9047    /// union arm at its non-degenerate composition: `has` still
9048    /// resolves `true` on both halves (OR is not the discriminating
9049    /// bit), `find` yields the FIRST-precondition-side match
9050    /// (`or_else` walk order), `iter` yields every match with the
9051    /// full pre-then-post chain order (five total matches across the
9052    /// two halves), `count` returns the SUM (five). A regression that
9053    /// (a) collapsed `find`'s `or_else` to `and_then` (silently
9054    /// narrowing to intersection), (b) collapsed `iter`'s `chain` to
9055    /// `zip` (silently truncating to `min(pre, post)`), or (c)
9056    /// collapsed `count`'s SUM to `max` (silently narrowing the
9057    /// cardinality) surfaces HERE — the four laws are pinned
9058    /// simultaneously and any single-arm regression fails one of
9059    /// the four asserts.
9060    #[test]
9061    fn boundary_surface_union_composition_laws_hold_on_interleaved_duplicates() {
9062        let mut b = Boundary::default();
9063        b.preconditions.push(Condition {
9064            kind: ConditionKind::ClosedLoopAuth,
9065            params: json!({ "side": "pre-1" }),
9066        });
9067        b.preconditions.push(Condition {
9068            kind: ConditionKind::PromQL,
9069            params: json!({ "query": "up" }),
9070        });
9071        b.preconditions.push(Condition {
9072            kind: ConditionKind::ClosedLoopAuth,
9073            params: json!({ "side": "pre-2" }),
9074        });
9075        b.postconditions.push(Condition {
9076            kind: ConditionKind::PromQL,
9077            params: json!({ "query": "healthy" }),
9078        });
9079        b.postconditions.push(Condition {
9080            kind: ConditionKind::ClosedLoopAuth,
9081            params: json!({ "side": "post-1" }),
9082        });
9083        crate::assert_surface_union_composition_laws!(b);
9084    }
9085}